I don’t know why but it keeps saying that prime?(num) method is not defined…
I am trying to make it so that it finds the product of prime numbers between 1 and 20
class LCM200
def prime?(num)
if num == 1 then
return false
end
range = Math.sqrt(num)
for i in 2..range
if num%i == 0
return false
end
return true
end
end
#if __FILE__ == $0
lcm = 1
for j in 1..20 do
if prime?(j)
lcm *= j
end
end
puts lcm
#end
end
The issue is because you’re running the code inside a class. Inside a class,
prime?gets defined as an instance method of the class, however when you’re running the for loop inside the class you’re callingprime?as though it were a class method (aka static method). To fix it, just remove the class declarations:You can also define
prime?in a more “Ruby-ish” way:Documentation for Enumerable#all?