forked from joeyajames/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorial.java
More file actions
42 lines (37 loc) · 887 Bytes
/
Copy pathFactorial.java
File metadata and controls
42 lines (37 loc) · 887 Bytes
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
import java.util.Scanner;
public class Factorial {
private static String space = " ";
@SuppressWarnings("resource")
public static void main(String[] args) {
Factorial factorial = new Factorial();
Scanner in = new Scanner(System.in);
int num = 0;
do
{
num = in.nextInt();
System.out.println(factorial.getRecursiveFactorial(num));
System.out.println(factorial.getIterativeFactorial(num));
}
while (num != 0);
}
public int getRecursiveFactorial(int n) {
System.out.print(n);
System.out.print(space);
if (n < 0)
return -1;
else if (n < 2)
return 1;
else
return (n * getRecursiveFactorial(n - 1));
}
public int getIterativeFactorial(int n) {
System.out.print(n);
System.out.print(space);
if (n < 0)
return -1;
int fact = 1;
for (int i = 1; i <= n; i++)
fact *= i;
return fact;
}
}