gpt4 book ai didi

Ruby - 质数计算器

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:00 24 4
gpt4 key购买 nike

我需要一些反馈来弄清楚为什么我不能通过我的方法在屏幕上putsprint 任何东西。这是我为解决寻找第 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com