首页 > 代码库 > uva 11582(大fib,打表找循环节)

uva 11582(大fib,打表找循环节)

  • f (0) = 0 and f (1) = 1
  • f (i+2) = f (i+1) + f (i)  for every i ≥ 0

Sample input

three integers a,b,n where 0 ≤ a,b < 264 (a and b will not both be zero) and 1 ≤ n ≤ 1000.

T

a  b  n 
3
1 1 2
2 3 1000
18446744073709551615 18446744073709551615 1000

Sample output

For each test case, output a single line containing the remainder of f (ab)upon division by n.

1
21
250


其实这题的主要知识,还是找循环节,打表。

卡点:2^64-1 --->   unsigned long long


#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#define bug(a) cout<<a<<"--->\n";
using namespace std;

typedef unsigned long long ULL;

vector<int>f[1005];
int period[1005];

int qpow(ULL a,ULL b,int p)
{
    int ans=1;
    while(b)
    {
        if(b&1) ans=int((ans*a)%p);
        a=(a*a)%p;
        b>>=1;
    }
    return ans;
}

void pre_fib()
{
    for(int n=2;n<=1000;n++)
    {
        f[n].push_back(0);f[n].push_back(1);
        for(int i=2;;i++)
        {
            f[n].push_back((f[n][i-1]+f[n][i-2])%n);
            if(f[n][i-1]==0&&f[n][i-2]==1)
            {
                period[n]=i-1;
                break;
            }
        }
    }
}

int main()
{
    int T;
    pre_fib();
    scanf("%d",&T);
    while(T--)
    {
        ULL a,b;
        int p;
        int c;
        scanf("%llu%llu%d",&a,&b,&p);
        if(a==0||p==1) printf("0\n");
        else
        {
            c=qpow(a%period[p],b,period[p]);
            printf("%d\n",f[p][c]);
        }
    }
    return 0;
}