1
0

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 1 year has passed since last update.

pythonで素数判定のためにエラトステネスの篩でテーブルを作る

Last updated at Posted at 2022-02-19

以下を参考にさせて頂いています。

エラトステネスの篩

  1. 簡単なもの
def primes(n):
    is_prime = [True] * (n + 1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, n + 1):
        for j in range(i * 2, n + 1, i):
            is_prime[j] = False
    return [i for i in range(n + 1) if is_prime[i]]

以下のような、 n までの素数テーブルを用意するclass(素数であればTrue)を作成する

import math

# n までの素数テーブルを用意するclass(素数であればTrue)
# n-1までの整数が素数かどうかを判定する
class PrimeClass:
    def __init__(self, n):
        self.prime=[True]*(n+1)
        self.prime[0]=False
        self.prime[1]=False
        rangeMax = int(math.sqrt(n))
        for p in range(rangeMax):
            if self.prime[p] == True:
                for i in range(p*p, n+1, p):
                    self.prime[i]=False

    def isPrime(self, val):
        if val >= len(self.prime)-1:
            return None
        return self.prime[val]

Prime = PrimeClass(200)
print(Prime.isPrime(197))
print(Prime.isPrime(198))
print(Prime.isPrime(199))
print(Prime.isPrime(200))
print(Prime.isPrime(202))
print(Prime.isPrime(201))

print("---")
Prime2 = PrimeClass(4)
print(Prime2.isPrime(2))
print(Prime2.isPrime(3))
print(Prime2.isPrime(4))

以下の部分が出力される

$ python test.py
True
False
True
None
None
None
---
True
True
None

以上です。

参考

エラトステネスの篩

1
0
6

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?