forked from msdohehrty/dsa555-s16
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursion.cpp
82 lines (74 loc) · 1.26 KB
/
recursion.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "timer.h"
#include <iostream>
#include <cstdlib>
using namespace std;
unsigned int iterativeFib(unsigned int n);
unsigned int fib(unsigned int n);
int main(int argc, char* argv[]){
unsigned int v=atoi(argv[1]);
unsigned int result;
Timer t1;
Timer t2;
t1.start();
result=iterativeFib(v);
t1.stop();
cout << "result is: " << result << ". It took " << t1.currtime() << " seconds"<< endl;
t2.start();
result=fib(v);
t2.stop();
cout << "result is: " << result << ". It took " << t2.currtime() << " seconds"<< endl;
}
unsigned int iterativeFib(unsigned int n){
int first=0;
int second=1;
int result;
if(n>=2){
while(n>=2){
result=first+second;
first=second;
second = result;
n--;
}
}
else{
result=n;
}
return result;
}
unsigned int fib(unsigned int n){
int result;
if(n == 0){
result=0;
}
else if(n == 1){
result=1;
}
else{
result=fib(n-1) + fib(n-2);
}
return result;
}
double power(double base, int n){
double result;
if(n == 0){
result = 1;
}
else{
result = power(base,n/2);
result = result * result;
//if n is odd
if(n % 2 == 1){
result =result *base;
}
}
}
double power2(double base, int n){
double result;
if(n == 0){
result = 1;
}
else{
result = base*power2(base,n-1);
}
return result;
}