Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler 2 in Java

Tags:

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.

like image 947
Breon Thibodeaux Avatar asked Nov 26 '25 06:11

Breon Thibodeaux


1 Answers

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.

Solution = 4613732

like image 188
spydon Avatar answered Nov 28 '25 20:11

spydon