Hello guys, if you are looking for a Java program to calculate factorial with
and without recursion then you have come to the right place. Factorial is a
common programming exercise
that is great to learn to code and how to program. When I teach Java to new
people, I often start with coding problems like
prime numbers,
Fibonacci series, and
factorial because they help you to develop a coding sense and teach you how to write a
program initially. In order to calculate factorial, you just need to know the
factorial concepts from Mathematics, and rest I will explain this simple Java
programming tutorial.
If you come from a Maths background then you know that the factorial of a
number is number*(factorial of number -1),
once you know that, your next task is how to convert that formula into a
computer program and that's what you will learn in this article.
We will use Java programming constructs like variables, operators, methods,
and algorithms like
recursion
and loops to calculate the factorial of a number in Java, but before that
let's get the problem statement right.
Problem: Write a Java program to calculate the factorial of a given
number in Java, using both recursion and iteration.
Solution: We will use this formula to calculate factorial in this Java tutorial. Since factorial is a naturally recursive operation, it makes sense to first use recursion to solve this problem which is great and we'll also do the same but just remember that it's not always the best way to solve problems in the real world.
Solution: We will use this formula to calculate factorial in this Java tutorial. Since factorial is a naturally recursive operation, it makes sense to first use recursion to solve this problem which is great and we'll also do the same but just remember that it's not always the best way to solve problems in the real world.
Iteration provides a more robust way, but don't worry you will learn how to
calculate factorial with and without recursion in Java.
By the way, the factorial of numbers grows very quickly and even the largest
integral data type in Java long is not able to hold factorial of anything or
above 50. In such cases, you can use BigInteger or long or data type which has
theoretically no limit and can be used to represent very large integral
numbers.
How to Calculate Factorial in Java? Example Tutorial
Without wasting any more of your time, let's jump into the two solutions we
can use to calculate factorials in Java. In the first solution, we will use
recursion, where a method calls itself for repetition, and in the second
solution, we will use loops like for and while loop to achieve repetition.
This is also known as iteration because you iterate or perform the same task
again and again.
Solution 1: Factorial using recursion
In order to create a recursive solution, you would need a base case where the program terminates and repetition stops. In this problem, the base case is factorial of 1, which is 1 so when your function calls factorial(1) you can simply return 1 without doing any calculation.
And, if the given number is greater than 1, we keep applying the factorial
formula and recursive calling the same factorial with n - 1 as shown below
:
public static long factorial(int number){ //base case - factorial of 0 or 1 is 1 if(number <=1){ return 1; } return number*factorial(number - 1); }Once input becomes 1 the method stopped recursive call and return 1. From there onward method stack started to roll down and finally factorial of a number is calculated and returned.
Solution 2: Factorial without Recursion
As I said instead of using recursion and calling the factorial method again you can also use for loop to calculate factorial because !n = n*(n-1)*(n-2).....*1, which can easily be implemented using the loop as shown below :public static long factorial(long input){ long factorial = 1L; for(long i= input; i > 0; i--){ factorial = factorial * i; } return factorial; }You can see that we start with the number and multiply it with the factorial which is initialized with 1 then we reduce the number by 1 until the number becomes 1, which is nothing but n*(n-1)*(n-2).....*1.
Java Program to calculate Factorial with and without Recursion
Here is our complete solution to this problem. You can see that I have created two factorial() methods, one accepts an int and return long like long factorial(int number), while the other accepts a long and returns a long factorial i.e. long factorial(long number).
Since their parameter type is different they are two different methods also
known as
overloaded methods. The first method uses recursion to calculate factorial while the second
method uses iteration to calculate factorial.
That's all about how to calculate the factorial of a number in Java using both recursion and iteration. This problem is often used to teach programming, particularly recursion in schools and colleges, and it's a good one as well. Just remember that even though recursive solutions are small and clear they are prone to throw StackOverFlowException, hence not suitable for production code. Iteration or use of for loop results in a more robust solution.
import java.math.BigInteger; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Java Program to calculate factorial using iteration and recursion * * @author WINDOWS 8 * */ public class FactorialTest { public static void main(String args[]) { System.out.println("factorial of 1 using recursion : " + factorial(1)); System.out.println("factorial of 1 using iteration : " + factorial(1L)); System.out.println("factorial of 5 using recursion : " + factorial(5)); System.out.println("factorial of 5 using loop : " + factorial(5L)); System.out.println("factorial of 7 using recursive algorithm : " + factorial(7)); System.out.println("factorial of 7 using iterative algorithm : " + factorial(7L)); } /** * Java method to calculate factorial of given integer using recursion. * @param number * @return factorial of number */ public static long factorial(int number){ //base case - factorial of 0 or 1 is 1 if(number <=1){ return 1; } return number*factorial(number - 1); } /** * Java method to calculate factorial of given number using iteration * @param input * @return factorial of input */ public static long factorial(long input){ long factorial = 1L; for(long i= input; i > 0; i--){ factorial = factorial * i; } return factorial; } } Output : factorial of 1 using recursion : 1 factorial of 1 using iteration : 1 factorial of 5 using recursion : 120 factorial of 5 using loop : 120 factorial of 7 using recursive algorithm : 5040 factorial of 7 using iterative algorithm : 5040
That's all about how to calculate the factorial of a number in Java using both recursion and iteration. This problem is often used to teach programming, particularly recursion in schools and colleges, and it's a good one as well. Just remember that even though recursive solutions are small and clear they are prone to throw StackOverFlowException, hence not suitable for production code. Iteration or use of for loop results in a more robust solution.
Other Programming Articles you may like
If you are learning to program then you can also try the following problem
to improve your logic and coding skill :
- How to check if a given number is prime or not? (solution)
- How to find if the given String is a palindrome in Java? (solution)
- How to reverse an int variable in Java? (solution)
- How to find a missing number in a sorted array? (solution)
- 75 Programming Questions for Interviews (questions)
- 100+ Data Structure and Algorithms problems for interviews (questions)
- 10 Free Courses to learn Data Structure and Algorithms (free courses)
- 10 Free Courses to learn Java Programming (free courses)
- Write a program to check if a number is a power of two or not? (solution)
- How to reverse String in Java without using StringBuffer? (solution)
- How do you reverse the word of a sentence in Java? (solution)
- How do you swap two integers without using a temporary variable? (solution)
- 10 Dynamic Programming Problems for Interviews (DP questions)
Thanks, for reading this article so far, if you like this article then
please share it with your friends and colleagues. If you have any
questions or feedback then please drop a note.
P. S. - If you are new to the Java Programming world and looking
for a free online course to learn Java from scratch then I highly
recommend you to check out Java Tutorial for Complete Beginners(FREE) course
on Udemy. It's completely free and more than 1 million students have
already joined this course.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.