Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Mathematical Definition
3.
Implementation
3.1.
1.) Using Iteration
3.1.1.
Algorithm:
3.1.2.
Code:
3.1.3.
Output:
3.2.
Complexity Analysis
3.2.1.
Time Complexity:
3.2.2.
Space Complexity:
3.3.
2.) Using Recursion
3.3.1.
Algorithm:
3.3.2.
Code:
3.3.3.
Output:
3.4.
Complexity Analysis
3.4.1.
Time Complexity:
3.4.2.
Space Complexity:
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Factorial of a Number in Java

Author Aniket Majhi
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Welcome readers! I hope you are doing well.

In this blog, you will learn how to find out the factorial of a number in Java. We will show you the different algorithms to implement the factorial program. We will also show you the program flow of different algorithms.

This blog will enhance your knowledge of Java and will help you to improve your problem-solving skills.

So, Without any further ado, let’s start the topic.

Mathematical Definition

Factorial of a number(non-negative) is the multiplication of all smaller integers than the number, including the number itself.
We can write factorial of a number as,

Also see, Duck Number in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Implementation

There are mainly two ways to write the factorial program in Java:

1.) Using Iteration

The iteration method is discussed below:

Algorithm:

The steps for calculating factorial using iteration in java are as follows - 

  • Initialise the result to 1
long Result = 1;
  • Run a loop in the range [1, number]
for(int i = 1 ; i <= Number ; i++) {}
  • In each iteration update the result.
Result = Result * i;
  • Finally, print the result
System.out.printf("The Factorial of %d is: %d ",Number,Result);

Code:

public class Factorial {
    public static void main(String[] args) {
        int Number = 6; // Given Number
        long Result = 1;
        for(int i = 1 ; i <= Number ; i++) {
            Result = Result * i;
        }

        System.out.printf("The Factorial of %d is: %d ",Number,Result);
    }
}

Output:

From the above program, the factorial of 6 comes out to be 720.

Let’s see the steps for number 6 in iteration.

Complexity Analysis

The time and space complexity of the above code is shown below:

Time Complexity:

The time complexity of the above code is O(n), where n is the number.

Space Complexity:

The space complexity of the above code is O(1), as we are not allocating any extra spaces.

2.) Using Recursion

The Recursion method is discussed below:

Algorithm:

The steps for calculating factorial using recursion in java are as follows:

  • Create a recursive function by giving the Number as a parameter.
public static long fact(int Number) {}
  • If the number is 0, return 1 else call the function for  Number - 1
if(Number == 0) return 1;
else return Number * fact(Number - 1);
  • Store the result in a variable after the end of the recursion.
long Result = fact(Number);
  • Print the result.
System.out.printf("The factorial of Number %d is: %d",Number,Result);

Code:

public class Factorial {
    public static long fact(int Number) {
        if (Number == 0)
            return 1;
        else
            return Number * fact(Number - 1);
    }

    public static void main(String[] args) {
        int Number = 6;
        long Result = fact(Number);
        System.out.printf("The factorial of Number %d is: %d", Number, Result);
    }
}

Output:

Let's see the steps for number 6 in recursion.

Try it by yourself on Java Online Compiler.

Complexity Analysis

The time and space complexity of the above code is shown below:

Time Complexity:

The time complexity of the above code is O(n), where n is the number.

Space Complexity:

The space complexity of the above code is O(n) as a stack of size n will be allocated here to store the functions’ state.

Also check out Addition of Two Numbers in Java here.

Read More - Time Complexity of Sorting Algorithms

FAQs

  1. What is a factorial number?
    The factorial of a non-negative integer(N) is the product of integers from 1 to N.
     
  2. How do you solve the factorial of 4?
    4! = 4 * 3 * 2 * 1 = 24
     
  3. Can we find a factorial of a negative number?
    No factorial of a negative number is not possible.
    let’s  understand why
    We can write n! = (n + 1)! / (n + 1).
    Like , 5! = 6! / 6 , 4! = 5! / 5.
    But for negative numbers like -1.
    -1! = 0! / 0
    It is undefined. This applies to other negative numbers as well.
     
  4. What is the time complexity of the factorial program?
    For both the iteration and recursion solution,  the time complexity of the factorial program is O(n), where n = number.
     
  5. What is the space complexity of the factorial program?
    For the iteration solution, the space complexity is O(1), and for the recursion solution, the space complexity is O(n) due to the call stack.(n = Number). For factorial n, a stack of size n will be allocated to store the functions' state.

You can also read about - Strong number in c

Key Takeaways

In this article, we have extensively discussed the factorial program and its implementations in Java.

In this blog, we started with the basic definition of factorial. Then we discussed the two possible methods, i.e., iterative and recursive approaches regarding the factorial program their implementations with the proper program flow diagram.

We hope that this blog has helped you enhance your knowledge regarding the factorial program and if you would like to learn more, check out our articles on Reverse Array in Java Binary Search in Java. Do upvote our blog to help other ninjas grow.

Recommended Readings:

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Recommended Problems:

Happy Reading!

Previous article
Palindrome Program in Java
Next article
Java Program to Check Armstrong Number
Live masterclass