题意
给你,求
,其中
表示组合数。对
取模
题解
看到式子首先可以打表看看,有:
1 1 2 2 3 3 4 5 5 8 6 13 7 21 8 34 9 55 10 89 11 144
敏感的一看就会发现这是个斐波那契数列,利用矩阵快速幂就可以解决了。这里给出证明。
设为奇数
那么
根据杨辉三角的公式有
令为偶数,所以上式有
由于且
所以有
代码
#define MAX 2
typedef struct {
int m[MAX][MAX];
}Matrix;
const int mod=1e9+9;
Matrix P={1,1,1,0};
Matrix I={1,0,0,1};
Matrix Matrixmul(Matrix a,Matrix b)
{
int i,j,k;
Matrix c;
for(i=0;i<MAX;i++)
for(j=0;j<MAX;j++)
{
c.m[i][j]=0;
for(k=0;k<MAX;k++)
{
c.m[i][j]=(c.m[i][j]+1ll*a.m[i][k]*b.m[k][j]%mod)%mod;
}
}
return c;
}
Matrix quickpow(long long n)
{
Matrix m=P,b=I;
while(n>0)
{
if(n%2==1)
b=Matrixmul(b,m);
n=n/2;
m=Matrixmul(m,m);
}
return b;
}
class Solution {
public:
/**
*
* @param n int整型
* @return int整型
*/
int Sum(int n) {
// write code here
Matrix a;
a=quickpow(n);
return a.m[0][0];
}
};二次剩余版
const int mod=1e9+9;
long long quickmod(long long a,long long b)
{
long long ans=1;
while(b)
{
if(b%2==1)
ans=ans*a%mod;
a=a*a%mod;
b=b/2;
}
return ans;
}
class Solution {
public:
/**
*
* @param n int整型
* @return int整型
*/
int Sum(int n) {
// write code here
return 276601605LL*((quickmod(691504013LL,n+1)-quickmod(308495997LL,n+1)+mod)%mod)%mod;
}
};


京公网安备 11010502036488号