一道数论题
数据范围,要用unsigned long long ,输入输出用%llu
还有一个坑,当a=0时,报错。因为这个 runtine error好多次。
另外,因为a 一开始就很大,所有用快速幂时,首先就要对a取模。
主要是周期的确定。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ll;
ll a,b;
int n,time;
ll f_pow(ll a,ll b)
{
ll res=1;
while(b)
{
if(b&1)
{
res*=a;//printf("res=%llu\n",res);
res%=time;
}
a%=time;//先模一次,否则会爆
a*=a;
a%=time;
b>>=1;
}
return res%time;
}
int F(int y)
{
int a0=0,a1=1%n,a2;
for(int i=2;i<=y;i++)
{
a2=(a0%n+a1%n)%n;
a0=a1;
a1=a2;
}
if(y==0)
return a0;
else if(y==1)
return a1;
else
return a2;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%llu%llu%d",&a,&b,&n);
if(a==0)//runtime erro!!!!!!!!!!!
printf("0\n");
else
{
int m=n*n;
int f0=0;
int f1=1%n;
int ff1=f0,ff2=f1,ff3;
for(int i=1;i<=m;i++)
{
ff3=(ff1%n+ff2%n)%n;
ff1=ff2;
ff2=ff3;
if(ff1==f0&&ff2==f1)
{
time=i;
break;
}
}//printf("time=%d\n",time);
int x=(int)f_pow(a,b);//printf("x=%d\n",x);
printf("%d\n",F(x));
}
}
return 0;
}