Friday, January 29, 2010

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.

No comments: