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!
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!
2 3 1 2013 2 3 2 2013 2 2 1 2013
4 14 4
题意:
Sn是上面那个式子的向上取整,求Sn%m
思路:
第一种方法:共轭
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>
using namespace std;
typedef long long LL;
const int N = 2;
int m;
struct Matrix
{
LL m[N][N];
};
Matrix I = {//I主对角线是1
1,0,
0,1
};
Matrix multi(Matrix a,Matrix b)//矩阵乘法
{
Matrix c;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
c.m[i][j] = 0;
for(int k=0;k<N;k++)
c.m[i][j] += (a.m[i][k] * b.m[k][j])%m;
c.m[i][j]%=m;
}
}
return c;
}
Matrix power(Matrix A,long long k)//矩阵A的k次幂(快速幂)
{
Matrix ans = I,p = A;
while(k)
{
if(k&1)
{
ans = multi(ans,p);
k--;
}
k >>= 1;
p = multi(p,p);
}
return ans;
}
int main()
{
LL a,b,n;
while(scanf("%lld%lld%lld%d",&a,&b,&n,&m)!=EOF)
{
if(n==1){printf("%lld\n",2*a%m);continue;}
if(n==0){printf("1\n");continue;}
Matrix A = {
2*a%m,(b%m-a*a%m+m)%m,
1,0
};
Matrix ans = power(A,n-2);
/* for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
cout<<ans.m[i][j]<<" ";
cout<<endl;
}*/
int c1=2*a%m;
LL c2=2*a*a%m+2*b%m;
c2%=m;
long long anss= ((ans.m[0][0]%m*c2%m)%m+ans.m[0][1]*c1%m);
anss%=m;
printf("%lld\n",anss);
}
return 0;
}
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>
using namespace std;
typedef long long LL;
const int N = 2;
int m;
struct Matrix
{
LL m[N][N];
};
Matrix I = {//I主对角线是1
1,0,
0,1
};
Matrix multi(Matrix a,Matrix b)//矩阵乘法
{
Matrix c;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
c.m[i][j] = 0;
for(int k=0;k<N;k++)
c.m[i][j] += (a.m[i][k] * b.m[k][j])%m;
c.m[i][j]%=m;
}
}
return c;
}
Matrix power(Matrix A,long long k)//矩阵A的k次幂(快速幂)
{
Matrix ans = I,p = A;
while(k)
{
if(k&1)
{
ans = multi(ans,p);
k--;
}
k >>= 1;
p = multi(p,p);
}
return ans;
}
int main()
{
LL a,b,n;
while(scanf("%lld%lld%lld%d",&a,&b,&n,&m)!=EOF)
{
if(n==1){printf("%lld\n",2*a%m);continue;}
if(n==0){printf("1\n");continue;}
Matrix A = {
a%m,b%m,
1,a%m
};
Matrix ans = power(A,n-1);
/* for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
cout<<ans.m[i][j]<<" ";
cout<<endl;
}*/
long long anss= 2*((ans.m[0][0]%m*a%m)%m+ans.m[0][1]%m);
anss%=m;
printf("%lld\n",anss);
}
return 0;
}