Thursday, January 20, 2011

Project Euler - Problem 1

So I discovered I still have Eclipse (the Java IDE) set up on my laptop. Lets see if I can knock the first problem off before work. That gives me... half an hour.

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.



My initial thought was to create a collection of all numbers below 1000 that are multiples of 3 or 5 and then simply going through the collection with a loop and adding them all together. I then realised that this is a relatively time consuming way of solving this problem. A much better way would be to simply use a for loop to go through every number from 1 to 1000 and, if it's a multiple of 3 or 5, add it to a running total. This could also be done with recursion (I love recursion), so I'm going to try both ways.

First the simpler method. The pseudo-code looks something like this:
runningTotal = 0
for i = 1 -> 1000
if i is divisible by 3 or 5
runningTotal += i
print runningTotal

And in Java:
public class Problem1 {

 public static void main(String[] args){

  int runningTotal = 0;

  for (int i = 1; i < 10; i++){
   if (i % 3 == 0 | i % 5 == 0){
    runningTotal += i;
   }
  }
  System.out.println(runningTotal);
 }
}
This gives the result "233168" which turns out to be correct. Admittedly I did original have the if statement reading:
if (i % 3 == i / 3 } i % 5 == i / 5){
which obviously didn't work as the maths is completely wrong but give me a break, I haven't done anything like this in more than a year. Maybe I should take a basic maths subject this year...
I've decided against trying this with recursion, I'll save that for another problem. Now, time for work.

No comments:

Post a Comment