In a vain attempt to become productive and cultivate motivation and some kind of order into my otherwist Street Fighter 4 driven life I’m attempting to get all of the Project Euler puzzles done and to write a little bit about my solution and writing a better solution. In some, probably most, cases, I will also have to go through some theory of how I got to the solution.

The first puzzle has to do with finding the sum of a series of natural numbers. It’s very close to a question that I’ve added to our list of interview questions recently labelled FizzBuzz.

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

If you know how to program, or program on a regular basis the answer to this is quite straight forward and has the following steps.

For each number, starting at 1 and ending with 100

If the number divided by three has zero remainder output Fizz

If the number divided by five ALSO has a zero remainder output Buzz

If the number divided by five has zero remainder output Buzz

Otherwise, output the number

What we can do here, is replace the outputting of Fizz and Buzz with a summation of that number giving us the following, simpler pseudo code or flow.

For each number, starting at 1 and ending with 100

If the number divided by three has zero remainder, add it to the ‘output’.

OR If the number divided by five has zero remainder, add it to the ‘output’.

Otherwise, do nothing.

After we reach 100, print ‘output’

The more important thing about this is that we recognise the OR, a number that has a remainder of zero when divided by both five and three must not be added to the output twice.

The actual Project Euler first question is as follows:

Find the sum of all the multiples of 3 or 5 below 1000.

To solve this with a programming language it is beneficial to know about modulo arithmetic and the modulo operator, but I don’t have time to go in to this at the moment.

In future I hope to go in to other peoples solutions and how optimization is brought into Project Euler.

Advertisements

Like this:

LikeLoading...

Related

This entry was posted on Tuesday, March 30th, 2010 at 09:02 and is filed under Programming, Project Euler. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Thanks for the hint on the OR, I thought I had the right answer but forgot that I shouldn’t add numbers that are multiples of 3 AND 5. A simple else-if solved it.

Thanks for the hint on the OR, I thought I had the right answer but forgot that I shouldn’t add numbers that are multiples of 3 AND 5. A simple else-if solved it.