Showing posts with label factorial. Show all posts
Showing posts with label factorial. Show all posts

Monday, December 15, 2014

BigInteger to the rescue


Java's Math library provides BigInteger that can hold any kind of largest number (no idea how BigInteger breaks the barrier of 64 bit and I am looking for an answer)

import java.math.*;

class bigfactorial {
    
public static BigInteger compute(int num) 
    { 
   if(num < 0) 
   { throw new IllegalArgumentException("negative number passed for factorial computation");}
   
   if(num < 2) 
   {return BigInteger.ONE;} 
   
   BigInteger factorial = BigInteger.ONE; 
   
   while(num > 1) 
   {  factorial = factorial.multiply(BigInteger.valueOf(num--)); }
   return factorial; 
    }
    
}

public class biginteger {

public static void main(String args[]){
    for (int i=2; i<25;i++)
    System.out.println("The " + i + " ! is: " 
    + bigfactorial.compute(i));
    }

}



JAVA Program for factorial 20


This JAVA program illustrate the use of long to store the output of factorial 20. 

In JAVA, an int is 4 byte long therefore the largest number starting from 0 that an unsigned int can store is =  (2^32 - 1) OR 4,294,967,295 or to remember easily 4.2x10^9.

To store negative integers we generally sacrifice one bit to indicate the sign of number and use rest of the 31 bits to store the number, therefore signed int can store number fro -2,147,483,647 to 2,147,483,647 ( $\pm 2^{31} - 1$). To remember simply we can say 4.2/2 = 2.1 and therefore signed int can store -2.1x10^9 to +2.1x10^9

Long is 8 bytes long: therefore the largest number that an unsigned long can store starting from 0 is =  (2^64-1) OR 18,446,744,073,709,551,615  OR 1.8X10^19.
Unsigned we can sacrifice one bit and it will be like 0.9x10^19

Now, the problem is how are we going to produce and store a number which is larger than the order of 10^19. 


class calcFactorial
{
long number;
long calculation(long num)
{
  number = num;
    if (number == 1)
  { return 1;}
  else
   return (number * calculation(number-1));
}
}


public class factorial {
public static void main (String[] args)
{
  calcFactorial variable1 = new calcFactorial();
     for (int i=1; i<=21; i++)
{System.out.println("factorial of " + i + " is = " + variable1.calculation(i));}
}
}