例题10-1 巨大的斐波那契数! UVa11582

1.题目描述:点击打开链接

2.解题思路:由于是模运算,因此整个序列肯定会出现重复序列,事先可以枚举周期T,然后利用pow_mod的算法快速计算a^b(mod T)的结果p,返回F[p]即可。

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

typedef unsigned long long LL;
const int N = 1010;

LL a, b;
int n;
int memo[N];

int T(int n) //计算周期T
{
	int& res = memo[n];
	if (res)return res;
	int prev = 0, curr = 1, succ;
	res = 0;
	for (;;) 
	{
		res++;
		succ = (prev + curr) % n;
		prev = curr;
		curr = succ;
		if (prev == 0 && curr == 1)return res;
	}
}

int pow_mod(LL a, LL k, int mod) //计算a^k模mod的结果
{
	a %= mod;
	LL res = 1;
	while (k) 
	{
		if (k & 1) 
			res = (res*a) % mod;
		a = (a*a) % mod;
		k >>= 1;
	}
	return (int)res;
}

int F(int n, int mod) //计算第n项
{
	int prev = 0, curr = 1, succ;
	while (n--) 
	{
		succ = (prev + curr) % mod;
		prev = curr;
		curr = succ;
	}
	return prev;
}

int main() 
{
	//freopen("test.txt", "r", stdin);
	int t;
	cin >> t;
	while (t--) 
	{
		cin >> a >> b >> n;
		if (n == 1) 
		{
			cout << 0 << endl;
			continue;
		}
		cout << F(pow_mod(a, b, T(n)), n) << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值