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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值