
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Square Root of 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
Example (Python)
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))
Input
print(ob1.mySqrt(4)) print(ob1.mySqrt(16)) print(ob1.mySqrt(7)) print(ob1.mySqrt(15))
Output
2 4 2 3
Advertisements