Ruby - 素数计算器

标签 ruby primes

我需要一些反馈来弄清楚为什么我无法在屏幕上放置打印我的方法中的任何内容。这是我编写的一个简单脚本,用于解决查找第 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/

相关文章:

ruby 。如何知道定义了哪个类的实例方法?

ruby-on-rails - 如何在 Rails 脚手架生成器上强制使用单数表名?

ruby - Nokogiri 用 <span>ed 词替换内部文本

javascript - 这个奇怪的 JavaScript 素数检查函数是如何工作的?

javascript - 如何将参数传递给 Rails 中的 js.erb?

ruby-on-rails - 调用 arerel 操作的动态方法

java - 总和(1/质数[i]^2)> = 1?

javascript - 为什么我的筛子没有看到应有的性能提升?

performance - 素数计数功能的可行实现

java - 使用 Java 的 BigInteger 可能素数