Breon Thibodeaux Breon Thibodeaux - 5 months ago 20
Java Question

Project Euler 2 in Eclipse using Java

public class Euler2 {

public static void main(String[] args) {

int Num1 = 0;
int Num2 = 1;
int sum = 0;

do
{
sum = Num1 + Num2;
Num1 = Num2;
Num2 = sum;

if (Num2 % 2 == 0)
sum = sum + Num2;
}
while (Num2 < 4000000);

System.out.println(sum);
}
}


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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

I don't feel like I coded it wrong but the answer I'm getting is 5702887 and I know it should be 4613732

Answer
public class Euler {
    public static void main(String[] args) {    
        int num1 = 0;
        int num2 = 1;
        int temp = 0;
        int sum = 0;

        do {
            if (num2 % 2 == 0) {
                sum = sum + num2;
            }
            temp = num1 + num2;
            Num1 = num2;
            Num2 = temp;
        } while (num2 < 4000000);

        System.out.println(sum);
    }
}

You messed up the sum by assigning it twice on each iteration where num2 is even. In this solution we use a temporary variable to store the next fibonacci number.

Comments