fibonacci数列(tyvj 1337)

来源:互联网 发布:房屋中介管理系统源码 编辑:程序博客网 时间:2024/05/22 04:39

题目

因为这一题的n范围给到maxlongint,所以普通方法求斐波那契肯定不行,这题转换成求矩阵的快速幂。

设起始矩阵是(1,1),不断的乘(1,1)以后会发现矩阵实际上就由斐波那契数列中的数组成:(F[N +2],F[N+1])

     (1,0)                  (1,0)                                                                                     (F[N +1], F[N])

所以最后只要输出二维数组[1][1]位置的元素就可以。

#include <stdio.h>#include <stdlib.h>#include <string.h>#define M 32768#define N 2struct mat{int num[N][N];};long long n;mat sta, ori;mat mul(mat a, mat b){//矩阵相乘 mat temp;memset(temp.num, 0, sizeof(temp.num));for(int i = 0; i < N; i++){for(int j = 0; j < N; j++){for(int k = 0; k < N; k++)temp.num[i][j] += a.num[i][k] * b.num[k][j];temp .num[i][j] %= M;}}return temp;}void ans(){//快速幂while(n){if(n & 1){sta = mul(sta, ori);//printf("%d %d\n%d %d\n\n", sta.num[0][0], sta.num[0][1], sta.num[1][0], sta.num[1][1]);}n >>= 1;ori = mul(ori, ori);}}int main (void){while(scanf("%lld", &n) != EOF){sta.num[0][0] = sta.num[0][1] = sta.num[1][0]= 1;sta.num[1][1] = 0;ori.num[0][0] = ori.num[0][1] = ori.num[1][0]= 1;ori.num[1][1] = 0;ans();printf("%d\n", sta.num[1][1]);}return 0;}


0 0
原创粉丝点击