我有一个关于Ruby循环的基本问题.
写入的程序返回第i个素数+1(即示例应返回17).我知道我可以简单地返回cand-1,但我想知道检查在while循环底部是否找到答案的"Ruby方式"是什么,只有在没有的情况下才增加.
def ith_prime(i)
pI = 0 # primes index
divs = []
cand = 2
until pI == i do
if divs.find { |div| cand%div == 0 } == nil
divs << cand
pI += 1
end
cand += 1
end
cand
end
puts ith_prime(7)
> 18
Run Code Online (Sandbox Code Playgroud)
我使用的是loop代替while或until大部分时间.这样我就可以将退出条件放在循环中的任何位置.
我会这样写(如果我理解正确的问题):
def ith_prime(i)
pI = 0 # primes index
divs = []
cand = 2
loop do
unless divs.find { |div| cand%div == 0 }
divs << cand
pI += 1
end
break if pI == i
cand += 1
end
cand
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
733 次 |
| 最近记录: |