w3resource

Python Challenges: Compute and return the square root of a given integer


Write a Python program to compute and return the square root of a given 'integer'.

Note: The returned value will be an ‘integer’.

Python: Square root

Sample Solution:

Python Code:

def my_sqrt(x):
   if x<2: return x
   left=1
   right=int(x/2)+1
   while left<=right:
            mid=int((left+right)/2)
            if mid*mid==x:
                return mid
            if mid*mid>x:
                right=mid-1
            else:
                left=mid+1
   return right

print(my_sqrt(16))

Sample Output:

4 

Flowchart:

Python Flowchart: Compute and return the square root of  an  given 'integer'

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to find three numbers from an array such that the sum of three numbers equal to a given number.
Next: Write a Python program to find the single number in a list that doesn't occur twice.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.