Friday, January 29, 2010

Problem 2

Whelp I just wiped out this entire post by accident. That is so awesome. I've learned an important lesson about Blogger.

Oh well, it was probably too long of a post for such an uninteresting problem.

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.

if __name__ == '__main__':
    sum = 0
    cur = 1
    prev = 0

    while cur + prev <= 4000000:
        newPrev = cur
        cur = cur + prev
        prev = newPrev
        if (cur % 2 == 0):
            sum = sum + cur
    print sum

Problem 1

First problem of the project and it is a pretty simple one.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

package euler1;

import java.util.Arrays;
import java.util.Collection;

/**
 * Project Euler Problem 1
 */
public class Main {

    public static void main(String[] args) {
        int sum = generateMultiples(1000, Arrays.asList(new Integer[]{3, 5}));
        System.out.println(sum);
    }

    private static int generateMultiples(int end, Collection multiples) {
        int sum = 0;
        
        for (int i = 0; i < end; i++) {
            for (Integer multiple : multiples) {
                if (i % multiple == 0) {
                    sum += i;
                    break;
                }
            }
        }
        return sum;
    }
}
Not much of interest here, aside from noting that writing this problem in Java felt like writing enterprise FizzBuzz. The use of Collections and Integers might be over engineering on my part, but what can I say, I like the way the For Each loop looks.