简体   繁体   中英

Incorrect Output for Project Euler #2 - Java

The Word Problem I'm trying to solve:

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'm sure you've seen questions about this problem on Project Euler before, but I'm not sure why my solution doesn't work, so I'm hoping you can help!

public class Problem2Fibonacci {

public static void main(String[] args) {
    /* 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. */

    int sum = 0; // This is the running sum
    int num1 = 1; // This is the first number to add
    int num2 = 2; // This is the second number
    int even1 = 0;
    int even2 = 0;
    int evensum = 0;

    while (num2 <= 4000000){ // If i check num2 for the 4000000 cap, num will always be lower

        sum = num1 + num2;  // Add the first 2 numbers to get the 3rd

        if(num2 % 2 == 0){ // if num2 is even
            even1 = num2; // make even1 equal to num2
        }
        if(sum % 2 == 0){ // if sum is even
            even2 = sum; // make even2 equal to sum
        }
        if (even1 != 0  && even2 != 0){ // If even1 and even2 both have values 
        evensum = even1 + even2; // add them together to make the current evensum
        even2 = evensum;
        }
        num1 = num2;
        num2 = sum;
        System.out.println("The current sum is: " + sum);
        System.out.println("The current Even sum is: " + evensum);
    }
  }
}                    

So my 2 questions are, 1. Why doesn't my plan to get sum of even numbers work correctly? and 2. The last time my loop runs, it uses a num2 that is > 4000000. Why?

Thanks!

This should help you :

    int first = 0;
    int second = 1;
    int nextInSeq =first+second;
    int sum =0;

    while(nextInSeq < 4000000) {
        first = second;
        second = nextInSeq;
        nextInSeq = first + second;
        if(nextInSeq % 2 ==0)
            sum = sum + nextInSeq;
        System.out.println("Current Sum = " + sum);
    }
    System.out.println("Sum = " + sum);

For your piece of code : even1 and even2 are not required and they are carrying value they hold from previous iterations as you continue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM