Project Euler: Problem 1

The first prob­lem of Project Euler is very straight forward.

If we list all the nat­ural num­bers below 10 that are mul­ti­ples of 3 or 5, we get 3, 5, 6 and 9. The sum of these mul­ti­ples is 23.

Find the sum of all the mul­ti­ples of 3 or 5 below 1000.

This prob­lem is basi­cally mak­ing sure that the site user has a com­puter lan­guage at their dis­posal and a basic grasp of com­mon oper­a­tions such as loop­ing, if/else, and the mod­ulo operator.

My straight for­ward Ruby code is below. Note that I write every Ruby pro­gram so that it can be run as an exe­cutable script that takes a value from the com­mand line. This value is typ­i­cally assigned to @n within my code. It’s used for prob­lems that solve a gen­eral case. The gen­eral case of this prob­lem is to find the sum of all the mul­ti­ples of 3 or 5 below N.

[source­code language=“ruby”]
#!/usr/bin/env ruby

class Prob­lem

# Cre­ate the object
def ini­tial­ize (n = 10)
@n = n.to_i
@sum = 0

# Solve it
def solve
puts “Find sum of all num­bers under #{@n} disivi­ble by 3 and 5″

@n.times do |k|
@sum += k if k % 3 == 0 || k % 5 == 0

puts “Solu­tion: #{@sum} is solu­tion for n = #{@n}“

if __FILE__ == $0

# Ini­tial­ize the pro­gram
p = ARGV[0] || 10


Leave a Reply