Sunday, 9 September 2012

Square root of a number upto accurate 6 decimal points

Implement a fast integer square root function that takes in a unsigned integer and returns another unsigned integer that is the square root of the input correct up to 6 decimal places.

Solution:
Classic application of Binary search Algorithm to solve the square root problem. A question asked in FB interview. Coded in python one of my fav programming language cant believe i ditched C++ :(. I'm still novice in python but would love to code more and more in python.

I need a better solution to stop at after 6 places after the decimal point, one other obvious solution is to run the while loop six times, but i need a mathematical rule which controls the loop.

#------------------------------------------------------------------------------- # Name: SquareRoot.py # Purpose: Implement a fast integer square root function that # takes in a unsigned integer and returns another unsigned integer that is # the square root of the input correct upto 6 decimal places. # # Created: 09/09/2012 #------------------------------------------------------------------------------- def main(): number=334567 sqroot=findsqroot(number) print(sqroot) def findsqroot(number): i=0 for i in range(number+1):# for 1 and 2 special cases input we need number+1 product=i*i if product > number: break; elif product == number: return i print(i) rootbase=i-1 begin,end=rootbase,i mid=(begin+end)/2 product=mid*mid while ((mid-rootbase)*1000000%10) == 0: if product > number: end=mid elif product < number: begin=mid else: return mid mid=(begin+end)/2 product=mid*mid return mid if __name__ == '__main__': main()

No comments:

Post a Comment