我需要一些反馈来弄清楚为什么我无法在屏幕上放置
或打印
我的方法中的任何内容。这是我编写的一个简单脚本,用于解决查找第 1001 个素数的问题。谢谢
def primes
# iterates through numbers until it has the 1001th prime number and returns it.
# I chose to create the num_primes variable instead of counting the number of
# elements in in_prime_array every iteration
# based upon a guess that it would be faster to check.
is_prime_array = []
num_primes = 0
i = 2
loop do
is_prime_array << i && num_primes += 1 if is_prime?(i) == true
i += 1
break if num_primes == 1001
end
is_prime_array[1001]
end
def is_prime? (num)
# Checks to see if the individual number given is a prime number or not.
i = 2
loop do
if i == num
return true
elsif num % i == 0
return false
else
i += 1
end
end
end
感谢您的帮助!
编辑
我听取了你的建议并尝试了这段代码:
def is_prime? (num)
# Checks to see if the individual number given is a prime number or not.
i = 2
loop do
if i == num
return true
elsif num % i == 0
return false
else
i += 1
end
end
end
i = 0
count = 0
loop do
count += 1 if is_prime?(x)
puts "#{i}" if count == 1001
break
end
它仍然没有返回任何内容。嗯嗯
最佳答案
i = 0
count = 0
loop do
if is_prime(i)
count += 1
end
if count == 10001
puts "#{i}"
break
end
end
简单的方法:)
关于Ruby - 素数计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16275379/