In this tutorial, we will learn how to write a Java program to find the factorial of a number.
Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.
For example:
4! = 4*3*2*1 = 24 5! = 5*4*3*2*1 = 120
Java Program to Find Factorial of a Number
In the below program, we are using a Scanner to get input from the console.
import java.math.BigInteger; import java.util.Scanner; public class FactorialExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); BigInteger fact = factorial(n); System.out.printf("%d! is %d", n, fact); scanner.close(); } private static BigInteger factorial(int value) { BigInteger result = BigInteger.ONE; if (value != 0 && value != 1) { for (int i = 2; i <= value; i++) { result = result.multiply(BigInteger.valueOf(i)); } } return result; } }
Output:
Enter a number: 5 5! is 120
Related Java Programs
- Java program to calculate the area of Triangle
- Java Program to Calculate Area of Square
- Java Program to Calculate Area of Rectangle
- Java Program to find the Smallest of three numbers using Ternary Operator
- Java Program to Find Largest of Three Numbers
- Java Program to Find GCD of Two Numbers
- Java Program to Check Armstrong Number
- Java Program to Generate Random Number
- Java Program to Check if Number is Positive or Negative
- Java program to check prime number
- Java Program to Calculate Simple Interest
- Java Program to Swap Two Numbers Without using a Temporary Variable
- Java Program to Swap Two Numbers
- Java Program to Find ASCII Value of a Character
- Java Program to Check Whether an Alphabet is Vowel or Consonant
- Java Program to Check Leap Year
- Java Program to Multiply Two Numbers
- Java Program to Check Even or Odd Number
- Java Program to Add Two Numbers
- Java Program to Swap Two Strings Without Using Third Variable
- Java Program to Swap Two Strings with Third Variable
- How to Get All Digits from String in Java
- Find Duplicate Number in Array in Java
- How to Get Current Working Directory in Java?
- Check Palindrome String in Java
- Java Program to Create Pyramid Of Numbers
Comments
Post a Comment