Python で数が平方数かどうかを判定

Document 对象参考手册Python3 実例

ある数が平方数かどうかを判定するには、数学的な方法を使うことができます。平方数とは、ある整数の2乗として表せる数のことです。例えば、16 は 4 の2乗なので平方数です。

実例

import math

def is_perfect_square(n):
    if n < 0:
        return False
    sqrt = math.isqrt(n)
    return sqrt * sqrt == n

# テスト
number = 16
if is_perfect_square(number):
    print(f{number} は平方数です)
else:
    print(f{number} は平方数ではありません)

コードの解説:

  1. import math:Python の数学モジュールをインポートして、使用するためmath.isqrt関数。
  2. def is_perfect_square(n)::関数を定義するis_perfect_square、それは1つの整数を受け取りnを引数とします。
  3. if n < 0::チェックするnが負の数かどうか。負の数は平方数ではあり得ないためです。
  4. sqrt = math.isqrt(n):使用するmath.isqrt関数で計算nの整数平方根。
  5. return sqrt * sqrt == n:平方根の2乗が等しいかどうかを確認するn、もし等しければ、nは平方数です。
  6. number = 16:テスト用の数値 16 を定義します。
  7. if is_perfect_square(number)::呼び出すis_perfect_square関数で判定numberが平方数かどうかを判定し、結果を出力します。

出力結果:

16 是完全平方数

Document 对象参考手册Python3 実例

その他の拡張