-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_fac_fib.cpp
83 lines (78 loc) · 1.29 KB
/
stack_fac_fib.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
83
#include <iostream>
#include <cstdlib>
using namespace std;
int n = 20;
int MAX = n;
int stack[20];
// int stack2[10];
int top = -1;
void push(int n)
{
if (top == MAX - 1)
{
cout << "stack is full" << endl;
return;
}
stack[++top] = n;
}
int pop()
{
if (top == -1)
{
cout << "stack is empty" << endl;
return -1;
}
int a = stack[top];
top--;
return a;
}
int fact_loop(int n)
{
int k = 1;
if (n == 0)
return 1;
else
{
for (int i = 1; i <= n; i++)
{
k *= i;
push(k);
}
return stack[n - 1];
}
}
int fact_recur(int n)
{
int result = 1;
while (n != 0)
{
push(n--);
result *= pop();
}
return result;
}
int fib_loop(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
int a = 0, b = 1;
push(a);
push(b);
for (int i = 2; i < n; i++)
{
a = a + b;
push(a);//
b = a + b;
push(b);
}
return stack[n];
}
int main()
{
// cout << fact_loop(5) << endl;
// cout << fact_recur(5) << endl;
// cout << fib_loop(5) << endl;
cout << fib_loop(10) << endl;
}