Python Check if a Number is a Perfect Square
To determine whether a number is a perfect square, we can use mathematical methods. A perfect square is a number that can be expressed as the square of an integer. For example, 16 is a perfect square because it is the square of 4.
Example
import math
def is_perfect_square(n):
if n < 0:
return False
sqrt = math.isqrt(n)
return sqrt * sqrt == n
# Test
number = 16
if is_perfect_square(number):
print(f"{number} is a perfect square")
else:
print(f"{number} is not a perfect square")
def is_perfect_square(n):
if n < 0:
return False
sqrt = math.isqrt(n)
return sqrt * sqrt == n
# Test
number = 16
if is_perfect_square(number):
print(f"{number} is a perfect square")
else:
print(f"{number} is not a perfect square")
Code explanation:
import math: Import Python's math module so as to usemath.isqrtthe function.def is_perfect_square(n):: Define a functionis_perfect_square, which accepts an integernas a parameter.if n < 0:: Checknwhether it is negative, because a negative number cannot be a perfect square.sqrt = math.isqrt(n): Usemath.isqrtthe function to calculatenthe integer square root ofreturn sqrt * sqrt == n: Check whether the square of the square root equalsn; if so, thennit is a perfect square.number = 16: Define a test number 16.if is_perfect_square(number):: Callis_perfect_squarethe function to determine whethernumberit is a perfect square, and output the result.
Output result:
16 是完全平方数Other Extensions
Python3 Examples