-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactorial-of-a-number.cpp
More file actions
55 lines (38 loc) · 1.16 KB
/
Copy pathfactorial-of-a-number.cpp
File metadata and controls
55 lines (38 loc) · 1.16 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
#include<bits/stdc++.h>
using namespace std;
/*
Below is an iterative function to calculate the factorial of a whole number
Time complexity: theta(n)
Space complexity: theta(1) (due to fixed number of total variables (input n, extra res), independent of input size)
Auxiliary space: theta(1) (due to fixed number of extra variables (res), independent of input size)
*/
int factorial_i(int n)
{
int res=1;
for(int i=2; i<=n; i++)
{
res=res*i;
}
return res;
}
/*
Below is a recursive function to calculate the factorial of a whole number
Time complexity: theta(n)
Space complexity: theta(n) (due to the function keeping n pending function calls on the call stack)
Auxiliary space: theta(n) (due to the function keeping n pending function calls on the call stack)
*/
int factorial_r(int n)
{
if(n==0)
return 1;
return n*factorial_r(n-1);
}
int main()
{
int n;
cout<<"Enter a whole number: ";
cin>>n;
cout<<"\nFactorial of "<<n<<", using the iterative solution, is "<<factorial_i(n);
cout<<"\n\nFactorial of "<<n<<", using the recursive solution, is "<<factorial_r(n);
return 0;
}