Java noobness

Soldato
Joined
7 Mar 2011
Posts
6,859
Location
Oldham, Lancashire
I am running through the problems on Project Euler and, rather stupidly, got stuck on problem 2!

The way I am reading it is basically the sum of all the even numbers in the fibbonaci sequence under 4000000. My program runs fine, but the answer is wrong. Any pointers? Not answers please, just an idea where I went wrong :D

Code:
package euler_2;

/**
 * By considering the terms in the Fibonacci sequence whose values do not 
 * exceed four million, find the sum of the even-valued terms.
 * 
 * @author Woden
 */
public class Euler_2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int max = 4000000; // Upper limit of the exercise
        int prev = 1; // Previous number int he sequence
        int cur = 2; // Current number in the sequence
        int next = 3; // next number in the sequence
        int sum = 0; // Sum of even terms
        
        while(prev + cur <= max) {
            if(cur % 2 == 0) {
                sum = sum + cur;
            }
            prev = cur;
            cur = next;
            next = prev + cur;
        }
        System.out.println(sum);
    }
}
 
I'd take a look at your while condition again as I believe that is at fault.

I think you could be right as well.

If you're still stuck OP, this got the right answer for me. :)

Code:
package co.ootf.euler;

/**
 * Created by IntelliJ IDEA.
 * User: Ben
 * Date: 18/07/12
 * Time: 19:47
 * To change this template use File | Settings | File Templates.
 */
public class Euler2 {
    
    private static final int MAX = 4000000;
    
    public static void main(String[] args) {
        int current = 1;
        int next = 2;
        int runningTotal = 0;

        while (current <= MAX ) {
            if (current % 2 == 0) {
                System.out.println("*" + current);
                runningTotal += current;
            } else {
                System.out.println(current);
            }
            int tempNext = current + next;
            current = next;
            next = tempNext;
        }

        System.out.println("total = " + runningTotal);

        
    }

}
 
Woop just checked my Java dropbox and still have my Project Euler folder, completely forgot about this. Only got to the 4th Proj with Java. Got a bit further with PHP but don't seem to have any backups :(

Will definitely pick it back up again w/ Java thanks for the reminder :)
 
Back
Top Bottom