大佬教程收集整理的这篇文章主要介绍了在Ruby中筛选Eratosthenes,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
def primeSieve(n) primes = Array.new for i in 0..n-2 primes[i] = i+2 end index = 0 while Math.sqrt(primes.last).ceil > primes[index] (primes[index] ** 2).step(primes.length - 1,primes[index]) {|x| x % primes[index] == 0 ? primes.delete(X) : ""} index += 1 end primes end
>为什么不迭代到数组的末尾?
>根据上面链接中的描述,循环中的数组中最后一个元素的方格大于当前的最大元素,这个循环应该被分解出来.
我确定它与修改数组长度的删除操作有关.例如,当我进入n = 10时,我的功能目前产生2,3,5,7,9,10,这显然是不正确的.有什么建议,我可以如何改变这个,使其工作,就像它应该?
while primes[index]**2 <= primes.last prime = primes[index] primes = primes.SELEct { |x| x == prime || x%prime != 0 } index += 1 end
编辑:我想我想出你是怎么想这样做的.以下似乎是有效的,似乎更符合你原来的做法.
while Math.sqrt(primes.last).ceil >= primes[index] (primes[index] * 2).step(primes.last,primes[index]) do |x| primes.delete(X) end index += 1 end
以上是大佬教程为你收集整理的在Ruby中筛选Eratosthenes全部内容,希望文章能够帮你解决在Ruby中筛选Eratosthenes所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。