Problem Description
A sequence Sn 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 Sn.
You, a top coder, say: So easy!
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate Sn.
You, a top coder, say: So easy!
Input
There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.
Output
For each the case, output an integer Sn.
Sample Input
2 3 1 2013
2 3 2 2013
2 2 1 2013
2 3 2 2013
2 2 1 2013
Sample Output
4
14
4
14
4
(a+sqrt(b))^n向上取整%M
令A(n)=(a+sqrt(b))^n,B(n)=(a-sqrt(b))^n
易得C(n)=A(n)+B(n)为整数
例如:2.3+0.7 ,由于(a-)^<b<a^,因此B(n)为小于1的小数
那么A(n)向上取整的结果就是C(n),题目也就是求C(n)%M
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <set>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#define ll long long
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define gep(i,a,b) for(ll i=a;i<=b;i++)
using namespace std;
ll a,b,n,mod;
/*
矩阵乘法的相乘矩阵的行数、列数都要一样,这和行列式不同。
*/
struct ma{
ll m[][];
ma(){
memset(m,,sizeof(m));
}
};
ma qu(ma a,ma b,ll mod){
ma c;
gep(k,,){
gep(i,,){
if(a.m[i][k]){
gep(j,,){
c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j]%mod+mod)%mod;
}
}
}
}
return c;
}
ma quick_qu(ma a,ll b,ll mod){
ma c;
gep(i,,){
c.m[i][i]=1ll;
}
while(b){
if(b&) c=qu(c,a,mod);
b>>=;
a=qu(a,a,mod);
}
return c;
}
int main()
{
while(~scanf("%lld%lld%lld%lld",&a,&b,&n,&mod)){
if(n==){
printf("%lld\n",*a%mod);
continue;
}
ma c;
c.m[][]=*a;c.m[][]=b-a*a;
c.m[][]=;c.m[][]=;
ma d;
d.m[][]=*a*a*a+*a*b;d.m[][]=*a*a+*b;d.m[][]=*a;
ma e=quick_qu(c,n-,mod);
ma f;
f=qu(e,d,mod); //矩阵乘法不满足交换律,e,d位置不能换。
printf("%lld\n",f.m[][]);
}
return ;
}