UVa 11582 巨大的斐波那契数!(幂取模)

时间:2023-11-11 18:12:32

https://vjudge.net/problem/UVA-11582

题意:

输入两个非负整数a、b和正整数n,你的任务是计算f(a^b)除以n的余数。f[0]=0,f[1]=1,f[i+2]=f[i+1]+f[i]。

思路:

因为余数最多n种,所以最多n^2项就会出现重复。计算出周期,之后幂取模算出周期内的第几个数。

 #include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
using namespace std; const int maxn = + ;
typedef unsigned long long LL; LL a, b;
int n;
int M; int pow_mod(LL a, LL b, int m)
{
if (b == ) return ;
int x = pow_mod(a, b / , m);
LL ans = (LL)x*x%m;
if (b % ) ans = ans*a%m;
return (int)ans;
} int f[maxn*maxn], period[maxn]; int solve(LL a, LL b, int n) {
if (a == || n == ) return ;
int ans = pow_mod(a%M, b, M);
return f[ans];
} int main()
{
//freopen("D:\\input.txt", "r", stdin);
int t;
scanf("%d", &t);
while (t--)
{
cin >> a >> b >> n;
f[] = ;
f[] = ;
for (int i = ; i <= n*n; i++)
{
f[i] = (f[i - ] + f[i - ]) % n;
if (f[i - ] == && f[i] == )
{
M = i - ;
break;
}
}
cout << solve(a, b, n) << endl;
}
}