Saturday, August 22, 2009

Project Euler Problem 1

A colleague of mine (Steve) let me know about a web site known as Project Euler. I signed up today and took a quick crack at problem 1. I knew I could optimize this to iterate through multiples of 3 and 5 instead of iterating through all numbers and checking if each was a multiple of 3 or 5, but I wanted to quickly get an answer so I took the brute-force route, which I won't do in the future.

My solution, which was correct on the first try, is listed below:


/*
* Problem 1
* 05 October 2001
*
* 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.
*
*/

public class PE0001
{
public static void main(String[] args)
{
long sum = 0;
for (int i = 0; i < 1000; i++)
if (isMultipleOf3Or5(i))
sum += i;

System.out.println(sum);
}

private static boolean isMultipleOf3Or5(int i)
{
if (i % 3 == 0 || i % 5 == 0)
return true;
return false;
}
}

1 comment: