In this Java program, you’ll learn how to find the factorial of a number in java. We are using a for
loop and a while
loop for finding the factorial of a number in Java.
In mathematics, the factorial of a positive integer n, denoted by n! is the product of all positive integers less than or equal to n:
n!=(n-1)x(n-2)x(n-3)x….3x2x1
The factorial, symbolized by an exclamation mark (!), is a quantity defined for all integers greater than or equal to 0.
For example,
5!=5x4x3x2x1=120
6!=6x5x4x3x2x1=720
The value of 0! is 1.
// Java Program to Find Factorial of a Number using For Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int n;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
n = scanner.nextInt();
scanner.close();
long factorial = 1;
for(int i = 1; i <= n; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", n, factorial);
}
}
Enter a Number: 5
Factorial of 5 = 120
// Java Program to Find Factorial of a Number using While Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int n, i = 1;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
n = scanner.nextInt();
scanner.close();
long factorial = 1;
while (i <= n) {
factorial *= i;
i++;
}
System.out.printf("Factorial of %d = %d", n, factorial);
}
}
Enter a Number: 10
Factorial of 10 = 3628800
In this java program, instead of long
, we use BigInteger
variable factorial. Since * cannot be used with BigIntege
r, so, we instead use the multiply()
method for the product. Also, n should be cast to BigInteger
for multiplication.
// Java Program to Find Factorial of a Number using BigInteger
import java.util.Scanner;
import java.math.BigInteger;
public class JavaPrograms {
public static void main(String[] args) {
int n;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
n = scanner.nextInt();
scanner.close();
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i <= n; ++i) {
// factorial = factorial * i;
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.printf("Factorial of %d = %d", n, factorial);
}
}
Enter a Number: 30
Factorial of 30 = 265252859812191058636308480000000
Comments