This is the first of a series of articles about project euler, a set of mathematics problems of incremental difficulty to be solved with your preferred programming language. You can find more about this on the
project website.
PROBLEM N 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.
Solution using Ruby
The solution above is extremely simple and readable, which is why I love ruby and use it in my every day work:
def is_a_multiple_of_3_or_5?( n )
n % 3 == 0 || n % 5 == 0
end
counter = 0
3.upto( 999 ) do |n|
counter += n if is_a_multiple_of_3_or_5?( n )
end
puts counter
Solution using Erlang
I'm totally new to Erlang, but I've worked to a one-line solution using a comprehension list:
Result = lists:sum([ N || N <- lists:seq(1,999), N rem 3 == 0 orelse N rem 5 == 0 ]).
Basically, I create a list of all numbers under 1000 which are either multiples of three or multiples of five, then I've calculated the sum of all those numbers with the native procedure lists:sum.
Solution using Scheme
I love scheme, although I've never done that much with it:
(define total
(lambda (n counter)
(cond
((> n 999) counter)
((or (= (remainder n 3) 0) (= (remainder n 5) 0))
(total (+ n 1) (+ n counter)))
(else (total (+ n 1) counter)))))
(display (total 3 0))
Conclusion
It was very simple to figure out the solution for this problem, but the point here for me is to exercise my programming skills with a series of problems. Feel free to send me your suggestions in the comments, especially about Erlang and Scheme, where I'm still new, and I need to improve.