M斐波那契数列--费马小定理+快速幂+矩阵快速幂

Problem Description
M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?

Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )

Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。

Sample Input
0 1 0
6 10 2

Sample Output
0
60

分析:写出前几项
f0=a
f1=b
f2=a * b
f3=a * b2
f4=a2 * b3

(a b后面是指数)

发现指数为斐波那契数列 a的指数fn-1 b的指数fn
费马小定理:C为质数且A,C互质,A^B %C=A^(B%(C-1))%C (欧拉函数定理:n是个素数 它的欧拉函数为n-1)
运用矩阵快速幂和快速幂求解
最后输出(quick_pow(a,ans.m[1][1])*quick_pow(b,ans.m[1][0]))%mod

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
const ll mod=1000000007;
ll a,b,n,num1,num2,sum;
struct mat{
	ll m[2][2];
}c,ans;
ll quick_pow(ll a,ll b)
{
	ll temp=a%mod,ans=1;
	while(b)
	{
		if(b&1)
			ans=(ans*temp)%mod;
		temp=(temp*temp)%mod;
		b>>=1;
	}
	return ans%mod;
}
mat mul(mat a,mat b)
{
	mat temp;
	memset(temp.m,0,sizeof(temp.m));
	for(int i=0;i<2;i++)
	{
		for(int j=0;j<2;j++)
		{
			for(int k=0;k<2;k++)
			{
				temp.m[i][j]=(temp.m[i][j]+a.m[i][k]*b.m[k][j])%(mod-1);
			}
		}
	}
	return temp;
}
void pow_mat(ll n)
{
	memset(ans.m,0,sizeof(ans.m));
	for(int i=0;i<2;i++)
		ans.m[i][i]=1;
	c.m[0][0]=1;
	c.m[0][1]=1;
	c.m[1][0]=1;
	c.m[1][1]=0;
	while(n)
	{
		if(n&1)
			ans=mul(ans,c);
		c=mul(c,c);
		n>>=1;
	}
//	cout<<ans.m[1][1]<<" "<<ans.m[1][0]<<endl;
//	cout<<a<<" "<<b<<endl;
	printf("%lld\n",(quick_pow(a,ans.m[1][1])*quick_pow(b,ans.m[1][0]))%mod);
}
int main()
{

	while(~scanf("%lld %lld %lld",&a,&b,&n))
	{	
		if(n==0)
			printf("%lld\n",a%mod);
		else if(n==1)
			printf("%lld\n",b%mod);
		else
		{
			pow_mat(n);
		} 
 	} 
 	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aaHua_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值