Sitemap

Fibonacci in Java

2 min readMar 1, 2018

--

The Fibonacci number sequence starts with 0 and 1 then every subsequent number is the sum of the previous two. Thus, the first 10 numbers in the sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

I wrote about the Fibonacci sequence early in my apprenticeship and at the time I was not a fan of how it was realised in code. This was probably because I overcomplicated the process of how to get the Fibonacci sequence.

Having recently finished doing the factorial sequence in Java, I felt a lot more comfortable when doing the Fibonacci sequence in Java.

Get Katerina’s stories in your inbox

Join Medium for free to get updates from this writer.

The formula for the sequence is:

Fn = Fn-1 + Fn-2

I started with zero again for this:

@Test
public void zero() {
assertEquals(0, fibonacci(0));
}

The code for Fibonacci zero and one was the same:

private int fibonacci(int i) {
return i;
}

When it gets to to Fibonacci three which is the sum of Fibonacci 2 (number 1) and Fibonacci 1 (number 1) then I was forced to write the recursive formula.

until the current number is less than 1
current number = current number - 1 + current number - 2

The code for this would be as follows:

private int fibonacci(int i) {
return i <= 1 ? i : fibonacci(i - 1) + fibonacci(i - 2);
}

In the original code I wrote to solve this problem, I used an if statement. I then changed then replaced the if statement with a turnery operator. This seemed to be a more concise way to achieve the same thing and in this case it made the code quicker to read and digest.

--

--

Katerina
Katerina

Written by Katerina

My journey of career changing into programming!