Recursion strikes back —
Factorial sequence in Java
Two of my stories this week were to experiment with recursion in Java. I got introduced to recursion when I was programming in Ruby and wrote this blog post with a basic example of how recursion works.
My first story was to write a program to work out the factorial of a given number. Wikipedia defines a factorial as follows:
the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.5! = 5 X 4 X 3 X 2 X 1 = 120.
I test drove the code which gave me a basis to start from and I started with zero. The factorial of zero equals one which to be honest is quite confusing. When looking up why this is the case, most of the internet seems to say “because it is”. I believe the actual reason for this is so that when doing 1! the factorial can be one and not zero.
public class FactorialTest {
@Test
public void zero() {
assertEquals(1, factorial(0));
}
}For the factorial of zero and one the code was very simple, I needed to return that number.
private int factorial(int i) {
return 1;
} I then did a basic if statement to handle two:
private int factorial(int i) {
if (i < 2) {
return 1;
} else {
return 2
}
}When it came to doing the factorial of three I was forced to write the actual formula is:
until current number is equal to 1
current number * (current number - one) My task was to use recursion to get the factorial. This meant I needed to call the same method from within my method whilst reducing the current number. To stop my method from recursing I needed a base case which was:
Get Katerina’s stories in your inbox
Join Medium for free to get updates from this writer.
i <= 1
My code for this formula looked like this:
private int factorial(int i) {
return i <= 1? 1 : i * (factorial(i - 1));
}I enjoyed doing this factorial program as it made recursion seem a little less scary. I then went on to do a Fibonacci program using recursion. This program is a little bit more complicated still relatively easy to break down.
You can read about my Fibonacci program here.






