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

[1858 byte] By [parisa] at [2007-10-2 13:18:54]
# 1

I didn't run your code, but I'm pretty sure that you're getting a stack overflow due to too many recursive calls (whan posting a question, always supply the compiler error!).

Try to make your method iterative. Something like this:

public BigInteger factorialIterative(BigInteger number) {

BigInteger factorial = new BigInteger("2");

for(int i = 3; i <= number.intValue(); i++)

factorial = factorial.multiply(new BigInteger(String.valueOf(i)));

return factorial;

}

Good luck.

prometheuzza at 2007-7-13 10:52:41 > top of Java-index,Other Topics,Algorithms...
# 2
Thank you, man.Yes, you were right, the iterator method is better, I didn't get the Stackoverflowerror. So I have an experience then.Best wishes.
parisa at 2007-7-13 10:52:41 > top of Java-index,Other Topics,Algorithms...