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 from -2,147,483,647 to 2,147,483,647 ( ). 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));}
}
}
No comments:
Post a Comment