isqrt function of math module in Python

The isqrt() function finds the integer square root of a given nonnegative integer using the iterative method of Newton. The Python example invokes isqrt() to find the integer square root of a large integer.

Math Updated 13 Nov 2019 1 min read

Function Name

isqrt

Function Signature

isqrt(n)

Parameters

n – A nonnegative integer for which the integer square root to be found.

Return Value

Integer square root of the given nonnegative integer.

Overview

  • The function isqrt(), of the Python math module returns the integer part of the square root of the input. Compare this with the output of the sqrt() function.
  • The input is a nonnegative integer. The integer part returned is the floor of the square root of the input.
  • The isqrt() function internally uses the Newton"s iteration method.

Example 1

python
# Example Python program that computes the integer square root of a nonnegative integer

import math

# Input

n = 766796512

# Find the integer square root

intSquareRoot = math.isqrt(n);

print("Integer square root of a given number:");

print(intSquareRoot);

Output

Output
Integer square root of a given number:

27691

Example 2

python
# Example Python program that raises a ValueError when

            # math.isrt() is passed a negative integer

            import math

# Get the integer square root of 10

            num = -225

            r = math.isqrt(num)

            print("Integer square root of %d is %d"%(num, r))

Output

Output
Traceback (most recent call last):

  File "/Valli/PythonProgs/isroot.py", line 7, in <module>

    r = math.isqrt(num)

ValueError: isqrt() argument must be nonnegative