UVA - 11582 Colossal Fibonacci Numbers! 【数学】

版权声明:如需转载,记得标识出处 https://blog.csdn.net/godleaf/article/details/81985119

题目链接:https://cn.vjudge.net/problem/UVA-11582

直接看代码吧,难点就在于精度和溢出问题;

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<vector>
#include<string>
#include<set>

using namespace std;

#define IOS ios::sync_with_stdio(false); cin.tie(0);

int read(){

    int r=0,f=1;char p=getchar();
    while(p>'9'||p<'0'){if(p=='-')f=-1;p=getchar();}
    while(p>='0'&&p<='9'){r=r*10+p-48;p=getchar();}return r*f;
}

typedef long long ll;
typedef unsigned long long ull;
const int Maxn = 1e6+100;
const long long LINF = 1e18;
const int INF = 0x3f3f3f3f;

ll num[Maxn];

ull pow_mod (ull a, ull n, ull m) {  // 注意ull的数据范围,格外小心精度
    if(n == 0) return 1;
    ull x = pow_mod(a, n/2, m);
    ull res = x*x%m;
    if(n%2 == 1) res = res*a%m; // 这里本来打算先a%m再*res防止溢出的,但是结果不对,不知道为什么
    return res;
}

int main (void)
{
    int cas,n,ans;
    ull a,b;
    cin >> cas;
    while (cas--) {
        cin >> a >> b >> n;
        num[0] = 0; num[1] = 1%n;
        int pos;
        for (int i = 2; i <= Maxn; ++i) { // 循环的规律,Maxn内一定会出现一次循环,先打表
            num[i] = (num[i-1]+num[i-2])%n;
            if(num[i] == num[1] && num[i-1] == num[0]) { pos = i-1; break; }
        }
        int ans = (int)pow_mod (a%pos,b,(ull)pos);  // 这里的a要先 %pos,不然会溢出
        cout << num[ans] << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/godleaf/article/details/81985119
今日推荐