Python| math.iqrt() 方法
Python中的数学模块包含许多数学运算,可以使用该模块轻松执行。
Python中的math.iqrt()方法用于获取给定非负整数值 n 的整数平方根。此方法返回 n 的精确平方根或等效的最大整数 a 的下限值,使得 a 2 <= n。
注意:此方法是Python 3.8 版本中的新方法。
Syntax: math.isqrt(n)
Parameter:
n: A non-negative integer
Returns: an integer value which represents the floor of exact square root of the given non-negative integer n.
代码 #1:使用 math.isqrt() 方法
Python3
# Python Program to explain
# math.isqrt() method
import math
n = 10
# Get the floor value of
# exact square root of n
sqrt = math.isqrt(n)
print(n)
n = 100
# Get the floor value of
# exact square root of n
sqrt = math.isqrt(n)
print(n)
Python3
# Python Program to explain
# math.isqrt() method
import math
def isPerfect(n):
# Get the floor value of
# exact square root of n
sqrt = math.isqrt(n)
if sqrt * sqrt == n:
print(f"{n} is perfect square")
else :
print(f"{n} is not a perfect square")
# Driver's code
isPerfect(100)
isPerfect(10)
Python3
# Python Program to explain
# math.isqrt() method
import math
n = 11
def Next(n):
# Get the ceiling of
# exact square root of n
ceil = 1 + math.isqrt(n)
# print the next perfect square of n
print("Next perfect square of {} is {}".
format(n, ceil*ceil))
# Driver's code
Next(11)
Next(37)
输出:
3
10
代码#2:使用 math.isqrt() 方法检查给定的整数是否是完美的正方形。
Python3
# Python Program to explain
# math.isqrt() method
import math
def isPerfect(n):
# Get the floor value of
# exact square root of n
sqrt = math.isqrt(n)
if sqrt * sqrt == n:
print(f"{n} is perfect square")
else :
print(f"{n} is not a perfect square")
# Driver's code
isPerfect(100)
isPerfect(10)
输出:
100 is perfect square
10 is not a perfect square
代码 #3:使用 math.isqrt() 方法找到 n 的下一个完美平方。
Python3
# Python Program to explain
# math.isqrt() method
import math
n = 11
def Next(n):
# Get the ceiling of
# exact square root of n
ceil = 1 + math.isqrt(n)
# print the next perfect square of n
print("Next perfect square of {} is {}".
format(n, ceil*ceil))
# Driver's code
Next(11)
Next(37)
输出:
Next perfect square after 11 is 16
Next perfect square after 37 is 49