Repository navigation
Expand file tree
/
Copy pathday16.cpp
More file actions
82 lines (80 loc) · 1.83 KB
/
Copy pathday16.cpp
File metadata and controls
82 lines (80 loc) · 1.83 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
void countdown(int n){
if (n==0){
return ;
}
cout<<n<<endl;
countdown(n-1);
}
int sum(int n){
if (n==0) return 0;
return n+sum(n-1);
}
double power_fn(double n, double x ){
if (n==0.0) return 0.0;
if (x==0.0) return 1.0;
double result=pow(n,x);
return result;
}
double fast_power_fn(double n , double x ){
if (n==0) return 0.0;
if (x==0) return 1.0;
if (x<0) return 1.0/fast_power_fn(n, -x);
double half=fast_power_fn(n,floor(x/2));
if (fmod(x ,2.0)==0.0) {
return half * half;
}
return n * half * half;
}
int product_using_addition(int a, int b){
if (a==0 || b==0) return 0;
int result= a+ product_using_addition(a,b-1);
return result;
}
int factorial(int n){
if (n==0){
return 1;
}
cout<<"factorial("<<n<<")="<<n<<"*factorial("<<n-1<<")"<<endl;
int p=n*factorial(n-1);
cout<<"factorial "<<n<<"="<<p<<endl;
return p;
}
int fibonnaci(int n){
if (n==0){
return 0;
}
if (n==1){
return 1;
}
return fibonnaci(n-1)+fibonnaci(n-2);
}
map<int,int>memo;
int fibonnaci_fast(int n){
if (memo.count(n)) return memo[n];
if (n==0) return 0;
if (n==1) return 1;
memo[n]=fibonnaci_fast(n-1)+fibonnaci_fast(n-2);
return memo[n];
}
int main(){
countdown(5);
cout<<"sum = "<<sum(5)<<endl;
cout<<"power= "<<power_fn(4.0,5.0)<<endl;
cout<<factorial(5)<<endl;
cout<<"fast power= "<<fast_power_fn(6.0,7.0)<<endl;
cout<<"multiply= "<<product_using_addition(6,9)<<endl;
cout<<"digit counter= "<<countdown;
for (int i=0;i<30;++i){
cout<<fibonnaci(i)<<" ";
}
cout<<endl;
for (int i=0;i<30;++i){
cout<<fibonnaci_fast(i)<<" ";
}
cout<<endl;
return 0;
}