-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFibonacciRec.cpp
More file actions
59 lines (56 loc) · 1.3 KB
/
Copy pathFibonacciRec.cpp
File metadata and controls
59 lines (56 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <algorithm>
using namespace std;
static int fib(int n) {
if(n <=0)
return 0;
else if(n==1)
return 1;
else
return fib(n-1) + fib(n-2);
}
static int fibMemo(int n,int * memo) {
if(n <=0)
return 0;
else if(n==1)
return 1;
else if(!memo[n]){
memo[n] = fibMemo(n-1,memo) + fibMemo(n-2,memo);
}
return memo[n];
}
static long long fibRec(int n, long long & prev, long long & next) {
if(n==0)
return next;
else {
long long old = next;
next += prev;
prev = old;
fibRec(n-1, prev, next);
}
}
static long long fibTail(int n){
long long prev = 0, next = 1;
//Fib0, Fib1 are calculated so we need to calculated n-1 times on tail
return fibRec(n-1, prev, next);
}
static int fibIterative(int n) {
int fibPrev =0;
int fib=1;
int index =1;
//n-1 times more
while(index++<n){
int temp = fib;
fib +=fibPrev;
fibPrev = temp;
}
return fib;
}
int main(){
cout<<fib(10)<<endl;
cout<<fibIterative(10)<<endl;
cout<<fibTail(10)<<endl;
int memo[11] = {0};
cout<<fibMemo(10,memo)<<endl;
return 0;
}