Alex_tz307

Kth Fibonacci

Sep 12th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. //https://www.pbinfo.ro/articole/19411/Matrice%20Fibonacci
  2. #include <bits/stdc++.h>
  3. #define MOD 666013
  4.  
  5. using namespace std;
  6.  
  7. ifstream f("kfib.in");
  8. ofstream g("kfib.out");
  9.  
  10. long long a[5][5], b[5][5], c[5][5], sol[5][5];
  11.  
  12. void inmultire_matrice(long long a[5][5],long long b[5][5]) {
  13.     for(int i = 1; i <=2; ++i)
  14.         for(int j = 1; j <= 2; ++j) {
  15.             long long s = 0;
  16.             for(int k = 1; k <= 2; ++k)
  17.                 s = (s + a[i][k] * b[k][j]) % MOD;
  18.             c[i][j] = s % MOD;
  19.         }
  20.     for(int i = 1; i <= 2; ++i)
  21.         for(int j = 1; j <= 2; ++j)
  22.             a[i][j] = c[i][j];
  23. }
  24.  
  25. void pow_log(long long k) {
  26.     while(k > 0) {
  27.         if(k & 1)
  28.             inmultire_matrice(sol, b);
  29.         inmultire_matrice(b, b);
  30.         k >>= 1;
  31.     }
  32. }
  33.  
  34. int main() {
  35.     long long n;
  36.     f >> n;
  37.     if(n == 0)
  38.         g << 0;
  39.     else {
  40.         a[1][2] = b[1][2] = b[2][1] = b[2][2] = sol[1][1] = sol[2][2] = 1;
  41.         pow_log(n - 1);
  42.         inmultire_matrice(a, sol);
  43.         g << a[1][2];
  44.     }
  45. }
  46.  
Add Comment
Please, Sign In to add comment