Fibonacci Sequence II (Matrix Multiplication + Fast Power)

Fibonacci Sequence II

Time Limit:1000MS
Memory Limit:65536K

Description

A sequence of the form 1 1 2 3 5 8 13 21 34 55 89 144..., find the nth term of the Fibonacci sequence.

Input

n (1〈 n 〈 231

Output

A number is the nth term mod 10000 of the Fibonacci sequence;

Sample Input

123456789
Sample Output

4514

Problem solving ideas

This question is P1962 Fibonacci number (fast matrix multiplication + power) of the original title
with only a change of a few%

AC code

#include<cstdio>
using namespace std;
long long n,k;
struct node
{
    
    
	long long oo[5][5];
}a;
node operator*(node x,node y)//重新定义“*”,变为矩阵乘法
{
    
    
	node z;
	for(long long i=1;i<=2;i++)//都改为2
	 for(long long j=1;j<=2;j++)
	  z.oo[i][j]=0;
	for(long long o=1;o<=2;o++)  
	 for(long long i=1;i<=2;i++)
	  for(long long j=1;j<=2;j++)
	   z.oo[i][j]=(z.oo[i][j]+x.oo[i][o]*y.oo[o][j])%10000;
	return z;
}
node ksm(node x,long long k)//快速幂
{
    
    
	node y=x;
	while(k)
	{
    
    
		if(k%2)y=x*y;
		x=x*x;
		k/=2;
	}
	return y;
}
int main()
{
    
    
	scanf("%lld",&n);
	a.oo[1][1]=0;//初始值
	a.oo[1][2]=a.oo[2][1]=a.oo[2][2]=1;
	a=ksm(a,n);
	printf("%lld",a.oo[1][1]);
	return 0;
}


Thank you

Guess you like

Origin blog.csdn.net/weixin_45524309/article/details/111068543