LoginSignup
2
1

More than 3 years have passed since last update.

pythonで素数を判定

Last updated at Posted at 2020-05-11

Sympyの関数を使う(おすすめ)

from sympy import isprime
isprime(11)
実行例
print(isprime(11))
print(isprime(12))
実行結果
True
False

ただし,(理由があるのかもしれないが)引数がfloat形式だと常にFalseを返すようになるので,intに変換する必要がある

実行例
print(isprime(11))
print(isprime(11.0))

#引数をint型に変換する
print(isprime(int(11.0)))
実行結果
True
False
True

関数を自作する場合

import math

def isprime(x):
    if x == 1:
        return False
    if x == 2:
        return True
    for i in range(2, int(x**0.5) + 1):
        if x % i == 0:
            return False
    return True
実行例
print(isprime(11))
print(isprime(12))
実行結果
True
False

雑記

sympyには,素数関連の関数がいろいろある印象がした.
例えば,(a,b)の範囲に何個の素数を含まれるか,や,n番目に大きい素数を求める関数,など.
今後まとめていく予定である.
詳細はこちら

2
1
1

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