Description
Without expecting, Angel replied quickly.She says: “I’v heard that you’r a very clever boy. So if you wanna me be your GF, you should solve the problem called GF~. ”
How good an opportunity that Gardon can not give up! The “Problem GF” told by Angel is actually “Gauss Fibonacci”.
As we know ,Gauss is the famous mathematician who worked out the sum from 1 to 100 very quickly, and Fibonacci is the crazy man who invented some numbers.
Arithmetic progression:
g(i)=k*i+b;
We assume k and b are both non-nagetive integers.
Fibonacci Numbers:
f(0)=0
f(1)=1
f(n)=f(n-1)+f(n-2) (n>=2)
The Gauss Fibonacci problem is described as follows:
Given k,b,n ,calculate the sum of every f(g(i))
The answer may be very large, so you should divide this answer by M and just output the remainder instead.
Input
The input contains serveral lines. For each line there are four non-nagetive integers: k,b,n,M
Each of them will not exceed 1,000,000,000.
Output
For each line input, out the value described above.
Sample Input
2 1 4 100
2 0 4 100
Sample Output
21
12
居然可以等比数列2分,额,参考大神博客,讲的很详细的:http://blog.csdn.net/ACdreamers/article/details/7851144
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<set>
using namespace std;
int m;
struct r{
long long int m[2][2];
} ;
r add(r a,r b){
r cnt;
cnt.m[0][0]=(a.m[0][0]+b.m[0][0])%m;
cnt.m[0][1]=(a.m[0][1]+b.m[0][1])%m;
cnt.m[1][0]=(a.m[1][0]+b.m[1][0])%m;
cnt.m[1][1]=(a.m[1][1]+b.m[1][1])%m;
return cnt;
}
r multi(r a,r b){
r cnt;
cnt.m[0][0]=(a.m[0][0]*b.m[0][0]+a.m[0][1]*b.m[1][0])%m;
cnt.m[0][1]=(a.m[0][0]*b.m[0][1]+a.m[0][1]*b.m[1][1])%m;
cnt.m[1][0]=(a.m[1][0]*b.m[0][0]+a.m[1][1]*b.m[1][0])%m;
cnt.m[1][1]=(a.m[1][0]*b.m[0][1]+a.m[1][1]*b.m[1][1])%m;
return cnt;
}
r power(r tmp,int n){
r ans;
ans.m[0][0]=ans.m[1][1]=1,ans.m[1][0]=ans.m[0][1]=0;
while(n){
if(n&1)
ans=multi(tmp,ans);
tmp=multi(tmp,tmp);
n>>=1;
}
return ans;
}
r sum(r A,int k) { // 2分求等比矩阵和
if(k==1) return A;
if(k==0){
A.m[0][0]=A.m[0][1]=A.m[1][0]=A.m[1][1]=0;
return A;
}
r t = sum(A,k/2);
if(k&1) {
r cur = power(A,k/2+1);
t= add(t,multi(t,cur));
t= add(t,cur);int k,b,m,n;
}
else {
r cur = power(A,k/2);
t = add(t,multi(t,cur));
}
return t;
}
int main(){
int k,b,n;
while(cin>>k>>b>>n>>m){
r a;
a.m[0][0]=a.m[0][1]=a.m[1][0]=1,a.m[1][1]=0;
r fb=power(a,b);
r an=power(a,k);
r fs=multi(fb,sum(an,n-1));
r s=add(fb,fs);
cout<<s.m[0][1]<<endl;
}
return 0;
}