読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 7

Project Euler

Problem7を解き直しました.

  • 10001st prime

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

https://projecteuler.net/problem=7

問題は「10001番目の素数を求めよ」.

def getPrimeID(num)
  return 2 if num == 1

  count = 1
  i = 3
  loop do
    flag = false
    j = 2
    while j * j <= i
      if (i % j).zero?
        flag = true
        break
      end
      j += 1
    end

    unless flag
      count += 1
      return i if count == num
    end
    i += 2
  end
end

p getPrimeID(10_001)

結局n番目の素数を求めるメソッドを作成しました.