BigInteger... help me!!
Hi,
Can anyone help me. I used BigInteger to calculate the factorial. Howeverit always printed error when I insert a number upto 4000.
import java.io.*;
import java.math.BigInteger;
// A class represents factorial calculation.
public class Factorial
{
// main method of the program.
public static void main( String[] args )
{
boolean finish = false;
// continue calculating
while( !finish ) {
// handle input from user.
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
// print welcome.
System.out.println("Please enter number. Enter -1 to finish: ");
String answer = "";
// read input from user and convert to a BigInteger number.
try {
answer += input.readLine();
}
catch( IOException e ) {
System.out.println("Unable to read line.");
}
BigInteger number = new BigInteger(answer);
int compare = number.compareTo(new BigInteger("-1"));
// finish rogram when -1 is entered.
if( compare == 0 )
finish = true;
else {
//calculate factorial and print result.
BigInteger result = (new Factorial()).factorial(number);
System.out.println(number.toString() + "! = " + result.toString());
}
}
}
//a recursive method to calculate factorial.
public BigInteger factorial( BigInteger number )
{
int compare = number.compareTo( new BigInteger("1"));
// base case when n = 1 or n = 0.
if(( compare == 0) || (compare == -1))
return new BigInteger("1");
else {
BigInteger i1 = new BigInteger("1");
BigInteger i2 = number.subtract(i1);
BigInteger less = factorial(i2);
return number.multiply(less);
}
}
}
Thanks,
Paris

