[关闭]
@xunuo 2017-03-25T11:43:32.000000Z 字数 1541 阅读 1176

poj 3070 Fibonacci---(矩阵快速幂模板)


Time Limit: 1000MS      Memory Limit: 65536K

矩阵快速幂


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

0
9
999999999
1000000000
-1

Sample Output

0
34
626
6875

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:

图片


题意:

Fibonacci数列,问你第n个是多少?

解题思路:

由题+图可知:裸的矩阵快速幂,再取个模;模板模板,一切都是模板。。。。。

完整代码:

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. using namespace std;
  5. const int mod=10000;
  6. struct node
  7. {
  8. int a[2][2];
  9. void init()
  10. {
  11. a[0][0]=0,a[0][1]=1;
  12. a[1][0]=1,a[1][1]=1;
  13. }
  14. };
  15. node matrixmul(node x,node y)
  16. {
  17. node z;
  18. for(int i=0;i<2;i++)///题中为2*2的矩阵
  19. {
  20. for(int j=0;j<2;j++)
  21. {
  22. z.a[i][j]=0;
  23. for(int k=0;k<2;k++)
  24. z.a[i][j]+=(x.a[i][k]*y.a[k][j]);///矩阵乘法
  25. z.a[i][j]%=mod;
  26. }
  27. }
  28. return z;
  29. }
  30. node mul(node s,int k)
  31. {
  32. node ans;
  33. ans.init();
  34. while(k>=1)
  35. {
  36. if(k&1)
  37. ans=matrixmul(ans,s);
  38. k>>=1;
  39. s=matrixmul(s,s);
  40. }
  41. return ans;
  42. }
  43. int main()
  44. {
  45. int n;
  46. while(scanf("%d",&n)!=EOF)
  47. {
  48. int ans;
  49. if(n==-1)
  50. break;
  51. if(n==0)
  52. ans=0;
  53. else
  54. {
  55. node s;
  56. s.init();
  57. s=mul(s,n-1);
  58. ans=s.a[0][1]%mod;
  59. }
  60. printf("%d\n",ans);
  61. }
  62. return 0;
  63. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注