http://acm.hdu.edu.cn/showproblem.php?pid=4565
求x=(a+sqrt(b) )向上取整
求Sn=x^n %mod
----------------------
记(a+sqrt_b)n为An,(a-sqrt_b)n 为bn
那么Cn=An+Bn=(a+sqrt_b)n+(a−sqrt_b)n
因为A B共轭 所以C为整数(没去证明)
那么根据题目对b的限定,显然 Bn是0到1间的小数,又答案是向上取整
所以An就等于Cn,
然后去递推Cn
用Cn乘以((a+sqrt_b)+(a−sqrt_b))
展开最后得到
C(n+1)=2aC(n)−(a2−b)C(n−1)
然后构造矩阵快速幂做即可
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int N = 2;
long long mod=1e9+7;
struct Matrix
{
long long mat[N][N];
} ;
Matrix unit_matrix ;
long long n;
const long long k=2;
Matrix mul(Matrix a, Matrix b) //矩阵相乘
{
Matrix res;
for(int i = 0; i < k; i++)
for(int j = 0; j < k; j++)
{
res.mat[i][j] = 0;
for(int t = 0; t < k; t++)
{
res.mat[i][j] += a.mat[i][t] * b.mat[t][j];
res.mat[i][j] %= mod;
}
}
return res;
}
Matrix pow_matrix(Matrix a, long long m) //矩阵快速幂
{
Matrix res = unit_matrix;
while(m != 0)
{
if(m & 1)
res = mul(res, a);
a = mul(a, a);
m >>= 1;
}
return res;
}
long long a,b;
Matrix get(long long n)
{
Matrix ori;
memset(ori.mat,0,sizeof ori.mat);
ori.mat[0][0]=ceil((a+sqrt(1.0*b))*(a+sqrt(1.0*b)));
ori.mat[0][0]%=mod;
ori.mat[0][1]=ceil(a+sqrt(1.0*b) );
ori.mat[0][1]%=mod;
Matrix c;
c.mat[0][0]=2*a%mod;
c.mat[0][1]=1;//b-a*a;
c.mat[1][0]=(b-a*a)%mod;
c.mat[1][0]=(c.mat[1][0]+mod)%mod;;
c.mat[1][1]=0;
Matrix ans = pow_matrix(c, n-1 );
ans = mul(ori,ans);
return ans;
}
int main()
{
int i, j, t;
//初始化单位矩阵 //类似快速幂的 ans=1; 如今是ans=单位矩阵
for(i = 0; i < k; i++)
for(j = 0; j < k; j++)
unit_matrix.mat[i][j] = 0;
for(i = 0; i < k; i++) unit_matrix.mat[i][i] = 1;
while(scanf("%lld",&a)!=EOF)
{
scanf("%lld%lld%lld,",&b,&n,&mod);
Matrix ans=get(n);
printf("%lld\n", ans.mat[0][1]);
}
return 0;
}