Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Java Program to Find the Factorial of a Number

Last Updated on May 17, 2023 by Prepbytes

The sum of all integers from 1 to the given number is known as the factorial of that number. Make sure you are comfortable with Java loops before continuing.

Example:

Enter the number: 5

Output:

A factorial of 5 is 120

Method 1: Find the Factorial of a Number in Java.

In this method, we will learn how to find the factorial of a number in java using a while loop.

Algorithm to Find the Factorial of a Given Number using a While Loop

  • Create an instance of a Scanner class.
  • Declare and initialize the new variable.
  • Declare a new variable for the loop and store the factorial of a number.
  • Initialize both variables with 1.
  • Traverse using a while loop.
  • Run the loop till the given number.
  • Update the factorial in each iteration of the number.
  • Increment the loop variable.
  • Print the factorial of a number.

Code Implementation of Java Program to Find Factorial of a Number using While Loop


import java.util.*;
public class Main
{
     public static void main(String []args)
     {
        
        Scanner sc=new Scanner(System.in);
       
        System.out.println("Enter the number: ");
        int num=sc.nextInt();
        int i=1,fact=1;
        while(i<=num)
        {
            fact=fact*i;
            i++;
        }
        System.out.println("Factorial of the number: "+fact);  
     }   
}

Output:

Enter the number: 5
Factorial of the number: 120

Method 2: Java Program to Find the Factorial of a Number

In this method, we will use a for loop to find the factorial number.

Algorithms to Find the Factorial of a Given Number using For Loop

  • Create an instance of a Scanner class.
  • Declare and initialize the new variable.
  • Declare a new variable for the loop and store the factorial of a number.
  • Initialize both variables with 1.
  • Use a for loop to calculate the factorial.
  • Update the factorial variable by multiplying it with the loop variable in each iteration.
  • Print the factorial of the given number.

Code Implementation Java Program to Find Factorial of a Number using For Loop

import java.util.*;
public class Main
{
     public static void main(String []args)
     {       
        Scanner sc=new Scanner(System.in);       
        System.out.println("Enter the number: ");
        int num=sc.nextInt();
        int fact=1;
        for(int i=1;i<=num;i++)
        {
            fact=fact*i;
        }
        System.out.println("Factorial of the number: "+fact); 
     }  
}

Method 3: Java Program to Find the Factorial of a Given Number Recursively

In this method, we will find the factorial of a given number recursively, In this program, we will take input from the user and we calculate the factorial of a number recursively.

Algorithm to Find the Factorial of a Given Number Recursively

  • Declare a variable to store a number.
  • Ask the user to enter the input number.
  • Check whether it is possible to calculate the factorial or not.
  • If the number is greater than and equal to 0, then call a recursive function to calculate the factorial of the entered number.
  • If the number is lesser than 0, print the message that it is not possible to calculate the factorial.
  • If the entered number is 0 or 1, then return 1.
  • If the entered number is other than 0 or 1, then calculate the factorial by recursively calling the same method.
  • Return the result and print the factorial of a given number

Code Implementation of Java Program to Find Factorial of a Number

import java.util.Scanner;
public class Main
{
  
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number :");
        int num = sc.nextInt();   
        if(num>=0) 
        {
          
           int factorial=findFactorial(num);
           System.out.println("The factorial of the entered number is :"+factorial);
        }        
        else
        {
            System.out.println("Factorial not possible.");
            System.out.println("Please enter valid input.");
        } 
    }
   
    public static int findFactorial(int num)
    {
        if(num==0)
        return 1;
        else if(num==1)
        return 1;
        else
        return num*findFactorial(num-1);        
    }
}

Output:

Enter the number: 6
The factorial of the entered number is:720

Conclusion
In conclusion, finding the factorial of a number involves multiplying the number by all positive integers less than it down to 1. It is represented by the symbol "!". The factorial of a number N is denoted as N! and is calculated as the product of N (N-1) (N-2) 2 * 1.

The factorial function is widely used in mathematics and combinatorics, especially for counting permutations and combinations. It grows very quickly, and for large numbers, it can become computationally expensive to calculate the factorial.

The factorial of a number N is the product of all positive integers less than or equal to N. It is commonly used in various mathematical and combinatorial calculations.

Frequently Asked Questions

Q1. What is the factorial of 0?
Ans. By convention, the factorial of 0 is defined as 1.

Q2. What is the largest number for which we can accurately calculate the factorial?
Ans. The largest number for which we can accurately calculate the factorial depends on the capabilities of the programming language or library being used. For most programming languages, the factorial can be accurately calculated up to a certain limit, typically the maximum value of the integer data type.

Q3. What happens if I try to calculate the factorial of a negative number?
Ans. The factorial is not defined for negative numbers. It is a concept applicable only to non-negative integers. If you attempt to calculate the factorial of a negative number, it would be considered mathematically invalid.

Q4. Is there a more efficient way to calculate the factorial of a number?
Ans. The factorial calculation involves multiplying a series of numbers together. While the basic approach is iterative or recursive, more efficient algorithms, such as the use of memoization or dynamic programming techniques, can be applied to optimize the calculation for large numbers.

Q5. Can the factorial of a non-integer or a decimal number be calculated?
Ans. The factorial is defined only for non-negative integers. It is not defined for non-integer or decimal numbers. If you need to calculate factorials for non-integer values, you may need to explore alternative mathematical functions or approximation techniques.

Other Java Programs
Java program to add two numbers
Java program to search an element in a linked list
Java program to convert arraylist to linkedlist
Java program to reverse a linked list

Leave a Reply

Your email address will not be published. Required fields are marked *