UVA 11582 Colossal Fibonacci Numbers!

来源:互联网 发布:数据库推荐书籍 编辑:程序博客网 时间:2024/05/16 01:00

题目链接  http://acm.hust.edu.cn/vjudge/problem/41990


题意:让你求斐波纳契数列的第 a^b项 模n的结果(1<=n<=1000) 

预处理求出n分别为1-1000时斐波那契模数列的周期,不同的n值都会对应一个周期
之后求出a^b是周期中第几个
longlong会爆  要用unsigned longlon


#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <queue>#include <vector>#include <cmath>#include <stack>#include <map>#include <set>#define pi acos(-1)#define LL long long#define ULL unsigned long long#define INF 0x3f3f3f3fusing namespace std;typedef pair<int, int> P;const int maxn = 1e5 + 5;vector<int>fib[1005];int qpow(ULL x, ULL n, int mod){    int res = 1;    while (n){        if (n & 1) res = (int)(res * x % mod);        x = x * x % mod;        n >>= 1;    }    return res;}void pre_process(){    for (int m = 2; m <= 1000; m++){        fib[m].push_back(0);        fib[m].push_back(1);        for (int i = 2; ; i++){            fib[m].push_back( (fib[m][i-1] + fib[m][i-2]) % m );            if (fib[m][i] == 1 && fib[m][i-1] == 0)                break;        }        int cnt = fib[m].size(); //多了1和0两个数         fib[m].resize(cnt-2);    }}int main(void){//freopen("C:\\Users\\wave\\Desktop\\NULL.exe\\NULL\\in.txt","r", stdin);    ULL a, b;    int n, T, dex;    pre_process();    cin >> T;    while(T--)    {        scanf("%llu %llu %d", &a, &b, &n);        if (a == 0 || n == 1)            printf("0\n");        else {            int mod = fib[n].size();            dex = qpow(a%mod, b, mod); // a要先mod一下 不然会爆             printf("%d\n", fib[n][dex]);        }    }    return 0;}


0 0
原创粉丝点击