斐波那契
Problem:
Keven 特别喜欢斐波那契数列,已知 (fib_1=1),(fib_2=1),对于 (ngeq3),f(fib_{n}=fib_{n-2}+fib_{n-1}),并且他想知道斐波那契前 n 项平方和是多少?
为了防止答案过大,请将最后的答案模 1e9+7
Input:
第一行一个整数 n(1<=n<=1e18)
Output:
在一行中输出斐波那契数列的前 n 项平方和模 1e9+7
Example:
input
5
output
40
note
(1^2+1^2+2^2+3^2+5^2=40)
Solution:
找规律发现结果为
[a_{n}=fib_{n}*fib_{n-1}
]
因为n可以取到1e18,所以fib需要用矩阵快速幂求
fib的递推式:
[fib[i]=fib[i-1]+fib[i-2]\fib[i-1]=fib[i-1]\即:\fib[i]=1*fib[i-1]+1*fib[i-2]\fib[i-1]=1*fib[i-1]+0*fib[i-2]\即:\egin{bmatrix}fib[n]\fib[n-1]end{bmatrix}=egin{bmatrix}1&1\1&0end{bmatrix} imesegin{bmatrix}fib[n-1]\fib[n-2]end{bmatrix}\Leftrightarrow\egin{bmatrix}fib[n]\fib[n-1]end{bmatrix}=egin{bmatrix}1&1\1&0end{bmatrix}^{n-1} imesegin{bmatrix}fib[1]\fib[0]end{bmatrix}
]
Code:
#include <bits/stdc++.h>
#define lowbit(x) (x&(-x))
#define CSE(x,y) memset(x,y,sizeof(x))
#define INF 0x3f3f3f3f
#define Abs(x) (x>=0?x:(-x))
#define FAST ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int maxn = 111111;
const ll mod = 1e9 + 7;
ll ans[2] = { 1,0 };
ll sp[2][2] = { {1,1},{1,0} };
void qpow(ll n) {
while (n) {
if (n & 1) {
ll mid[2] = { 0,0 };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
mid[i] = (mid[i] + (ans[j] * sp[i][j]) % mod) % mod;
}
}
ans[0] = mid[0]; ans[1] = mid[1];
}
n >>= 1;
ll mid[2][2] = { {0,0},{0,0} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
mid[i][j] = (mid[i][j] + (sp[i][k] * sp[k][j]) % mod) % mod;
}
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sp[i][j] = mid[i][j];
}
}
}
return;
}
int main()
{
ll n;
cin >> n;
qpow(n);
cout << ans[0] * ans[1] % mod << endl;
return 0;
}