Change the factorial method to return a BigInteger. You can leave the parameter
ID: 3687098 • Letter: C
Question
Change the factorial method to return a BigInteger. You can leave the parameter value alone (ie, the parameter will remain an integer). You'll need to modify the method to use
BigInteger objects and instance methods.
Hint: remember that you can easily form Strings from numerical values by concatenating the numerical value with the empty String "". For
Example:
String s = 5 + "";
•What happens when you rerun your loop in main? Do you get the correct answers?
import java.math.BigInteger;
public class Lab10 {
public static int factorial(int n) {
int result = 1;
for(int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
for(int i = 1; i < 31; i++) {
System.out.println(i + " " + factorial(i));
}
}
}
Explanation / Answer
Yes. If we use BigInteger, will get correct answers.
Lab10.java
import java.math.BigInteger;
public class Lab10 {
public static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for(int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
for(int i = 1; i < 31; i++) {
System.out.println(i + " " + factorial(i));
}
}
}
Output:
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 6227020800
14 87178291200
15 1307674368000
16 20922789888000
17 355687428096000
18 6402373705728000
19 121645100408832000
20 2432902008176640000
21 51090942171709440000
22 1124000727777607680000
23 25852016738884976640000
24 620448401733239439360000
25 15511210043330985984000000
26 403291461126605635584000000
27 10888869450418352160768000000
28 304888344611713860501504000000
29 8841761993739701954543616000000
30 265252859812191058636308480000000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.