Factorial Program in Java

Created with Sketch.

 

Factorial Program in Java

Java program to find factorial of a number, if the number is negative, then an error message is printed. You can also find factorial using recursion. The first program uses integer data type so it can calculate the factorial of small numbers only. Factorial of large numbers using BigInteger.

Factorial of a number in Java

import java.util.Scanner;

class Factorial
{
public static void main(String args[])
{
int n, c, f = 1;

System.out.println(“Enter an integer to calculate its factorial”);
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println(“Number should be non-negative.”);
else
{
for (c = 1; c <= n; c++)
f = f*c;

System.out.println(“Factorial of “+n+” is = “+f);
}
}
}

Output of program:
Java factorial program output

 

Java program for calculating factorial of large numbers

The above program doesn’t give the correct result for calculating factorial of say 20. Because 20! is a large number and can’t be stored in integer data type, which is of 4 bytes. To calculate factorial of say hundred, we use BigInteger class of java.math package.

import java.util.Scanner;
import java.math.BigInteger;

class Factorial
{
public static void main(String args[])
{
int n, c;

BigInteger i = new BigInteger(“1”);
BigInteger f = new BigInteger(“1”);

Scanner input = new Scanner(System.in);

System.out.println(“Input an integer”);
n = input.nextInt();

for (c = 1; c <= n; c++) {
f = f.multiply(i);
i = i.add(BigInteger.ONE);
}

System.out.println(n + “! = “ + f);
}
}

 

We run the program to calculate 100 factorial.

Input an integer
100
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Leave a Reply

Your email address will not be published. Required fields are marked *