Uva11582 Colossal Fibonacci Numbers! (数论、斐波那契循环节)

Uva11582 Colossal Fibonacci Numbers! (斐波那契循环节)

链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2629

题目

Time Limit:1000MS Memory Limit:0KB
Description
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 < 264 (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( ab ) upon division by n.

Sample Input
3
1 1 2
2 3 1000
18446744073709551615 18446744073709551615 1000

Sample Output
1
21
250

题意

求第 ab 个斐波那契数模n之后的数

分析

1.既然需要求 ab 且需要不断模,就需要使用快速幂。
2.由于斐波那契数为f[i] = f[i-1]+f[i-2],故对每个斐波那契数模n会使其产生循环节。所以只需找到循环节再模 ab 即可

源码

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<utility>
#include<sstream>
#define mem0(x) memset(x,0,sizeof x)
#define mem1(x) memset(x,-1,sizeof x)
#define dbug cout<<"here"<<endl;
//#define LOCAL

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6+10;
const int MOD = 1000000007;

ull f[1008612];

ull quickMod(ull a, ull b,ull mod){
    ull ans = 1;
    a %= mod;
    while(b){
        if(b & 1){
            ans = (ans*a)%mod;
        }
        b = b >> 1;
        a = (a*a)%mod;
    }
    return ans;
}

void solve(ull a, ull b, ull n){
    f[1] = f[2] = 1;
    ull i;
    for(i = 3; i <= n*(n+1); ++i){
        f[i] = (f[i-1] + f[i-2])%n;
        if(f[i]==f[2] && f[i-1]==f[1])
            break;
    }
    ull ans = quickMod(a, b ,i-2);//注意此处传入循环节长度,故不要忘了减2
    cout << f[ans] << endl;
}

int main(){
    #ifdef LOCAL
        freopen("C:\\Users\\asus-z\\Desktop\\input.txt","r",stdin);
        freopen("C:\\Users\\asus-z\\Desktop\\output.txt","w",stdout);
    #endif
    int t;
    ull a,b,n;
    cin >> t;
    while(t--){
        cin >> a >> b >> n;
        if(n==1){
            cout << "0" << endl;
            continue;
        }
        solve(a, b, n);
    }
    return 0;
}

你可能感兴趣的:(Uva11582 Colossal Fibonacci Numbers! (数论、斐波那契循环节))