The Wayback Machine - https://web.archive.org/web/20240914171329/https://www.geeksforgeeks.org/java-program-for-factorial-of-a-number/
Open In App

Java Program for factorial of a number

Last Updated : 30 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. In this article, we will learn how to write a program for the factorial of a number in Java.

Formulae for Factorial

n! = n * (n-1) * (n-2) * (n-3) * ........ * 1
Factorial of a Number in Java

Example of Factorial in Java

6! == 6*5*4*3*2*1 = 720. 
5! == 5*4*3*2*1 = 120
4! == 4*3*2*1 = 24

Methods to Find Factorial of a Number

1. Iterative Solution for Factorial in Java

Below is the implementation of the above method:

Java




// Java program to find factorial
// of given number
  
// Driver Class
class Test {
    // Method to find factorial
    // of given number
    static int factorial(int n)
    {
        int res = 1, i;
        for (i = 2; i <= n; i++)
            res *= i;
        return res;
    }
  
    // main method
    public static void main(String[] args)
    {
        int num = 5;
        System.out.println("Factorial of " + num + " is "
                           + factorial(5));
    }
}


Output

Factorial of 5 is 120

The complexity of the above method:

Time Complexity: O(n)
Auxiliary Space: O(1)

2. Factorial in Java Using Recursive Method

Below is the implementation of the above method:

Java




// Java program to find factorial
// of given number
  
// Driver Class
class Test {
    // method to find factorial
    // of given number
    static int factorial(int n)
    {
        if (n == 0)
            return 1;
  
        return n * factorial(n - 1);
    }
  
    // main method
    public static void main(String[] args)
    {
        int num = 5;
        System.out.println("Factorial of " + num + " is "
                           + factorial(5));
    }
}


Output

Factorial of 5 is 120

The complexity of the above method:

Time Complexity: O(n)
Auxiliary Space: O(n)

3. One-line Solution (Using the Ternary operator)

Below is the implementation of the above method:

Java




// Java program to find factorial
// of given number
  
// Driver Class
class Factorial {
    // function to find factorial
    int factorial(int n)
    {
  
        // single line to find factorial
        return (n == 1 || n == 0) ? 1
                                  : n * factorial(n - 1);
    }
  
    // main function
    public static void main(String args[])
    {
        Factorial obj = new Factorial();
        int num = 5;
        System.out.println("Factorial of " + num + " is "
                           + obj.factorial(num));
    }
}


Output

Factorial of 5 is 120

The complexity of the above method:

Time Complexity: O(n)
Auxiliary Space: O(n)

The above solutions cause overflow for small numbers. Please refer factorial of large numbers for a solution that works for large numbers. Please refer complete article on the Program for factorial of a number for more details!



Previous Article
Next Article

Similar Reads

