fork download
  1. #include <iostream>
  2. using namespace std;
  3. void multiply(int F[2][2], int M[2][2]) {
  4. int a = F[0][0] * M[0][0] + F[0][1] * M[1][0];
  5. int b= F[0][0] * M[0][1] + F[0][1] * M[1][1];
  6. int c = F[1][0] * M[0][0] + F[1][1] * M[1][0];
  7. int d = F[1][0] * M[0][1] + F[1][1] * M[1][1];
  8. F[0][0] = a;
  9. F[0][1] = b;
  10. F[1][0] = c;
  11. F[1][1] = d;
  12. }
  13. void power(int F[2][2], int n) {
  14. if (n == 0 || n == 1)
  15. return;
  16. int M[2][2] = {{1,1},{1,0}};
  17. power(F, n / 2);
  18. multiply(F, F);
  19. if (n % 2 != 0)
  20. multiply(F, M);
  21. }
  22. int fibonacci_matrix(int n) {
  23. int F[2][2] = {{1,1},{1,0}};
  24. if (n == 0)
  25. return 0;
  26. power(F, n - 1);
  27. return F[0][0];
  28. }
  29. int main() {
  30. int n;
  31. cout<<"Enter the number ";
  32. cin>>n;
  33. cout<<fibonacci_matrix(n)<<endl;
  34. return 0;
  35. }
Success #stdin #stdout 0s 15232KB
stdin

stdout
Enter the number 0