UVA-11582 Colossal Fibonacci Numbers!

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

題目意思:

      給你三個數a,b,n,要你求出Fib(a^b)~mod~n

解題思路:

      對於輸入的每組數,因爲求對於n取餘的結果,我們在求斐波那契數組時對n取餘,直到找到循環節tmp。由於(a*a)~mod~n=((a~mod~n)*(a~mod~n))~mod~n,同時每tmp個數一個循環,因此我們只需輸出Fib數組中第(a~mod~tmp)^b~mod~tmp項即可

#include<iostream>
#include<cstdio>

using namespace std;

#define ULL unsigned long long
const int maxN = 1100;

int Fib[maxN*maxN];

ULL fastPow(ULL a, ULL b, ULL c) {
    if(b == 0)
        return 1;
    ULL res = 1;
    while(b) {
        if(b & 1) {
            res = (res * a) % c;
        }
        b >>= 1;
        a = (a * a) % c;
    }
    return res;
}

int main() {
    int t;
    ULL a,b,n,tmp;
    cin >> t;
    while(t--) {
        cin >> a >> b >> n;
        Fib[0] = 0 % n;     //不加%n會RE,玄學,至今未懂
        Fib[1] = 1 % n;
        for(int i = 2;i <= n * n + 100;i++) {
            Fib[i] = (Fib[i-1] + Fib[i-2]) % n;
            if(Fib[i-1] == Fib[0] && Fib[i] == Fib[1]) {
                tmp = i - 1;
                break;
            }
        }
        ULL Loc = fastPow(a % tmp,b,(ULL)tmp);
        cout << Fib[Loc] << endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章