Programming Que: Implement Square Root Method using C#

I am here again with another example where we will see how to find square root of a number without using .NET library method.

Let’s start with basic one though it’s not efficient as it considers all the number starting from 0.001 till the difference of multiplying both numbers and the number given is less than the previous iteration.

It’s not efficient as it took 3003 iterations to find the square root of 9.

  1. public static float FindSquareRoot1 (int number)  
  2. {  
  3.     float result = 0;  
  4.     float diff = 0;  
  5.     float minDiff = Math.Abs(result * result - number);  
  6.     int count = 0;  
  7.     float tempResult = 0;  
  8.     while (true)  
  9.     {  
  10.         tempResult = Convert.ToSingle(count) / 1000;  
  11.         diff = Math.Abs(tempResult * tempResult - number);  
  12.         if (diff <= minDiff)  
  13.         {  
  14.             minDiff = diff;  
  15.             result = tempResult;  
  16.        }  
  17.        else  
  18.            return result;  
  19.            count++;  
  20.      }  
  21. }   

Now let’s see another way which is efficient as it uses Binary Search.

It’s really efficient as It took just 17 iterations to find the square root of 9.

  1. public static float FindSquareRoot_BS(int number)  
  2. {  
  3.     float precision = 0.0001f;  
  4.     float min = 0;  
  5.     float max = number;  
  6.     float result = 0;  
  7.     while (max-min > precision)  
  8.     {  
  9.         result = (min + max) / 2;  
  10.         if ((result*result) >= number)  
  11.         {  
  12.            max = result;  
  13.         }  
  14.         else  
  15.         {  
  16.            min = result;  
  17.         }  
  18.    }  
  19.    return result;  
  20. }   
  21.    

Please let me know your comments/suggestion or if you have any better ways to do that.