#1

# this is what i was to do

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.

``````#My_Code

def three
counter = 0
loop do
counter += 1
next if counter % 3 != 0
puts "#{counter} "
break if counter >= 9
end
end

def five
fi = 0
loop do
fi += 1
next if fi%5 != 0
puts "#{fi} "
break if fi >=10
end
end

three
five

three.each {|x| x}
five.each {|y| y}

print x + y``````

I know it doesn't look pretty but someone help me to write this code from scratch or edit my code tell me where i went wrong and all that! this is how i was going to approach this.

#2

Keeping this objective in mind, we can brute-force an answer in steps:

``````n = 1000
u = Array.new(n) { |x| false }

(3...n).step(3).each do |x|
u[x] = true
end

(5...n).step(5).each do |x|
u[x] = true
end

(0...n).each do |x|
u[x] = u[x] ? x : 0
end

v = u.inject{ |sum,x| sum + x }

# 233168
``````

See if you can glean any ideas from this.

``````def fizzbuzz_sum(n)
u = Array.new(n) { |x| 0 }
(3...n).step(3).each { |x| u[x] = x }
(5...n).step(5).each { |x| u[x] = x }
return u.inject{ |sum, x| sum + x }
end
``````

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.