Find the last digit when factorial of A divides factorial of B
We are given two numbers A and B such that B &gt;= A. We need to compute the last digit of this resulting F such that F = B!/A! where 1 = A, B &lt;= 10^18 (A and B are very large).Examples: Input : A = 2, B = 4Output : 2Explanation : A! = 2 and B! = 24. F = 24/2 = 12 --&gt; last digit = 2Input : 107 109Output : 2As we know, factorial function grows
10 min read
Java Program to Count trailing zeroes in factorial of a number
Given an integer n, write a function that returns count of trailing zeroes in n!. Examples : Input: n = 5 Output: 1 Factorial of 5 is 120 which has one trailing 0. Input: n = 20 Output: 4 Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100 Output: 24Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5) +
2 min read
Java Program to Find Factorial of a Number Recursively
Factorial of a number n is defined as a product of all positive descending integers, Factorial of n is denoted by n!. Factorial can be calculated using the following recursive formula where the recursive call is made to a multiplicity of all the numbers lesser than the number for which the factorial is computed as the formula to calculate factorial
4 min read
Golang Program to Count Trailing Zeros in Factorial of a Number
Given an integer n, write a Go program to count the number of trailing zeros in the factorial of n. Examples: Input : 7 Output : 1 Explanation: 7! = 5040, which has 1 trailing zero Input : 10 Output : 2 Explanation: 10! = 3628800, which has 2 trailing zeros Naive approach: To count the trailing zeros in n!, one approach is to find the factorial of
3 min read
Recursive Program to find Factorial of a large number
Given a large number N, the task is to find the factorial of N using recursion. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Examples: Input : N = 100Output : 933262154439441526816992388562667004-907159682643816214685929638952175999-9322
6 min read
Program for factorial of a number
Given the number N (N &gt;=0), print its factorial. Factorial of a non-negative integer is the multiplication of all positive integers smaller than or equal to N. It is represented by a number and a ”!” mark at the end and is widely used in permutations and combinations to calculate the total possible outcomes. Examples: Input: 5Output: 120Explanat
7 min read
Check if a given number is factorial of any number
Given a number n, the task is to determine whether n can be a factorial of some number x.Examples: Input: N = 24Output: YesExplanation: 4! = 24 Input: N = 25Output: No Approach: For a number to be a factorial of any number it must be divisible by all the numbers from 1 to that number. So in this approach We keep on dividing the number if it is comp
4 min read
One line function for factorial of a number
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. Example : Factorial of 6 is 6 * 5 * 4 * 3 * 2 * 1 which is 720. We can find the factorial of a number in one line with the help of Ternary operator or commonly known as Conditional operator in recursion. C/C++ Code // C++ program to find factorial of
3 min read
First digit in factorial of a number
Given a positive integer n, find the first digit in its factorial. Examples : Input : n = 5 Output : 1 Factorial of 5 is 120 and first digit is 1. Input : 1000 Output : 4 A simple solution is to compute factorial of number, then find first digit in it. The above solution causes overflow soon. A better solution is to use the fact that factorial cont
5 min read
Number of digits in N factorial to the power N
Given a positive integer N, we have to find the total number of digits in the factorial of N raised to the power N, i.e, [Tex](N!)^N [/Tex]Examples: Input: 4 Output: 6 Explanations: [Tex](4!)^4[/Tex] = [Tex](24)^4[/Tex] = 331776. Total number of digits in 331776 is 6.Input: 5Output: 11Explanations: [Tex](5!)^5[/Tex] = [Tex](120)^5[/Tex] = 248832000
4 min read
Last digit of a number raised to last digit of N factorial
Given two number X and N, the task is to find the last digit of X raised to last digit of N factorial, i.e. [Tex]X^{\left ( N! \right )mod 10} [/Tex].Examples: Input: X = 5, N = 2 Output: 5 Explanation: Since, 2! mod 10 = 2 therefore 52 = 25 and the last digit of 25 is 5.Input: X = 10, N = 4 Output: 0 Explanation: Since, 4! mod 10 = 24 mod 10 = 4 t
15 min read
Factorial of a number without using multiplication
Given a positive number N, the task is to calculate the factorial of N without using the multiplication operator. Examples: Input: N = 5Output:120Explanation:5*4*3*2*1=120 Input: N = 7Output:5040 Observation: A*B=A+A+A+A...B times. This observation can be used as follows: 5!=5*4*3*2*1 =(5+5+5+5)*3*2*1 =(20+20+20)*2*1 =60+60 =120 Approach 1: The pro
7 min read
Find remainder when a number A raised to N factorial is divided by P
Given three integers A, N and P, the task is to find (A^(N!)) % P. Examples: Input: A = 2, N = 1, P = 2Output: 0Explanation: As (2^(1!)) = 2 Therefore 2 % 2 will be 0. Input: A = 3, N = 3, P = 2Output: 1 Naive Approach: The simplest solution of this problem can be find out factorial of N say f, and now calculate A to power f say pow and find its re
10 min read
Calculate MDAS Factorial of given number
Given an integer N, the task is to find the MDAS factorial.The general factorial of a no. N is given by: Factorial(N) = (N)*(N-1)*(N-2)*(N-3)*(N-4)*(N-5)*(N-6)*(N-7)- - - - - -(3)*(2)*(1). In MDAS factorial, instead of simply multiplying the numbers from N to 1, we perform four operations, Multiplication(*), Divide(/), Addition(+) and Subtraction(-
5 min read
Find sum of digits in factorial of a number
Given a number n, write code to find the sum of digits in the factorial of the number. Given n â‰Ī 5000 Examples: Input : 10 Output : 27 Input : 100 Output : 648 Recommended PracticeSum of digits in factorial of a numberTry It!It is not possible to store a number as large as 100! under some data types so, idea is to store an extremely large number in
11 min read
Find the first natural number whose factorial is divisible by x
Given a number x, the task is to find first natural number i whose factorial is divisible by x.Examples : Input : x = 10 Output : 5 5 is the smallest number such that (5!) % 10 = 0 Input : x = 16 Output : 6 6 is the smallest number such that (6!) % 16 = 0 A simple solution is to iterate from 1 to x-1 and for every number i check if i! is divisible
14 min read
Smallest number with at least n trailing zeroes in factorial
Given a number n. The task is to find the smallest number whose factorial contains at least n trailing zeroes.Examples : Input : n = 1Output : 5 1!, 2!, 3!, 4! does not contain trailing zero.5! = 120, which contains one trailing zero.Input : n = 6Output : 25Recommended PracticeSmallest factorial numberTry It!Approach:In this approach, we use a whil
9 min read
Smallest number with at least n digits in factorial
Given a number n. The task is to find the smallest number whose factorial contains at least n digits.Examples: Input : n = 1 Output : 0 0! = 1, hence it has 1 digit. Input : n = 2 Output : 4 4! = 24 and 3! = 6, hence 4 is the smallest number having 2 digits in its factorial Input : n = 5 Output : 8 In the article for Count digits in a factorial of
10 min read
Sum of divisors of factorial of a number
Given a number n, we need to calculate the sum of divisors of factorial of the number. Examples: Input : 4 Output : 60 Factorial of 4 is 24. Divisors of 24 are 1 2 3 4 6 8 12 24, sum of these is 60. Input : 6 Output : 2418 A Simple Solution is to first compute the factorial of the given number, then count the number divisors of the factorial. This
14 min read
Smallest number S such that N is a factor of S factorial or S!
Given a number N. You are tasked with finding the smallest number S, such that N is a factor of S! (S factorial). N can be very large.Examples: Input : 6 Output : 3 The value of 3! is 6 This is the smallest number which can have 6 as a factor. Input : 997587429953 Output : 998957 If we calculate out 998957!, we shall find that it is divisible by 99
9 min read
Find the last two digits of Factorial of a given Number
Given an integer N, the task is to find the last two digits of factorial of a number. Examples: Input: N = 7 Output: 40 Explanation: 7! = 5040Input: N = 11 Output: 00 Approach#1We can observe that for N &gt;= 10, the last two places of its factorial will contain 0's only. Hence N! % 100 for any N &gt;= 10 will always be 0. So we just calculate the
15 min read
Find maximum power of a number that divides a factorial
Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact). Examples: Input : fact = 5, n = 2 Output : 3 Explanation: Value of 5! is 120. The largest power of 2 that divides 120 is 8 (or 23 Input : fact = 146, n = 15 Output : 35 The idea is based on Legendre’s formula which finds largest power of a prime numbe
12 min read
Count trailing zeroes in factorial of a number
Given an integer n, write a function that returns count of trailing zeroes in n!. Examples : Input: n = 5Output: 1 Explanation: Factorial of 5 is 120 which has one trailing 0. Input: n = 20Output: 4Explanation: Factorial of 20 is 2432902008176640000 which has 4 trailing zeroes. Input: n = 100Output: 24 Table of Content [Naive Approach] By calculati
6 min read
Find the Factorial of a large number
Find the factorial of a large number.  What is Factorial of a number?Factorial of a non-negative integer, is the multiplication of all integers smaller than or equal to n.  Examples:  Input: 100Output: 933262154439441526816992388562667004-         907159682643816214685929638952175999-         932299156089414639761565182862536979-         2082722375
15+ min read
Find the length of factorial of a number in any given base
Given an integer n and base B, the task is to find the length of n! in base B.Examples: Input: n = 4, b = 10 Output: 2 Explanation: 4! = 24, hence number of digits is 2 Input: n = 4, b = 16 Output: 2 Explanation: 4! = 18 in base 16, hence number of digits is 2 Brute Force Approach: The brute force approach to solve this problem would involve findin
9 min read
Factorial of each element in Fibonacci series
Given the upper limit, print factorials of all Fibonacci Numbers smaller than the limit.Examples : Input : limit = 20 Output : 1 1 1 2 6 120 40320 6227020800 Explanation : Fibonacci series in this range is 0, 1, 1, 2, 3, 5, 8, 13. Factorials of these numbers are output. Input : 50 Output : 1 1 1 2 6 120 40320 6227020800 51090942171709440000 2952327
11 min read
Expressing factorial n as sum of consecutive numbers
Given two numbers N and M. Find the number of ways in which factorial N can be expressed as a sum of two or more consecutive numbers. Print the result modulo M.Examples: Input : N = 3, M = 7 Output : 1 Explanation: 3! can be expressed in one way, i.e. 1 + 2 + 3 = 6. Hence 1 % 7 = 1 Input : N = 4, M = 7 Output : 1 Explanation: 4! can be expressed in
13 min read
Range and Update Sum Queries with Factorial
Given an array arr[] of N integers and number of queries Q. The task is to answer three types of queries. Update [l, r] – for every i in range [l, r] increment arr[i] by 1.Update [l, val] – change the value of arr[l] to val.Query [l, r] – calculate the sum of arr[i]! % 109 for all i in range [l, r] where arr[i]! is the factorial of arr[i]. Prerequi
15+ min read
Check if N is a Factorial Prime
Given a positive integer N, the task is to check if N is a Factorial prime or not. If it is a factorial prime then print YES else print NO.Note: In mathematics, a factorial prime number is a prime number that is one less than or one more than a factorial of any number. First few factorial primes are 2, 3, 5, 7, 23, 719, 5039, ....Examples: Input: N
9 min read
Find GCD of factorial of elements of given array
Given an array with N positive integers. Find the GCD of factorials of all elements of array.Examples: Input : arr[] = {3, 4, 8, 6} Output : 6 Input : arr[] = {13, 24, 8, 5} Output : 120 Approach: To find the GCD of factorial of all elements, first of all, calculate the factorial of all elements and then find out their GCD. But this seems to be a v
5 min read
Practice Tags :