0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Project Euler 問題7 「10001番目の素数」

Posted at

問題

10001番目の素数を求めよ。

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 10 001st prime number?

コード(Python)

def isPrimeNum(num, primeNums):
    for primeNum in primeNums:
        if num % primeNum == 0:
            return False;
        if primeNum * primeNum > num:
            return True;

def getNextPrimeNum(primeNums):
    num = primeNums[-1] + 1;
    while (isPrimeNum(num, primeNums) == False):
        num += 1;
    return num;

primeNums = [2]
while(len(primeNums) < 10001):
    next = getNextPrimeNum(primeNums)
    primeNums.append(next)
print(primeNums[-1])

処理時間は約0.1秒でした。


# 5行目
if primeNum * primeNum > num:

の処理を抜くと6秒くらいになります。ループを削る工夫って大事なんだなぁ。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?