Q:

Write a method that returns the sum of all even Fibonacci numbers. Consider all Fibonacci numbers that are less than or equal to n

0

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.
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

public Integer evenFibonacciSum(Integer 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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now