快速幂 UVa11582 巨大的斐波那契数!

Colossal Fibonacci Numbers!

 UVA - 11582 

The i’th Fibonacci number f(i) is recursively defined in the following way:

• f(0) = 0 and f(1) = 1

• f(i + 2) = f(i + 1) + f(i)

for every i ≥ 0 Your task is to compute some values of this sequence.

Input

Input begins with an integer t ≤ 10, 000, the number of test cases.

Each test case consists of three integers a, b, n where 0 ≤ a, b < 2 64 (a and b will not both be zero) and 1 ≤ n ≤ 1000.

Output

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

Sample Input

3 1 1

2 2 3

1000 18446744073709551615 18446744073709551615 1000

Sample Output

1

21

250

题解:模板题。

AC代码:

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn=10000000+5;
typedef unsigned long long ll;
int s[maxn];
ll pow_mod(ll a,ll b,int n)
{
    a%=n;
    ll ans=1;
    while(b)
    {
        if(b&1)
            ans=ans*a%n;
        b=b>>1;
        a=a*a%n;
    }
    return ans;
}
int main()
{
    int num;
    while(cin>>num)
    {
        while(num--)
        {
            ll a,b;
            int n;
            cin>>a>>b>>n;
            if(n==1||a==0)
            {
                cout<<"0"<<endl;
                continue;
            }
            s[0]=s[1]=1;
            int p;
            for(int i=2;;i++)
            {
               s[i]=(s[i-1]+s[i-2])%n;
               if(s[i]==1&&s[i-1]==1)
               {
                      p=i-1;
                   break;
               }
            }
            cout<<s[pow_mod(a,b,p)-1]<<endl;
        }
    }
    return 0;
}

 

今天也是元气满满的一天!good luck!

posted @ 2017-10-07 19:12  ikefire  阅读(247)  评论(0编辑  收藏  举报