POJ3070Fibonacci(矩阵快速幂)(AC)

来源:互联网 发布:百元电脑音箱推荐 知乎 编辑:程序博客网 时间:2024/05/29 18:16
Fibonacci
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 16150 Accepted: 11354

Description

In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

An alternative formula for the Fibonacci sequence is

.

Given an integer n, your goal is to compute the last 4 digits of Fn.

Input

The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output

For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input

099999999991000000000-1

Sample Output

0346266875

Hint

As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

.

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

.

Source

Stanford Local 2006

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>int N = 0;//Int型够了int binary[32]; //int最大32位,0~31//矩阵快速幂 这种类型的题目没有做过//矩阵的快速幂是用来高效地计算矩阵的高次方的//简单的说就是把幂分成二级制 例如 A^19  =>  (A^16)*(A^2)*(A^1) A^4能通过(A^2)*(A^2)得到,A^8又能通过(A^4)*(A^4)得到//网上找到的一段解释//矩阵乘法的优越性究竟体现在哪里呢。其实,矩阵乘法只是体现了我们从之前求的数到现在要求的数的递推过程,就是说矩阵乘法可以完成多个元素的递推。//不过这个我们用普通的递推就可以实现的啊~~认真想想我们就能发现,我们在矩阵乘法的过程中把上见面的A矩阵自己相乘了很多遍。就是说,我们可以求A矩阵的幂最后乘上B矩阵,既然要求幂,//矩阵乘法满足结合律,那么我们就可以用快速幂啦~~矩阵乘法的优越性就体现在这里:在递推过程变成不断乘以一个矩阵,然后用快速幂快速求得从第一个到第n个的递推式,这样子就可以在短时间内完成递推了//题目中已经告知公式//因此不需要自己推导公式了typedef struct matrix{int m[2][2];};//最后算N-1次幂就可以得到Fnmatrix ma =  //题目中的矩阵,最后要算的就是矩阵的n次幂{1, 1,1, 0};matrix azermi =  //0次幂{1, 0,0, 1};matrix multi(matrix a, matrix b){matrix tmp;int i = 0;int j = 0;int k = 0;for (i = 0; i < 2;i++){for (j = 0; j < 2; j++){tmp.m[i][j] = 0;for (k = 0; k < 2; k++){ tmp.m[i][j] += (a.m[i][k] * b.m[k][j])% 10000; //只留最后四位tmp.m[i][j] %= 10000;}}}return tmp;}matrix getans(){matrix tmp = azermi;matrix matmp = ma;while (N>0){//如果N >0,则开始算,如果N是奇数,那必定最后一位是1if (N&1){tmp = multi(tmp, matmp);}//举例10的9次方,= 10的8次方*10//1: tmp = 1*10 (9&1 = 1) 9/2 = 4 同时做(10*10)//2: (10*10)*(10*10) (4 &1 != 1) 4/2 = 2//3: (10*10*10*10)*(10*10*10*10) (2 &1 != 1) 2/2 = 1//4: 10* (10*10*10*10*10*10*10*10) (1 &1 != 1) 1/2 = 0matmp = multi(matmp, matmp); //这步是为什么 相当于幂相乘了,因为相当于自己又乘自己了//这个要好好体会下N >>= 1;//右移1位,相当于/2}return tmp;}int main(){int i = 0;int tmpN = 0;matrix ans;freopen("input.txt", "r", stdin);while (1 == scanf("%d",&N) &&(-1 != N)){if (0 == N){printf("0\n");continue;}/*//如果从N =1开始,那这个矩阵是tmpN = N;//转换成二进制用位运算for (i = 0; i < 32;i++){binary[i] = tmpN & 1;tmpN = tmpN >> 1;}N = N;*/ans = getans();printf("%d\n", ans.m[0][1]);}return 0;}