Pythonで数が完全平方数かどうかを判定する
完全平方数とは、ある整数が別の整数の平方として表せる数のことです。例えば、1, 4, 9, 16 などは完全平方数です。数学的な方法で、ある数が完全平方数かどうかを判定できます。
例
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} は完全平方数ではありません")
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} は完全平方数ではありません")
コード解説:
import math:Python の math モジュールをインポートして、math.isqrt関数を使用するため。def is_perfect_square(n)::関数を定義するis_perfect_square、ある数が完全平方数かどうかを判定するために使用する。if n < 0::入力された数が負の数の場合は、直接返すFalse、負の数は完全平方数になり得ないため。sqrt = math.isqrt(n):使用してmath.isqrt関数で計算nの整数平方根。return sqrt * sqrt == n:平方根の2乗が元の数に等しい場合n、その場合は返すTrue、それ以外の場合は返すFalse。number = 16:テスト用の数値を定義する16。if is_perfect_square(number)::呼び出しis_perfect_square関数で16完全平方数かどうかを判定し、結果に応じて対応する情報を出力します。
出力結果:
16 是一个完全平方数その他の拡張
Python3 例