您的位置:首页 > 其它

Fibonacci----poj3070(矩阵快速幂, 模板)

2015-09-20 21:26 573 查看
题目链接:http://poj.org/problem?id=3070

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include<math.h>
using namespace std;
#define N 10

struct node
{
int a

;
}s,e;

node mul(node p, node q)///求两个矩阵的积;
{
node tem;
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
tem.a[i][j] = 0;
for(int k=0; k<2; k++)
tem.a[i][j] = (tem.a[i][j]+p.a[i][k]*q.a[k][j])%10000;
}
}
return tem;
}
node Pow(node p, int n)
{
node tem;
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
tem.a[i][j] = (i==j);
while(n)
{
if(n&1)///n是奇数;
tem = mul(tem, p);///让矩阵e和矩阵a相乘;
n/=2;
p = mul(p, p);
}
return tem;
}

int main()
{
s.a[0][0] = 1;
s.a[0][1] = 1;
s.a[1][0] = 1;
s.a[1][1] = 0;
int n;
while(scanf("%d", &n),n!=-1)
{
e = Pow(s, n);
printf("%d\n", e.a[0][1]);
}
return 0;
}


View Code
对比着想想快速幂;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: