Skip to content

Commit 9d340b9

Browse files
IMPROVE fibonacci algorithms, add constant time solution
1 parent 3b167d1 commit 9d340b9

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

Algorithms/fibonacci.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
#include <vector>
44
#include <map>
5+
#include <math.h>
56

67
using namespace std;
78

@@ -77,6 +78,14 @@ int fib5(int num) {
7778
return res;
7879
}
7980

81+
/** Constant time solution from solving a recurrence relation :) */
82+
int fib6(float num) {
83+
float sqrt5 = sqrt(5);
84+
85+
return ( 1.0/sqrt5*pow(0.5+sqrt5/2.0, num) - 1.0/sqrt5*pow(0.5-sqrt5/2.0, num) );
86+
}
87+
88+
8089

8190
int main(void) {
8291
int num;
@@ -91,5 +100,11 @@ int main(void) {
91100

92101
cout << "fib 3: " << fib3(num) << endl;
93102

103+
cout << "fib 4: " << fib4(num) << endl;
104+
105+
cout << "fib 5: " << fib5(num) << endl;
106+
107+
cout << "fib 6: " << fib6(num) << endl;
108+
94109
return 0;
95110
}

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ Click to expand the 43 *C++ programs*!
8787
- You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
8888
- Leetcode problem [here](https://leetcode.com/problems/destination-city/)
8989
- fibonacci.cpp
90-
- five ways of making the fibonacci sequence
91-
- naive recursive, two memoized recursive, two sequential
90+
- six ways of making the fibonacci sequence
91+
- naive recursive, two memoized recursive, two sequential, one constant
9292
- flippingAnImage.cpp
9393
- Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
9494
- Leetcode problem [here](https://leetcode.com/problems/flipping-an-image/)

0 commit comments

Comments
 (0)