[Matrix Multiplication] [SSL 1529] Fibonacci Sequence Ⅱ
topic
Shaped like 1,123,581,321,345,589,144 ... number of columns, the number of columns required Pei Bo Laqi of nnn items.
enter
n n n (1〈 n n n 〈2 ^ 31)
Output
A number of series of Pei Bola Qi nnn itemsmod modmod 10000;
Sample
input
123456789
output
4514
Problem-solving ideas
Matrix multiplication
Two matrices AAA, B B B multiplied by
tm tmThe length of the product of t m isAAA 's length and width areBBWideAA of B
The sum of the product of the number in the first row of A multiplied by the number in the first column of B is the number in the first row and first column of the product
.
The writing method of this question is
given that f [n] = f [n − 1] + f [n − 2] f[n]=f[n-1]+f[n-2]f[n]=f[n−1]+f[n−2 ]
If you requiref [n + 1] f[n+1]f[n+1]
即 f [ n + 1 ] = f [ n ] + f [ n − 1 ] f[n+1]=f[n]+f[n-1] f[n+1]=f[n]+f[n−1 ]
Expandf [n + 1] = f [n − 1] + f [n − 2] + f [n − 1] f[n+1]=f[n-1]+f[n-2 ]+f[n-1]f[n+1]=f[n−1]+f[n−2]+f[n−1 ]
An answer matrix can be constructed to store the currentf [n − 1] f[n-1]f[n−1 ] andf [n] f[n]f [ n ] The
current f[n] is the nextf [n − 1] f[n-1]f[n−1 ]
and the nextf [n] f[n]f [ n ] is the current f[n] andf [n − 1] f[n-1]f[n−1 ] The sum
can be constructed as a matrix. In the
title,nnn is 2^31, it is
conceivable to use fast exponentiation to solve
Code
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int mo=10000;
long long n;
struct hhx{
long long n,m,h[5][5];
}a,b,x;
hhx operator * (hhx l,hhx y) //重新定义乘号
{
x.n=l.n,x.m=y.m;
memset(x.h,0,sizeof(x.h));
for (int k=1;k<=l.m;k++)
for (int i=1;i<=x.n;i++)
for (int j=1;j<=x.m;j++)
x.h[i][j]=(x.h[i][j]+l.h[i][k]*y.h[k][j]%mo)%mo;
return x;
}
void power(long long n) //快速幂
{
if (n & 1) a=a*b;
if (n==1) return;
b=b*b;
power(n/2);
}
int main()
{
a.n=1,a.m=2;
a.h[1][1]=a.h[1][2]=1;
b.n=2,b.m=2;
b.h[1][2]=b.h[2][1]=b.h[2][2]=1; //赋值
scanf("%lld",&n);
power(n-1);
printf("%lld",a.h[1][1]);
return 0;
}