Find the sum of all even members in a Fibonacci sequence

I find it difficult to understand why the following code does not produce the expected result. Instead, the result = 272, which does not seem to be correct.

/*
 *Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
 *Find the sum of all the even-valued terms in the sequence which do not exceed four million.
 */

public class Fibonacci 
{
    public static void main (String[] args)
    {
        int result = 0;
        for(int i=2;i<=33;i++)
        {
            System.out.println("i:" + fib(i)); 
            if(i % 2 == 0) //if i is even 
            {
                result += i;
                System.out.println("result:" + result); 
            }
        }
    }   
    public static long fib(int n)
    {
        if (n <= 1)
            return n;
        else
            return fib(n-1) + fib(n-2);
    }
}    
+3
source share
3 answers

The line result += i;does not add the Fibonacci number to result.

You should be able to figure out how to add a Fibonacci number to result.

Hint: Consider creating a variable that stores the number you are trying to work with.

+5
source

First of all, you have something wrong for Fib. The definition of Fib can be found here: http://en.wikipedia.org/wiki/Fibonacci_number .

-, (i% 2) (2, 4, 6 ), , fib (2), fib (4) ..

, + = . , , fib (i). fib (i), , THAT , , .

[]
: , , . , StackOverflowException, , . , , fib (0), fib (1) .., , , , .

+1

, , C, Java. , :

0

Source: https://habr.com/ru/post/1774840/


All Articles