P1962 Fibonacci sequence (matrix multiplication + fast power)

P1962 Fibonacci Sequence

Topic portal

Problem solving ideas

This question and P3390 [template] fast power matrix (matrix multiplication + fast power) like
that is a change of the initial value on the line
this initial value is how come it
Insert picture description here

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])%1000000007;
	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/111067661