LoginSignup
8
1

More than 3 years have passed since last update.

Pythonで素数列挙

Last updated at Posted at 2019-10-25

概要

Pythonで素数を列挙する

コード

sosuu.py
sosuu=[2];A=10000
for L in range(3,A):
    chk=True
    for L2 in sosuu:
        if L%L2 == 0:chk=False
    if chk==True:sosuu.append(L)
print(sosuu)

追記

コメントにて、もっと見やすくて早い書き方ができるとのアドバイスをいただきました!ありがとうございます!

sosuu_faster.py
sosuu = [2]
A = 100000
for L in range(3, A, 2): # 2 以外の素数は奇数なので
    for L2 in sosuu:
        if L % L2 == 0:
            break # 素数でないことがわかったらそれ以上ループする必要はない
    else: # break で抜けることがなかったら L は素数(Python 特有の制御構文)
        sosuu.append(L)
print(sosuu)

また、内包表記を使用できるとのコメントもいただきました!ありがとうございます!

sosuu_comprehension.py
sosuu = [2]
A = 100000
for L in range(3, A, 2): # 2 以外の素数は奇数なので
    if all(L % L2 != 0 for L2 in sosuu):  # すべての既存素数で割り切れなかったら素数
        sosuu.append(L)
print(sosuu)
8
1
2

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