我想编写一个代码,打印出100以下的所有素数。这是我到目前为止的代码
class Numbers
def is_a_prime?(int)
x = 2
while x < int/2
if int % x == 0
return false
else
return true
end
end
end
def primes_under_100
x = 2
while x < 100
print x if is_a_prime?(x) # calling the method I defined above
x+= 1
end
end
end
不幸的是,当我使用primes_under_100调用方法时,我得到了
undefined local variable or method 'primes_under_100' for main:Object
我想知道我哪里出错了。我的方法都不是私密的。感谢帮助。
答案 0 :(得分:2)
另一种方法是扩展Fixnum。有了这个,你应该可以在int值上调用它。
这应该是这样的
class Fixnum
def is_a_prime?
(2..(self/2)).each do |x|
if self % x == 0
return false
end
end
return true
end
end
答案 1 :(得分:0)
你怎么称呼它?它们是Number
类的公共方法,因此为了调用它们,您需要实例化Number
类的对象:
number = Numbers.new
primes = number.primes_under_100
另外,正如Leo Correa在我的回答中所说的那样,方法is_a_prime?
无法像这样调用,你应该使用:
print x if is_a_prime?(x)
答案 2 :(得分:0)
为了使您的代码有效,您需要进行以下修改
class Numbers
def is_a_prime?(int)
x = 2
while x < int/2
if int % x == 0
return false
else
return true
end
end
end
def primes_under_100
x = 2
while x < 100
# Notice you're calling is_a_prime? on the instance of the Numbers object
# and sending x as an argument. Not calling is_a_prime? on the 'x'
print x if is_a_prime?(x)
x+= 1
end
end
end
然后拨打Numbers.new.primes_under_100
答案 3 :(得分:0)
我不知道哪个版本的Ruby在Prime中包含此方法,但是如果您使用的是2.2及更高版本,则可以这样做。
将此添加到文件顶部
require 'prime'
以及在特定数字下显示素数的方法。
Prime.each(100) do |prime|
p prime #=> 2, 3, 5, 7, 11, ...., 97
end