File tree Expand file tree Collapse file tree 3 files changed +13
-28
lines changed Expand file tree Collapse file tree 3 files changed +13
-28
lines changed Original file line number Diff line number Diff line change 1
-
2
1
#include < iostream>
3
2
4
3
using namespace std ;
5
4
6
- int fibonacciIterative (int n)
7
- {
5
+ int fibonacci (int n) {
8
6
int last = 0 ;
9
7
int curr = 1 ;
10
- for (int index = 0 ; index < n; ++index)
11
- {
8
+ for (int index = 0 ; index < n; ++index) {
12
9
int temp = curr;
13
10
curr += last;
14
11
last = temp;
15
12
}
16
13
return last;
17
14
}
18
15
19
- int main ()
20
- {
21
- cout << fibonacciIterative (12 ) << endl;
16
+ int main () {
17
+ cout << fibonacci (12 ) << endl;
22
18
}
Original file line number Diff line number Diff line change @@ -5,15 +5,15 @@ using namespace std;
5
5
6
6
vector<int > memo;
7
7
8
- int fibonacciMemoization (int n) {
8
+ int fibonacci (int n) {
9
9
if (n <= 1 ) {
10
10
return n;
11
11
}
12
12
if (memo[n] != -1 ) {
13
13
return memo[n];
14
14
}
15
15
16
- memo[n] = fibonacciMemoization (n - 1 ) + fibonacciMemoization (n - 2 );
16
+ memo[n] = fibonacci (n - 1 ) + fibonacci (n - 2 );
17
17
return memo[n];
18
18
}
19
19
@@ -23,6 +23,6 @@ int main() {
23
23
// Initialize the memoization table with -1 (uncomputed)
24
24
memo.assign (test_nbr + 1 , -1 );
25
25
26
- cout << " memoization: " << fibonacciMemoization (test_nbr) << endl;
26
+ cout << " memoization: " << fibonacci (test_nbr) << endl;
27
27
return 0 ;
28
28
}
Original file line number Diff line number Diff line change 1
-
2
1
#include < iostream>
3
2
4
3
using namespace std ;
5
4
6
- int fibonacciRecursive (int n)
7
- {
8
- if (n == 0 )
9
- {
10
- return 0 ;
11
- }
12
- else if (n == 1 )
13
- {
14
- return 1 ;
15
- }
16
- else
17
- {
18
- return fibonacciRecursive (n-1 ) + fibonacciRecursive (n-2 );
5
+ int fibonacci (int n) {
6
+ if (n <= 1 ) {
7
+ return n;
19
8
}
9
+ return fibonacci (n-1 ) + fibonacci (n-2 );
20
10
}
21
11
22
- int main ()
23
- {
24
- cout << fibonacciRecursive (12 ) << endl;
12
+ int main () {
13
+ cout << fibonacci (12 ) << endl;
25
14
}
You can’t perform that action at this time.
0 commit comments