forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorial.java
More file actions
30 lines (24 loc) · 791 Bytes
/
Factorial.java
File metadata and controls
30 lines (24 loc) · 791 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
import java.util.Scanner;
public class Factorial {
// Iterative method
public static long factorialIterative(int n) {
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Recursive method
public static long factorialRecursive(int n) {
if (n == 0 || n == 1) return 1;
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
System.out.println("Factorial (Iterative): " + factorialIterative(n));
System.out.println("Factorial (Recursive): " + factorialRecursive(n));
sc.close();
}
}