Skip to content

Commit 3e7f6a3

Browse files
Add recursive implementation of Factorial with user input
1 parent d927d00 commit 3e7f6a3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.thealgorithms.recursion;
2+
3+
import java.util.Scanner;
4+
5+
/**
6+
* This class provides a recursive implementation of the factorial function.
7+
* The factorial of a number n is defined as n! = n × (n-1) × (n-2) × ... × 1
8+
* with the base case 0! = 1.
9+
*/
10+
public class Factorial {
11+
12+
/**
13+
* Recursive method to calculate factorial.
14+
*
15+
* @param n the number to find factorial of
16+
* @return factorial of n
17+
* @throws IllegalArgumentException if n is negative
18+
*/
19+
public static long factorial(int n) {
20+
if (n < 0) {
21+
throw new IllegalArgumentException("Number must be non-negative");
22+
}
23+
if (n == 0 || n == 1) {
24+
return 1;
25+
}
26+
return n * factorial(n - 1);
27+
}
28+
29+
// Main method with user input
30+
public static void main(String[] args) {
31+
Scanner scanner = new Scanner(System.in);
32+
System.out.print("Enter a number to find its factorial: ");
33+
34+
int num = scanner.nextInt();
35+
scanner.close();
36+
37+
try {
38+
long result = factorial(num);
39+
System.out.println("Factorial of " + num + " is: " + result);
40+
} catch (IllegalArgumentException e) {
41+
System.out.println(e.getMessage());
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)