-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathFactorial.java
More file actions
27 lines (22 loc) · 766 Bytes
/
Factorial.java
File metadata and controls
27 lines (22 loc) · 766 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
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = calculateFactorial(n);
System.out.println("The factorial of " + n + " is: " + factorial);
}
scanner.close();
}
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}