HDU——4549M斐波那契数列(矩阵快速幂+快速幂+费马小定理)
2024-10-20 15:55:48
M斐波那契数列
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 2598 Accepted Submission(s): 774
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 )
每组数据占一行,包含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
6 10 2
Sample Output
0
60
60
水题一道
代码:
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
#define INF 0x3f3f3f3f
#define MM(x) memset(x,0,sizeof(x))
#define MMINF(x) memset(x,INF,sizeof(x))
typedef long long LL;
const double PI=acos(-1.0);
const LL mod=1000000007;
struct mat
{
LL pos[2][2];
mat(){MM(pos);}
};
mat operator*(const mat &a,const mat &b)
{
mat c;
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
for (int k=0; k<2; k++)
c.pos[i][j]+=(a.pos[i][k]*b.pos[k][j])%(mod-1);
}
}
return c;
}
mat operator^(mat a,LL b)
{
mat r;
for (int i=0; i<2; i++)
r.pos[i][i]=1;
while (b!=0)
{
if(b&1)
r=r*a;
a=a*a;
b>>=1;
}
return r;
}
LL qpow(LL a,LL b)
{
LL r=1;
a%=mod;
while (b)
{
if(b&1)
r=(r*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return r;
}
int main(void)
{
LL pa,pb;
LL a,b,c,n;
while (~scanf("%I64d%I64d%I64d",&a,&b,&n))
{
if(n==0)
printf("%I64d\n",a);
else if(n==1)
printf("%I64d\n",b);
else
{
mat t,one;
t.pos[0][0]=1;
t.pos[0][1]=1;
t.pos[1][0]=1;
one.pos[0][0]=1;
one.pos[1][0]=1;
t=t^(n-2);
one=t*one;
pa=one.pos[1][0]%(mod-1);
pb=one.pos[0][0]%(mod-1);
printf("%I64d\n",(qpow(a,pa)*qpow(b,pb))%mod);
}
}
return 0;
}
最新文章
- 【原】SDWebImage源码阅读(一)
- 我的LESS编译方案
- 基于keepalived搭建MySQL的高可用集群
- Think Python - Chapter 10 - Lists
- C#利用Attribute实现简易AOP介绍 (转载)
- apache&;nginx资料汇总
- HW2.3
- ASP.NET 路由
- 打开网页自动弹出QQ临时会话 (打开网站弹出QQ聊天) qq.js文件代
- 【JS】JavaScript中的执行环境与作用域
- ajax请求 readyState为0 可能原因之一
- mysql 零碎笔记
- 使用LVM进行分区扩展的记录
- 扫二维码登录实现原理,php版
- 人生苦短:Python里的17个“超赞操作
- python下划线
- 关于Windows下无法在MySQL安装目录找到配置文件my.ini
- If TransactionScope will close database connections
- android 代码edittext删除或者替换光标处的字串
- [Luogu 1073] NOIP2009 最优贸易