Guest User

Untitled

a guest
Mar 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. //POJ 3070
  2. /*
  3. 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:
  4.  
  5. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
  6.  
  7.  
  8. Given an integer n, your goal is to compute the last 4 digits of Fn.
  9.  
  10. Input
  11.  
  12. 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.
  13.  
  14. Output
  15.  
  16. 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).
  17. */
  18.  
  19. #include <cstdio>
  20. #include <cstring>
  21. #include <algorithm>
  22. #include <cmath>
  23. using namespace std;
  24.  
  25. const int MOD = 10000;
  26.  
  27. struct Matrix {
  28. int m[2][2];
  29.  
  30.  
  31. Matrix operator * (const Matrix& rhs)
  32. {
  33. Matrix matrix = {0, 0, 0, 0};
  34. for(int i = 0; i < 2; ++i)
  35. for(int j = 0; j < 2; ++j)
  36. for(int k = 0; k < 2; ++k)
  37. matrix.m[i][j] = (matrix.m[i][j] + (m[i][k] * rhs.m[k][j]) % MOD) % MOD;
  38. return matrix;
  39. }
  40. }f;
  41.  
  42. Matrix base = {1, 1, 1, 0};
  43.  
  44.  
  45. int pow(Matrix& matrix, int n)
  46. {
  47. Matrix res = {1, 0, 0, 1};
  48. while(n)
  49. {
  50. if(n & 1)
  51. res = res * matrix;
  52. matrix = matrix * matrix;
  53. n >>= 1;
  54. }
  55. return res.m[0][1];
  56. }
  57.  
  58.  
  59. int main() {
  60. int n;
  61. while(~scanf("%d",&n))
  62. {
  63. if(n == -1)break;
  64. base.m[0][0] = 1;
  65. base.m[0][1] = 1;
  66. base.m[1][0] = 1;
  67. base.m[1][1] = 0;
  68. printf("%d\n", pow(base, n));
  69. }
  70. return 0;
  71. }
Add Comment
Please, Sign In to add comment