- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sqrt(x) in Python
Suppose we have a number x, and x is a non-negative number. We have to find the square root of x without using any library functions. So we have to create our own function to evaluate sqrt(x). In this function, the decimal digit of the output will be truncated.
Suppose the value of x is 4, then the result will be 2 if the x is 8, then the result will be also 2, as sqrt(8) is 2.82842. But we will take only the integer part.
To solve this, follow these steps −
- initialize l = 1, and h = x + 1, answer = 0
- while h > l, do
- mid = (h + l)/2
- if mid*mid <= x, then l := mid + 1, answer = mid
- otherwise h = mid
- return answer
Let us see the implementation to get better understanding
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ low = 1 high = x+1 ans = 0 while high>low: mid = (high+low)//2 print(low,mid,high) if mid*mid<=x: low = mid+1 ans = mid else: high = mid return ans ob1 = Solution() print(ob1.mySqrt(4)) print(ob1.mySqrt(16)) print(ob1.mySqrt(7)) print(ob1.mySqrt(15))
print(ob1.mySqrt(4)) print(ob1.mySqrt(16)) print(ob1.mySqrt(7)) print(ob1.mySqrt(15))
2 4 2 3
- PHP sqrt() Function
- sqrt() function in PHP
- sqrt, sqrtl and sqrtf in C++
- Java sqrt() method with Examples
- Sqrt, sqrtl, and sqrtf in C++ programming
- sqrt ( ) function for complex number in C++
- Differences between Python 2.x and Python 3.x?
- Program to check number is perfect square or not without sqrt function in Python
- Pow(x, n) in Python
- Count Elements x and x+1 Present in List in Python
- Important differences between Python 2.x and Python 3.x with examples
- What are the differences in between python 2.x and python 3.x versions?
- What are the key differences between Python 2.7.x and Python 3.x?
- Program to find X for special array with X elements greater than or equal X in Python
- Difference between x++ and x = x+1 in Java