1

I know that BigInteger is the class to use when handling really large numbers. I wrote a simple script that calculates factorial. However, it breaks at input 25 and above.

/**
*    Calculates the factorial of a given number
*/
BigInteger fact(long n){
     def fact = 1
     while(n > 0){
         fact *= n--
     }
     return fact
}  

What is the right way to handle numbers as large as 100! ?

An SO User
  • 24,612
  • 35
  • 133
  • 221

2 Answers2

4

Just declare fact as a BigInteger with Groovy's G suffix:

BigInteger fact(long n){
     def fact = 1G
     while(n > 0){
         fact *= n--
     }
     return fact
}  

assert fact(30) == 265252859812191058636308480000000
assert fact(25) == 15511210043330985984000000
assert fact(100) == 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Will
  • 14,348
  • 1
  • 42
  • 44
0

You may try like this:

import static java.math.BigInteger.ONE

static BigInteger fact(BigInteger num) {
    num.equals(ONE) ? ONE : num.multiply(fact(num.subtract(ONE)));
}

Also check the answer given by Peter here: When calculating the factorial of 100 (100!) with Java using integers I get 0

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • Explanation, please :) – An SO User Sep 07 '14 at 18:40
  • 1
    @LittleChild:- The link which I have posted has the explanation as to why you are getting a zero pr negative number. I think its because of the overflow as the most probable guess is that the fact is taking it as long rather than BigInteger. – Rahul Tripathi Sep 07 '14 at 18:41
  • 1
    @LittleChild:- You may try to change the method defintion as `BigInteger fact(BigInteger n){` or `BigInteger fact(long n){ def fact = 1G`and check the result. – Rahul Tripathi Sep 07 '14 at 18:45