Factorial Program in Java

What is Factorial of a Number?

When you multiply a positive integer by all the integers smaller than that positive integer, you get its factorial. This article will explain what is factorial and how to write a factorial program in Java with examples.

For example, factorial of 4 is 4! = 1*2*3*4 = 24 and factorial of 7 is 7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 which equals to 5040.

By default, the factorial of 0 is 1, and the Factorial of a negative number is not defined.

In mathematics, a factorial is denoted by “!“. Therefore, the factorial of n is given by the formula
n! = n x (n-1) x (n-2) x (n-3) … x1.

Factorial can also be calculated using Euler’s gamma function which is
n! = γ(n+1) = \(∫_0^∞\) xn e-x dx

Problem Description

Write a Java program to find the factorial of a positive number. If number is negative print the message otherwise find the factorial of the number.

Problem Solution

There are several ways to find factorial of a number in Java. Let’s look at all different approaches to program this function:

advertisement
advertisement

Method 1: Factorial in Java using For Loop (Without Recursion)

In this method, we run a loop for N times and multiply all the N positive numbers.

Program/Source Code

Here is the source code of the Java program to print the factorial of a given number using for loop. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/*
 * Java program to find the factorial of a given number using for loop.
 */
 
import java.util.Scanner;
public class Factorial 
{
    public static void main(String[] args) 
    {
        int n, fact = 1;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the Number: ");
        n = s.nextInt();
        for(int i = 1; i <= n; i++)
        {
            fact = fact * i;
        }
        System.out.println("Factorial of "+n+" is "+fact);
    }
}
Program Explanation

1. Take a number and store it in ‘n’.
2. Check whether it is a valid number or not.
3. If not a valid number, print the message.
4. Else, run a for loop from 1 to N.
5. Take a variable ‘fact’ and store all the multiplication of N numbers in it.
6. Print the factorial value.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Example:
Take N=8, check whether N is less than 0. If it is less than zero, print message. Now we run a for loop from N=1 to N=8 and multiply all the numbers. Store the multiplication of numbers in a variable and print the answer as 40320.

Time Complexity: O(N)
Since we are running for loop for N times, it’s time complexity is O(N).

Space Complexity: O(1)
Since we are not using constant space for computation, it’s space complexity is O(1).

Runtime Test Cases

Here is the runtime output of a Java program to find the factorial of a number when the number entered by the user is “8”.

advertisement
 
Enter the Number: 8
Factorial of 8 is 40320

Method 2: Factorial Program in Java using While Loop

In this method we run a while loop for N times and multiply all the N positive numbers.

Program/Source Code

Here is source code of the java program to print the factorial of a given number using while loop (iterative solution). The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

// Java program to calculate factorial of a number using while loop
 
import java.util.Scanner;
public class Factorial
{
    public static void main(String[] args)
    {
        int n;
        System.out.println("Enter the number: ");
        Scanner s = new Scanner(System.in);
        n = s.nextInt();
        long fact = 1;
        int i = 1;
        while(i<=n)
        {
            fact = fact * i;
            i++;
        }
        System.out.println("Factorial of "+n+" is: "+fact);
    }
}
Program Explanation

1. Take a number from the user and store it in variable ‘n’.
2. The program initializes a long variable ‘fact‘ to 1 and an integer variable ‘i‘ to 1.
3. The program enters a while loop that continues until ‘i‘ is less than or equal to ‘n‘.
4. Inside the loop, the program multiplies the ‘fact‘ variable by ‘i‘ and stores the result in ‘fact‘. Then it increments ‘i‘ by 1.
5. After the loop, the program prints the value of ‘fact‘ as the factorial of the input number ‘n‘, along with a message.

advertisement

Time Complexity: O(N)
Since we are running for loop for N times,it’s time complexity is O(N).

Space Complexity: O(1)
Since we are not using constant space for computation, it’s space complexity is O(1).

Runtime Test Cases

In this case, we enter the number “7” to determine the factorial.

Enter the number: 7
Factorial of 7 is: 5040

Method 3: Factorial Program in Java using Recursion

It is a recursive problem and the solution of factorial of N is given by expression
fact(n) = n*fact(n-1)
In above expression, we get solution of (n-1)! by recursive function and when we multiply it with n, we get result of n!.

Program/Source Code

Here is the source code of the Java Program to Find Factorial Value With Using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/*
 * Java program to find the factorial of a number using Recursion
 */
 
import java.util.Scanner;
public class Factorial
{
    public static void main(String[] args) 
    {
        int n, mul;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the number:");
        n = s.nextInt();
        Factorial obj = new Factorial();
        mul = obj.fact(n);
        System.out.println("Factorial of "+n+" :"+mul);
    }
    int fact(int x)
    {
        if(x > 1)
        {
            return(x * fact(x - 1));
        }
        return 1;
    }
}
Program Explanation

1. Take a number from the user and store it in variable ‘n’.
2. The program calls the ‘fact‘ method of the Factorial object and passes ‘n‘ as an argument. The return value of the method is stored in an integer variable ‘mul‘.
3. It prints the value of ‘mul‘ as the factorial of the input number ‘n‘, along with a message.
4. The ‘fact‘ method takes an integer ‘x‘ as an argument and returns the factorial of ‘x‘.
5. Inside the ‘fact‘ method, there is a recursive call to itself, which multiplies the current value of ‘x‘ with the return value of the ‘fact‘ method called with ‘x-1‘ as an argument until ‘x‘ becomes 1, and then returns 1.

Time Complexity: O(N)
Since we are calling function for N times(N,N-1,N-2….3,2,1), time complexity is O(N).

Space Complexity: O(N)
In the context of recursion, a memory tree is created during execution, taking into account that
the space complexity of the tree is O(N).

Runtime Test Cases

Here is the runtime output of a Java program to find the factorial of a number when the number entered by the user is “9”.

 
Enter the number: 9
The Factorial of 9 is 362880

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.