Advertisement
joydip007x

GKG FIbonacci (works 5000+)

Oct 23rd, 2018
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. #include <stdio.h>
  2. #include<iostream>
  3. using namespace std;
  4. #define ll unsigned long long
  5. /* Helper function that multiplies 2 matrices F and M of size 2*2, and
  6. puts the multiplication result back to F[][] */
  7. void multiply(ll F[2][2], ll M[2][2]);
  8.  
  9. /* Helper function that calculates F[][] raise to the power n and puts the
  10. result in F[][]
  11. Note that this function is designed only for fib() and won't work as general
  12. power function */
  13. void power(ll F[2][2], ll n);
  14.  
  15. ll fib(ll n)
  16. {
  17. ll F[2][2] = {{1,1},{1,0}};
  18. if (n == 0)
  19. return 0;
  20. power(F, n-1);
  21.  
  22. return F[0][0];
  23. }
  24.  
  25. void multiply(ll int F[2][2], ll int M[2][2])
  26. {
  27. ll x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
  28. ll int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
  29. ll int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
  30. ll int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
  31.  
  32. F[0][0] = x;
  33. F[0][1] = y;
  34. F[1][0] = z;
  35. F[1][1] = w;
  36. }
  37.  
  38. void power(ll F[2][2],ll int n)
  39. {
  40. ll int i;
  41. ll int M[2][2] = {{1,1},{1,0}};
  42.  
  43. // n - 1 times multiply the matrix to {{1,0},{0,1}}
  44. for (i = 2; i <= n; i++)
  45. multiply(F, M);
  46. }
  47.  
  48. /* Driver program to test above function */
  49. int main()
  50. {
  51. ll int n=5010;
  52. cout<<fib(n);
  53. ///printf("%d", fib(n));
  54. getchar();
  55. return 0;
  56. }
  57. //https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement