Saturday, February 6, 2010

Number










Problem :Write a function to find square root of a number

/*
Steps:
Use binary search to find the square root.
1. Initialize, start = 0, end = number, mid = (start+end)/2.
2. Set prevMid = 0, as the previous mid value.
3. Find diff = absolute difference between prevMid and mid.
4. While mid is not the square root of number (i.e. mid*mid != number) and difference diff is greater than 0.0005, 
repeat the following steps:
  a. If mid*mid > number, then the square root will be less than mid. So, set end = mid.
  b. Else, the square root will be greater than mid. So, set start = mid.
  c. Set prevMid = mid
  d. Re-evaluate mid  = (start+end)/2.
  e. Re-evaluate diff from prevMid and mid.

*/

-

-





-

-

1 comment: