Yet another Number Sequence UVA - 10689
题意:给出a,b,n,m。f(0)=a,f(1)=b,求f(n)=f(n-1)+f(n-2)的最后m位数字。
思路:矩阵的模板题。
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
struct matrix{
ll x[2][2];
};
ll m;
matrix multi(matrix a,matrix b){
matrix temp;
memset(temp.x,0,sizeof(temp.x));
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
{
temp.x[i][j]+=a.x[i][k]*b.x[k][j];
temp.x[i][j]%=m;//负数取模的问题,除法取模
}
return temp;
}
matrix quick_multi(matrix a,ll n)//矩阵快速幂
{
matrix temp=a;
n--;
while(n){
if(n&1)
temp=multi(temp,a);
a=multi(a,a);
n>>=1;
}
return temp;
}
int main()
{
int t;
scanf("%d",&t);
ll a,b,n;
while(t--)
{
scanf("%lld%lld%lld%lld",&a,&b,&n,&m);
int mod=m;m=1;
while(mod--) m*=10;
matrix A,B;
memset(A.x,0,sizeof(A.x));
memset(B.x,0,sizeof(B.x));
A.x[0][0]=A.x[0][1]=A.x[1][0]=1;
B.x[0][0]=b,B.x[1][0]=a;
if(n<=1) n==0?printf("%d\n",a%m):printf("%d\n",b%m);
else
{
A=quick_multi(A,n-1);
B=multi(A,B);
printf("%d\n",B.x[0][0]%m);
}
}
return 0;
}