Isqrt Function Of Math Module In Python

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:

# 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:

Integer square root of a given number:

27691

Example 2:

# 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:

Traceback (most recent call last):

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

    r = math.isqrt(num)

ValueError: isqrt() argument must be nonnegative

 


Copyright 2024 © pythontic.com