Tuesday, January 18, 2011

Problem 1 - Multiples of 3 and 5

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.

This is essentially FizzBuzz revisited - in Supercollider you can find the solution with one line of code:

({|i|i}!1000).collect({|i|((i%3==0).or(i%5==0)).if({i},{0})}).sum;

({|i|i}!1000)
Generates the integers 0 to 999

.collect({|i|((i%3==0).or(i%5==0)).if({i},{0})})
.collect is an iterator method that maps an anonymous function over a Collection and returns a new collection - in this case we test to see if i modulo 3 or 5 is 0 - if it is, we return the value of i. Otherwise, we return o (which won't be accounted for when we sum to get the final answer).
In Supercollider, any expression is a Boolean so you can write a conditional as (expression).if({true},{false}) - where if is a method that takes 2 functions as arguments, for the true and false conditions.

.sum
Finally, we call the .sum method on the collection to return the sum of the collection's elements.

In the next post I'll post some sonifications of this algorithm.

1 comment:

  1. Hi, would you consider adding this to Rosetta Code? If not, would you object to someone else adding it?

    http://rosettacode.org/wiki/FizzBuzz

    SuperCollider is currently not listed, and it would be neat if it were.

    ReplyDelete