Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | math.isqrt() method

Python | math.isqrt() method

Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. 
math.isqrt() method in Python is used to get the integer square root of the given non-negative integer value n. This method returns the floor value of the exact square root of n or equivalently the greatest integer a such that a2 <= n.

Note: This method is new in Python version 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. 
 

Code #1: Use of math.isqrt() method

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(sqrt)
 
n = 100
 
# Get the floor value of
# exact square root of n
sqrt = math.isqrt(n)
print(sqrt)


Output: 

3
10

 

Code #2: Use of math.isqrt() method to check whether the given integer is a perfect square.

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)


Output: 

100 is perfect square
10 is not a perfect square

 

Code #3: Use of math.isqrt() method to find the next perfect square of 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)


Output: 

Next perfect square after 11 is 16
Next perfect square after 37 is 49

 

RELATED ARTICLES

Most Popular

Recent Comments