forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoubleFactorial.java
85 lines (74 loc) · 2 KB
/
DoubleFactorial.java
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
84
85
/**
* In mathematics, the double factorial or semi-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.
*/
import java.util.*;
public class DoubleFactorial {
// Recursive approach
private static int recursiveDoubleFactorial(int num) {
// checking for 1 and 0
if (num == 0 || num == 1) {
return 1;
}
// using recursion
return num * recursiveDoubleFactorial(num - 2);
}
// Iterative approach
private static int iterDoubleFactorial(int num) {
int result = 1;
// using iterations
for (int i = num; i >= 0; i = i - 2) {
if (i == 0 || i == 1) {
return result;
} else {
result *= i;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
int num = sc.nextInt();
System.out.println("Which approach would you like to use?");
System.out.println("1. Recursive");
System.out.println("2. Iterative");
int ch = sc.nextInt();
sc.close();
int result;
switch (ch) {
case 1:
result = recursiveDoubleFactorial(num);
System.out.println("Double factorial:" + result);
break;
case 2:
result = iterDoubleFactorial(num);
System.out.println("Double factorial:" + result);
break;
default:
System.out.println("Invalid choice.");
}
}
}
/**
* Sample input/output
* Enter the number:
* 5
* Which approach would you like to use?
* 1. Recursive
* 2. Iterative
* 1
* Double factorial:15
*
* Enter the number:
* 6
* Which approach would you like to use?
* 1. Recursive
* 2. Iterative
* 2
* Double factorial:48
*
* Time complexity for both the approaches is O(n)
*/