Jzzhu has invented a kind of sequences, they meet the following property:
You are given x and y, please calculate fn modulo 1000000007 (109 + 7).
The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).
Output a single integer representing fn modulo 1000000007 (109 + 7).
Input
2 3 3
Output
1
Input
0 -1 2
Output
1000000006
In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.
In the second sample, f2 = - 1; - 1 modulo (109 + 7) equals (109 + 6).
题意:已知f1,f2,n f【n】=f【n-1】-f【n-2】, 求f【n】
矩阵快速幂一下!!!
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;
struct mat
{
ll a[2][2];
mat()
{
a[0][0]=a[1][1]=1;
a[0][1]=a[1][0]=0;
}
};
mat mul(mat A,mat B)
{
mat ans;
int i,j,k;
memset(ans.a,0,sizeof(ans.a));
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
for(k=0;k<2;k++) {
ans.a[i][j]+=(A.a[i][k]*B.a[k][j]%mod+mod)%mod;
ans.a[i][j]%=mod;
}
}
}
return ans;
}
mat work(mat A,ll n)
{
mat ans;
while(n) {
if(n&1) ans=mul(A,ans);
A=mul(A,A);
n>>=1;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
ll f1,f2,fn,n;
mat A;
cin>>f1>>f2>>n;
f1%=mod,f2%=mod;
f1+=mod,f2+=mod;
f1%=mod,f2%=mod;
A.a[0][0]=A.a[1][0]=1;
A.a[0][1]=-1,A.a[1][1]=0;
if(n<3) {
if(n==1) cout<<f1<<endl;
if(n==2) cout<<f2<<endl;
return 0;
}
A = work(A,n-2);
fn = (A.a[0][0]*f2%mod + A.a[0][1]*f1%mod + mod)%mod;
cout<<fn<<endl;
return 0;
}