Algorithm


  1. Input: Accept the number for which the factorial needs to be calculated.
  2. Initialize: Set a variable factorial to 1.
  3. Loop: Start a loop from 1 to the given number.
    • Within the loop, multiply the current value of factorial by the loop variable.
  4. Output: The final value of factorial is the result.

 

Code Examples

#1 Code Example- Find Factorial of a number using for loop

Code - Java Programming

public class Factorial {

    public static void main(String[] args) {

        int num = 10;
        long factorial = 1;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial *= i;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Factorial of 10 = 3628800

#2 Code Example- Find Factorial of a number using BigInteger

Code - Java Programming

import java.math.BigInteger;

public class Factorial {

    public static void main(String[] args) {

        int num = 30;
        BigInteger factorial = BigInteger.ONE;
        for(int i = 1; i  < = num; ++i)
        {
            // factorial = factorial * i;
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Factorial of 30 = 265252859812191058636308480000000

#3 Code Example- Find Factorial of a number using while loop

Code - Java Programming

public class Factorial {

    public static void main(String[] args) {

        int num = 5, i = 1;
        long factorial = 1;
        while(i  < = num)
        {
            factorial *= i;
            i++;
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Factorial of 5 = 120
Advertisements

Demonstration


Java Programing Example to Find Factorial of a Number-DevsEnv