uva 11582 快速幂 Fibonacci循环节

来源:互联网 发布:数据结构c语言课程设计 编辑:程序博客网 时间:2024/05/20 20:01

题目:

紫书数论10.1 11582 P316

题解:

先找出Finonacci的循环节,这里注意a^b%n可以优化为(a%n)^b%n,
Unsigned long long 是比long long 在正数范围是前者大的,这里用unsigned long long 可以防止快速幂运算溢出
小于2^64的数要用unsigned long long

代码:

#include <iostream>#include <cstdio>using namespace std;const int maxn = 1000000+100;typedef long long LL;typedef unsigned long long ULL;LL f[maxn]={0,1};LL getT(LL n){    LL m = n*n+2;    int cnt=0;    for(LL i=2;i<=m;i++)    {        f[i]=(f[i-1]+f[i-2])%n;        cnt++;        if(f[i]==1&&f[i-1]==0)        {             return cnt;        }    }}int pow_mod(ULL a, ULL b, ULL m){    if(b==0) return 1;    int k=pow_mod(a, b/2, m);    k=k*k%m;    if(b%2) k=k*a%m;    return k;}int main(){    int T;    cin>>T;    ULL a,b,n;    while(T--)    {        scanf("%llu%llu%llu",&a,&b,&n);        LL round=getT(n);        cout<<round<<endl;        if(n!=1){        int tmp = pow_mod(a%round,b,round);        cout<<f[tmp]<<endl;        }        else            cout<<"0"<<endl;    }    return 0;}
阅读全文
0 0
原创粉丝点击