Reputation: 565
I am having trouble printing numbers past 12!(factorial).
Can someone please help me out? I'm not even sure if I'm using this class correctly.
public class Application{
public static int factorial(int n){
int index = n;
int total = 1;
while(index > 0){
total *= index;
index --;
}
return total;
}
public static void print(int n){
int index = n;
while(index > 0){
BigInteger big = BigInteger.valueOf(factorial(index));
System.out.println(index + ": " + big);
index --;
}
}
public static void main(String[] args){
int n = 30;
print(n);
}
}
and this is a snippet of what it prints out:
18: -898433024
17: -288522240
16: 2004189184
15: 2004310016
14: 1278945280
13: 1932053504
12: 479001600
Upvotes: 3
Views: 1592
Reputation: 156434
The problem is that you are trying to do "big" math with plain integers (declared as int
, using the multiplication operator *
) and then wrapping in a BigInteger when you should instead be doing math on BigIntegers directly (e.g. using the BigInteger#multiply(...)
method:
public static void main(String[] args) {
BigInteger factorial = BigInteger.ONE;
for (int i=1; i<=20; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
System.out.println(i + "! = " + factorial);
}
}
// 1! = 1
// 2! = 2
// 3! = 6
// ...
// 18! = 6402373705728000
// 19! = 121645100408832000
// 20! = 2432902008176640000
Upvotes: 2
Reputation: 32323
Use BigInteger
in your factorial
function, not "after you've done the calculation".
Note also that when multiplying BigInteger
s, use the BigInteger.multiply(BigInteger val)
method instead of *
.
Here's the changed method, which is exactly the same as yours except it uses BigInteger
instead of int
:
public static BigInteger factorial(int n){
int index = n;
BigInteger total = BigInteger.valueOf(1);
while(index > 0){
total = total.multiply(BigInteger.valueOf(index));
index --;
}
return total;
}
Note that also you don't need to convert the return value of the method to a BigInteger
anymore, e.g. just do:
BigInteger big = factorial(index);
Here's the output:
30: 265252859812191058636308480000000
29: 8841761993739701954543616000000
28: 304888344611713860501504000000
27: 10888869450418352160768000000
26: 403291461126605635584000000
25: 15511210043330985984000000
24: 620448401733239439360000
23: 25852016738884976640000
22: 1124000727777607680000
21: 51090942171709440000
20: 2432902008176640000
19: 121645100408832000
18: 6402373705728000
17: 355687428096000
16: 20922789888000
15: 1307674368000
14: 87178291200
13: 6227020800
12: 479001600
11: 39916800
10: 3628800
9: 362880
8: 40320
7: 5040
6: 720
5: 120
4: 24
3: 6
2: 2
1: 1
Upvotes: 6