nickel2halide

fibo

Nov 7th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. /*
  2. PROG: fibo
  3. LANG: C++
  4. */
  5.  
  6. #define PROG "fibo"
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <math.h>
  11. #include <string.h>
  12. #include <assert.h>
  13.  
  14. #include <algorithm>
  15. #include <iterator>
  16. #include <vector>
  17. #include <list>
  18. #include <stack>
  19. #include <queue>
  20. #include <string>
  21.  
  22. using namespace std;
  23.  
  24. #define DMP(_fmt, ...) fprintf(stderr, "[file %s, line %d]:" _fmt, __FILE__, __LINE__, __VA_ARGS__)
  25.  
  26. typedef list<int>::iterator liit;
  27. typedef pair<int, int> pii;
  28. typedef unsigned long long ull;
  29.  
  30. FILE *fin, *fout;
  31.  
  32. // constants and givens/pseudo-constants
  33. // const int MAXN = 1005;
  34. // int N;
  35. const int INF = 999999999;
  36. const long MOD = 1000000007;
  37. const int MAXN = 500005;
  38. int N;
  39.  
  40. // variables
  41. // int nfoo, a[MAXN];
  42. struct mat22 {
  43.   long a, b;
  44.   long c, d;
  45. } fibo[MAXN]; // the awesome way to compute fibonnaci numbers
  46. mat22 temp;
  47.  
  48. void matmult(const mat22& m1, const mat22& m2, long& a, long& b, long& c, long& d) {
  49.   a = ((m1.a * m2.a) % MOD + (m1.b * m2.c) % MOD) % MOD;
  50.   b = ((m1.a * m2.b) % MOD + (m1.b * m2.d) % MOD) % MOD;
  51.  
  52.   c = ((m1.c * m2.a) % MOD + (m1.d * m2.c) % MOD) % MOD;
  53.   d = ((m1.c * m2.b) % MOD + (m1.d * m2.d) % MOD) % MOD;
  54. } // one shit-ton of ugly coming right up
  55.  
  56. void compute(int n);
  57. void solve() {
  58.   compute(N);
  59. }
  60.  
  61. void compute(int n) {
  62.   if(n < 2) {
  63.     return;
  64.   }
  65.   compute(n / 2);
  66.   long a, b, c, d;
  67.   matmult(fibo[n / 2], fibo[n / 2], a, b, c, d);
  68.   if(n & 1) {
  69.     temp = (mat22) {a, b, c, d};
  70.     matmult(temp, fibo[1], a, b, c, d);
  71.   }
  72.   fibo[n] = (mat22) {a, b, c, d};
  73. }
  74.  
  75. void init() {
  76.   fibo[0] = (mat22) {1, 0, 1, 0};
  77.   fibo[1] = (mat22) {1, 1, 1, 0};
  78. }
  79.  
  80. void input() {
  81.   // fscanf(fin, "%d", &N);
  82.   // for(int i = 0; i < N; ++i) {
  83.   //   fscanf(fin, "%d", a+i);
  84.   // }
  85.   fscanf(fin, "%d", &N);
  86. }
  87.  
  88. void output() {
  89.   // fprintf(fout, "%d\n", nfoo);
  90.   fprintf(fout, "%ld\n", fibo[N].b);
  91. }
  92.  
  93. int main(int argc, char** argv)
  94. {
  95.   fin = fopen(PROG ".in", "r");
  96.   fout = fopen(PROG ".out", "w");
  97.   assert(fin != NULL);
  98.   assert(fout != NULL);
  99.  
  100.   init();
  101.   input();
  102.   solve();
  103.   output();
  104.  
  105.   fclose(fin);
  106.   fclose(fout);
  107.  
  108.   exit(0);
  109. }
  110.  
  111.  
Advertisement
Add Comment
Please, Sign In to add comment