Monday, May 11, 2009

Project Euler Problem 1

Recently I came across Project Euler web site. This is what the site has to say

"Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems. The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context."

I quickly registered to check what kind of mathematical problems are asked. I couldn't resist myself to start solving the problems. I chose Java to solve the problems as this is the only language I know ;)

Problem 1

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.

The solution is very simple and the code is self explanatory.

public class ProblemOne {
public static void main(String[] args) {
int result = 0;

for (int i = 1; i < 1000; ++i) {
if ((0 == (i % 3)) || (0 == (i % 5))) {
result += i;
}
}

System.out.println(result);
}
}