The joys of self-reference:
http://siletum.blogspot.ie/2009/07/joys-of-project-euler.html
and repeating one-self. Five years on, I have decided to have a run again at them, from the start this time using Ruby. From the command-line too. The project Euler site has moved on as well.
https://projecteuler.net/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."
1. A brute force
method seems the most straightforward
#!/usr/bin/env
ruby
sum=0
for
i in 1..9
# use modulo – if no remainder then it can be divided by the number
if i % 3 == 0 || i % 5 == 0
sum += i
end
end
puts
"sum of multiples of 3 or 5 below 10 is #{sum}"
the first time I ran
this I used 1..10 and got 33 as the answer for below 10, so should
have used 9
Full program, just
changing up to 999 and 1000 respectively:
#!/usr/bin/env
ruby
sum=0
for
i in 1..999
# use modulo – if no remainder then it can be divided by the number
if i % 3 == 0 || i % 5 == 0
sum += i
end
end
puts
"sum of multiples of 3 or 5 below 1000
is #{sum}"
This is still a
pretty crappy program, but the two reasons for it are to show how
fast you can get going with a Project Euler solution and how
relatively simple it is to get started with the Ruby language. This
was actually my first program in Ruby, so excuse the rough edges. In
subsequent problems I will try to use more of the features of the
language and be less literal.
Current
correct answer is supposed to be: 233168
Researches: Modulo,
logical OR, Ruby # Comment, Ruby end keyword