So Easy!
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5051 Accepted Submission(s): 1660
Problem Description
A sequence S
n is defined as:
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate S n.
You, a top coder, say: So easy!
![](http://acm.hdu.edu.cn/data/images/C468-1001-1.jpg)
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate S n.
You, a top coder, say: So easy!
![](http://acm.hdu.edu.cn/data/images/C468-1001-2.jpg)
Input
There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 2
15, (a-1)
2< b < a
2, 0 < b, n < 2
31.The input will finish with the end of file.
Output
For each the case, output an integer S
n.
Sample Input
2 3 1 2013 2 3 2 2013 2 2 1 2013
Sample Output
4 14 4
Source
Recommend
zhoujiaqi2010
/*化一化就转化成a^n+b^n%m的问题
跟lightOJ1070一样
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=2;
typedef struct node{
LL a[maxn][maxn];
node(){
memset(a,0,sizeof(a));
}
}Matrix;
Matrix multiply(Matrix x,Matrix y,LL mod){
Matrix ans;
for(int i=0;i<maxn;i++){
for(int j=0;j<maxn;j++){
for(int k=0;k<maxn;k++){
ans.a[i][j]=(ans.a[i][j]+x.a[i][k]*y.a[k][j])%mod;
}
}
}
return ans;
}
Matrix quickpow(Matrix x,int a,int mod){
Matrix ans;
for(int i=0;i<maxn;i++)
ans.a[i][i]=1;
while(a){
if(a&1)
ans=multiply(ans,x,mod);
x=multiply(x,x,mod);
a>>=1;
}
return ans;
}
int main(){
LL a,b,m;
int n;
while(~scanf("%I64d%I64d%d%I64d",&a,&b,&n,&m)){
if(n<3){
if(n==0) printf("%I64d\n",2%m);
else if(n==1) printf("%I64d\n",(2*a)%m);
else if(n==2) printf("%I64d\n",(2*a*a+2*b)%m);
continue;
}
Matrix base,x;
base.a[0][0]=2*a*a+2*b;base.a[0][1]=2*a;
x.a[0][0]=2*a%m;x.a[0][1]=1;x.a[1][0]=(b-a*a%m+m)%m;x.a[1][1]=0;//没取模就WA了
Matrix ans=multiply(base,quickpow(x,n-2,m),m);
printf("%I64d\n",ans.a[0][0]);
}
}