Skip to content

Commit a5ddd9d

Browse files
authored
Merge pull request #339 from Prakash5bisht/version2
nth fibonacci term using matrix.
2 parents aa02f2a + d3ac6dd commit a5ddd9d

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

fibonacciNumberUsingMatrix.cpp

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Program to find the nth fibonacci term
2+
3+
// what is fibonacci series?
4+
// A series is said to be fibonacci if every nth term is the sum of (n-1)th and (n-2)th term. 0 1 1 2 3 5 8,..... is the fibonacci series
5+
6+
/*
7+
According to this method, to get the nth fibonacci number, we need to multiply matrix [[1,1],[1,0]] to
8+
itself (n-1) times. Then, the [0,0]th element of this resultant matrix will be the required nth fibonacci number
9+
*/
10+
11+
#include <cstdio>
12+
#include<stdlib.h>
13+
#include<iomanip>
14+
#include<iostream>
15+
using namespace std;
16+
17+
void multiply(int Fib[2][2], int mat[2][2])
18+
{
19+
20+
int topleft = Fib[0][0] * mat[0][0] + Fib[0][1] * mat[1][0];
21+
int topRight = Fib[0][0] * mat[0][1] + Fib[0][1] * mat[1][1];
22+
int bottomLeft = Fib[1][0] * mat[0][0] + Fib[1][1] * mat[1][0];
23+
int bottomRight = Fib[1][0] * mat[0][1] + Fib[1][1] * mat[1][1];
24+
25+
Fib[0][0] = topleft;
26+
Fib[0][1] = topRight;
27+
Fib[1][0] = bottomLeft;
28+
Fib[1][1] = bottomRight;
29+
}
30+
31+
void power(int Fib[2][2], int n)
32+
{
33+
34+
if(n == 0 || n == 1)
35+
return;
36+
int mat[2][2] = {{1, 1}, {1, 0}};
37+
38+
power(Fib, n / 2);
39+
multiply(Fib, Fib);
40+
41+
if (n % 2 != 0)
42+
multiply(Fib, mat);
43+
}
44+
45+
46+
int fibonacci(int n)
47+
{
48+
int Fib[2][2] = {{1, 1}, {1, 0}};
49+
if (n == 0)
50+
return 0;
51+
power(Fib, n - 1);
52+
53+
return Fib[0][0];
54+
}
55+
56+
57+
int main()
58+
{
59+
system("cls");
60+
int n;
61+
cout<<"Enter the nth fibonaci you want to know: ";
62+
cin>>n;
63+
cout << fibonacci(n)<<endl;
64+
fflush(stdin);
65+
getchar();
66+
return 0;
67+
}
68+

fibonacciNumberUsingMatrix.exe

49.2 KB
Binary file not shown.

0 commit comments

Comments
 (0)