Project Euler problem 5 asks:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I'm learning Ruby by going through Project Euler problems, and though I got the following code right (as in the answer given by it), I'm not sure if I'm doing things quite the "Ruby way". Hence, I wanted the community's opinion of my code to better understand alternatives to my code (using the same algorithm please!), so that I don't become used to writing "C++ using Ruby!"
def prime? x
(2..x-1).each { |y| return false if x % y == 0 }
true
end
def primes_upto n
p = Array.new
(2..n-1).each {|x| p.push(x) if prime? x}
return p
end
upto = 20 # The upper limit of the LCM range
primes = primes_upto upto
range = Array.new(upto) {|i| i + 1}
lcm = 1
primes.each do |i|
flag = true
while flag and range.length > 0
range.each do |x|
if x % i == 0
flag = true
break
else
flag = false
end
end
if flag
lcm *= i
range.map! {|y| y % i == 0? y/i : y}
end
range.delete(1)
range.compact!
end
end
print "\nLCM of 1..", upto, " = ", lcm
In particular, I would like to take advantage of ruby's built-in operators on Array, to reduce the size of the code, as well as make it less of an if-then, while structure that I've seen in C++ programs.
The algorithm I've used can be found here (if its not obvious from the code!)