×

Factorial Program in Java using Recursion

Factorial Program in Java

Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to be calculated is represented by p!.It is pronounced as p factorial. In this section, we will create a Java program to calculate the factorial of a number using iterative and recursive approach.   

Factorial of any number is the multiplication of numbers from that particular number to 1 either in increasing or in decreasing order. In general terms, we can represent the factorial of a number as follows:

p! = p × (p-1) × (p-2) × … × 1 or 1 × … × (p-2) × (p-1) × p

For example:

3! = 3 × 2 × 1 or 1 × 2 × 3 = 6

4! = 4 × 3 × 2 × 1 or 1 × 2 × 3 × 4 = 24

Note: As per standard mathematical definition, the factorial of any negative number cannot be found. Also, 0! is always 1.

Let’s write a Java program that calculates the factorial of a number using Java for loop.

Iterative Approach

Filename: FactorialProgramExample.java

public class FactorialProgramExample
{
public static void main(String[] args)
{
int j, factorial = 1; 
int no = 6; //we are calculating factorial of the number assigned to the variable   
for(j=1; j <= no; j++)
{   
factorial = factorial * j;   
}   
System.out.println("Factorial of the number "+ no +" is: " + factorial);
}
}

Output:

Factorial of the number 6 is: 720

In the above example, the variable factorial initialized to 1. We have used the Java for loop to find the factorial of a number. The loop executes until the condition j <= no becomes false. After each iteration, the variable j increments by 1. The for loop executes in the following order:

First iteration: The variables factorial = 1, and j = 1.

factorial = factorial * j => factorial = 1×1 = 1

Second iteration: After the first iteration, the value of factorial become 1 and the value of j incremented by 1 i.e. 2.  Hence, factorial = 1, and j = 2.

factorial = factorial * j => factorial = 1×2 = 2

Third iteration: After the second iteration, the value of factorial become 2 and the value of j incremented by 1 i.e. 3. Hence, factorial = 2, and j = 3.

factorial = factorial * j => factorial = 2×3 = 6

Fourth iteration: After the third iteration, the value of factorial become 6 and the value of j incremented by 1 i.e. 4. Hence, factorial = 6, and j = 4.

factorial = factorial * j => factorial = 6×4 = 24

Fifth iteration: After the fourth iteration, the value of factorial become 24 and the value of j incremented by 1 i.e. 5. Hence, factorial = 24, and j = 5.

factorial = factorial * j => factorial = 24×5 = 120

Sixth iteration: After the fifth iteration, the value of factorial become 120 and the value of j incremented by 1 i.e. 6. Hence, factorial = 120, and j = 6.

factorial = factorial * j => factorial = 120×6 = 720

After the sixth iteration, the value of factorial become 720 and the value of j incremented by 1 i.e. 7. Now the condition j <= no becomes false. The loop will terminate and thus, we get 6! = 720.

Recursive Approach

We can also use the recursive approach to find the factorial. The demonstration is given below.

Filename: FactorialProgramExample1.java

public class FactorialProgramExample1
{
static int findFactorial(int n)
{
if (n == 0 || n == 1)
return 1;
if(n < 0)
return -1;
return n * findFactorial(n-1);  //recursively called function
}
public static void main(String[] args)
{
int j, factorial = 1; 
int num = 6; //a number whose factorial is to be calculated   
factorial = findFactorial(num);  
if(num >= 0)
System.out.println("Factorial of the number "+ num +" is: " + factorial);
else
System.out.println("The given number is negative. Hence, the factorial cannot be found.");
}
}

Output:

Factorial of the number 6 is: 720

Explanation: Here, the recursive approach worked because we can also write 6! as 6 × 5! and 5! as 5 × 4! and so on. The findFactorial() method finds the factorial of the number passed to its argument. So, if we pass 6 in the method argument, then the method will find the factorial of 6, and if 5 is passed, the method will find the factorial of 5. Therefore, we can say

findFactorial(6) = 6 × findFactorial(5)

findFactorial(5) = 5 × findFactorial(4)

findFactorial(4) = 4 × findFactorial(3)

findFactorial(3) = 3 × findFactorial(2)

findFactorial(2) = 2 × findFactorial(1)

findFactorial(1) = 1

Combining all the above, we get:

findFactorial(6) = 6 × 5 × 4 × 3 × 2 × 1 = 720.


Related Topics

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.