Recursive factorial in Java

problem

Calculate the factorial of a given number using a recursive approach. Recall the mathematical formula:

n! = n × (n – 1)!

SOLUTION

Let’s implement the formula above in a method as follows:

				
					public long factorial(int number) {
     if (number == 0) {
         return 1;
     } else {
         return number * factorial(number-1);
     }
}
				
			
running

Let’s put it in class with a Java main method so we can test it out:

Factorial.java
				
					public class Factorial {

    public long factorial(int number) {
        if (number == 0) {
            return 1;
        } else {
            return number * factorial(number-1);
        }
    }

    public static void main(String args[]){
        System.out.println(new Factorial().factorial(5));
    }
}
				
			

First, compile it e.g. in the terminal:

				
					javac Factorial.java
				
			

Execute it

				
					java Factorial
				
			
output

conclusion

In this post we saw how to write the recursive factorial implementation in Java. Then how to compile it in your terminal window and then execute it.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x