Python Determine if a number is a perfect square
A perfect square is an integer that can be expressed as the square of another integer. For example, 1, 4, 9, 16, etc. are all perfect squares. We can use mathematical methods to determine whether a number is a perfect square.
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 analysis:
import math: Import Python's math module to usemath.isqrtfunction.def is_perfect_square(n):: Define a functionis_perfect_square, used to determine whether a number is a perfect square.if n < 0:: If the input number is negative, directly returnFalse, because a negative number cannot be a perfect square.sqrt = math.isqrt(n): Usemath.isqrtfunction to calculatenthe integer square root ofreturn sqrt * sqrt == n: If the square of the square root equals the original numbern, then returnTrue, otherwise returnFalse。number = 16: Define a test number16。if is_perfect_square(number):: Callis_perfect_squarefunction to determine16whether it is a perfect square, and output corresponding information based on the result.
Output result:
16 是一个完全平方数Other extensions
Python3 Examples