forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
double_factorial.cpp
70 lines (61 loc) · 1.33 KB
/
double_factorial.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
//double factorial of a number n (denoted by n!!) is the product of all the integers from 1 up to n that have the same parity(odd or even) as n.
//algorithm to find the double factorial of a number n in O(n) time complexity and O(1) space complexity
#include <bits/stdc++.h>
using namespace std;
int Recursive(int num) //recursive approach
{
if (num == 0 || num == 1)
{
return 1;
}
return num * Recursive(num - 2);
}
int Iterative(int num) // Iterative approach
{
int ans = 1;
for (int i = num; i >= 0; i = i - 2)
{
if (i == 0 || i == 1)
{
return ans;
}
else
{
ans *= i;
}
}
return ans;
}
int main() {
//taking input from the user
int num;
cout << "Please Enter a number\n";
cin >> num;
cout << "Which way would you like to use?\n";
cout << "1. Iterative\n";
cout << "2. Recursive\n";
int way;
cin >> way;
if (way == 1)
{
cout << Iterative(num) << endl;
}
else if (way == 2)
{
cout << Recursive(num) << endl;
}
else
{
cout << "Invalid choice" << endl;
}
return 0;
}
/*
Sample input/output
Enter the number:
13
Which way would you like to use?
1 Iterative
2 Recursive
Output = 135135
*/