01. Example:
import java.util.Scanner; class findFactorial { public static void main(String args[]) { int N, counter, factorial = 1; System.out.print("Enter An Integer: "); Scanner in = new Scanner(System.in); N = in.nextInt(); if (N < 0){ System.out.println("nNumber must be Non-negative."); } else { for (counter = 1; counter <= N; counter++) factorial = factorial * counter; System.out.println("nFactorial of " + N + " is = " + factorial); } } }
Output:
Enter An Integer: 6 Factorial of 6 is = 720
To deal with larger integer values, we have to include the “BigInteger” class and process with the below program.
02. Example:
import java.util.Scanner; import java.math.BigInteger; class BigFactorial { public static void main(String args[]) { int N, counter; BigInteger increment = new BigInteger("1"); BigInteger fact = new BigInteger("1"); Scanner input = new Scanner(System.in); System.out.println("Input an integer: "); N = input.nextInt(); if (N > 0) { for (counter = 1; counter <= N; counter++) { fact = fact.multiply(increment); increment = increment.add(BigInteger.ONE); } System.out.println(N + "! = " + fact); } else{ System.out.println("nNumber must be Non-negative."); } } }
Output:
Enter An Integer: 6 Factorial of 6 is = 720