Multiples of 3 and 5
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 should be a fairly straightforward problem in imperative languages. Let's attempt it in one of the more elegant imperative languages - Python
Find the sum of all the multiples of 3 or 5 below 1000.
This should be a fairly straightforward problem in imperative languages. Let's attempt it in one of the more elegant imperative languages - Python
>>> def euler1():
answer = 0
for x in range(1000):
if x % 3 == 0 or x % 5 == 0:
answer += x
return answer
>>> euler1()
233168
The answer is 233168. Of course, we could have made this simple program more generic by taking 1000 as parameter and all that, but that is not the point here. Let's attempt this in Clojure. And here comes the solution -
(reduce +
(filter #(or (zero? (mod % 3))
(zero? (mod % 5)))
(range 1000))
)
The answer is 233168. As is evident from the indentation - we calculate the numbers less than 1000 which are divisible either by 3 or 5 and apply filter function over it. We reduce the values and obtain total by applying the + function.
No comments:
Post a Comment