0

So I've been trying to get big factorials like 50 using BigInteger. But when i run this program in cmd, i get unexpected error at line 16: fact=fact.multiply(new BigInteger(getFactorial(n-1))). I am not even able to see the thrown exception as it gets scrolled out. Please help me find the error.

import java.math.BigInteger;
class FactorialUsingRecursion {

public static void main(String args[]) {
    int num=50;
    String fact=getFactorial(num);
    System.out.println(num+"! = "+fact);
}

static String getFactorial(int n) {
    BigInteger fact=new BigInteger(n+"");

    if(fact.toString()=="1") {
        return "1";
    }
    fact=fact.multiply(new BigInteger(getFactorial(n-1)));//error line
    return fact.toString();
}
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Bhavik
  • 346
  • 4
  • 11
  • 3
    Why on earth are you using Strings to multiply 2 numbers? –  Mar 11 '16 at 13:24
  • Don't compare Strings with `==` – Eran Mar 11 '16 at 13:25
  • Big factorials like 50 cannot be contained in primitive data types like even long. U can see the recursive call in the multiplication – Bhavik Mar 11 '16 at 13:26
  • You are comparing string incorrectly which is why it is likely to be running out of memory, however you shouldn't be using string in the first place. – Peter Lawrey Mar 11 '16 at 13:26
  • Why isn't `getFactorial()` returning a `BigInteger` instead of a String? – Eran Mar 11 '16 at 13:27
  • because BigInteger takes String as its argument – Bhavik Mar 11 '16 at 13:29
  • 2
    Why not compare to [`BigInteger.ONE`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#ONE)? e.g. `fact.equals(BigInteger.ONE)`. – Andy Turner Mar 11 '16 at 13:30
  • I used BigInteger first time..kind of new to java...so i m not aware of all its functionalities – Bhavik Mar 11 '16 at 13:31
  • I got my solution however in the answer below..i was incorrectly comparing strings as per Lawrey, Thank you – Bhavik Mar 11 '16 at 13:34

1 Answers1

1

The problem is with String comparison in if condition. Change that if condition to the following:

if(fact.intValue() == 1) {
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102