Skip to content

Commit db3369e

Browse files
author
jsquared21
committed
Add Ex 18.1
1 parent 41c12ed commit db3369e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Diff for: Exercise_18/Exercise_18_01/Exercise_18_01.class

1.21 KB
Binary file not shown.

Diff for: Exercise_18/Exercise_18_01/Exercise_18_01.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*********************************************************************************
2+
* (Factorial) Using the BigInteger class introduced in Section 10.9, you can *
3+
* find the factorial for a large number (e.g., 100!). Implement the factorial *
4+
* method using recursion. Write a program that prompts the user to enter an *
5+
* integer and displays its factorial. *
6+
*********************************************************************************/
7+
import java.util.Scanner;
8+
import java.math.*;
9+
10+
public class Exercise_18_01 {
11+
/** Main method */
12+
public static void main(String[] args) {
13+
// Create a Scanner
14+
Scanner input = new Scanner(System.in);
15+
System.out.print("Enter an integer: ");
16+
String n = input.nextLine();
17+
18+
// Display factorial
19+
System.out.println("Factorial of " + n + " is "
20+
+ factorial(new BigInteger(n)));
21+
}
22+
23+
/** Retrun the factorial for the specified number */
24+
public static BigInteger factorial(BigInteger n) {
25+
if (n.equals(BigInteger.ZERO)) // Base case
26+
return BigInteger.ONE;
27+
else // Recursive call
28+
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
29+
}
30+
}

0 commit comments

Comments
 (0)