The Fibonacci Sequence is sometimes referred to as “God’s sequence” as it is a naturally occurring sequence. If you are curious about it check it out here. It is also heavily used in interview code exercises, with many variations available.
The sequence starts with numbers 1 and 2, and the next element is found by adding up the two previous numbers.
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Even Fibonacci Sum
Write a method that returns the sum of all even Fibonacci numbers. Consider all Fibonacci numbers that are less than or equal to n.
Each new element in the Fibonacci sequence is generated by adding the previous two elements.
Let’s start with the non-recursive version of this exercise. The recursive version will come later in the course. We simply keep calculating the next Fibonacci number and sum them up until your current Fibonacci reaches n.
int previousFibonacci = 1;
int currentFibonacci = 2;
int evenFibonacciSum = 0;
do {
if (currentFibonacci % 2 == 0) {
evenFibonacciSum += currentFibonacci;
}
int newFibonacci = currentFibonacci + previousFibonacci;
previousFibonacci = currentFibonacci;
currentFibonacci = newFibonacci;
} while (currentFibonacci < n);
return evenFibonacciSum;
You can play around with this code here. If you want to code a different exercise related with Fibonacci numbers you have one here.