问题
快速求得斐波拉切数列的某一位。
解法
首先将递推公式写成矩阵相乘的形式,然后计算出所有2的幂次的矩阵。对任意数,分解成2的幂次求得。
复杂度O(logn)
#include <bits/stdc++.h>
using namespace std;
const int mod = 19999997;
struct M{
long long a, b, c, d;
};
M m[32];
M mul(M a, M b)
{
M ret;
ret.a = (a.a*b.a%mod+a.b*b.c%mod)%mod;
ret.b = (a.a*b.b%mod+a.b*b.d%mod)%mod;
ret.c = (a.c*b.a%mod+a.d*b.c%mod)%mod;
ret.d = (a.c*b.b%mod+a.d*b.d%mod)%mod;
return ret;
}
int main()
{
m[0].a= 0; m[0].b = m[0].c = m[0].d = 1;
for (int i=1; i<32; ++i)
{
m[i] = mul(m[i-1], m[i-1]);
}
M b;
b.a = b.d = 1; b.b = b.c = 0;
int n;
scanf("%d", &n);
for (int i=0; i<32&& n; ++i, n>>=1)
{
if (n&(0x01))
{
b = mul(b, m[i]);
}
}
printf("%lld\n", b.d);
return 0;
}