Python Check Whether a Number Is a Perfect Square
To determine whether a number is a perfect square, we can use a mathematical approach. 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 4 squared.
Example
import
math
def
is_perfect_square
(
n
)
:
if
n
<
0
:
return
False
sqrt
=
math
.
isqrt
(
n
)
return
sqrt * sqrt
==
n
Testing
number
=
16
if
is_perfect_square
(
number
)
:
(
f
"{number} is a perfect square"
)
else
:
(
f
"{number} is not a perfect square"
)
Code analysis:
import math: Import Python's math module in order to usemath.isqrtfunction in Vue 3.def is_perfect_square(n):: Define a functionis_perfect_square, which takes an integernas its argument.if n < 0:: Check whethernCheck whether it is negative, because a negative number cannot be a perfect square.sqrt = math.isqrt(n): When usingmath.isqrtThe function computesnthe integer square root of the number.return sqrt * sqrt == n: Check whether the square of the square root is equal ton, if so, thennis a perfect square.number = 16: Define a test number, 16.if is_perfect_square(number):: Callingis_perfect_squareCall the function to determine whethernumberis a perfect square and print the result.
Output result:
16 是完全平方数
Python3 Examples