File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
src/main/java/com/thealgorithms/recursion Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments