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.
- public static float FindSquareRoot1 (int number)
- {
- float result = 0;
- float diff = 0;
- float minDiff = Math.Abs(result * result - number);
- int count = 0;
- float tempResult = 0;
- while (true)
- {
- tempResult = Convert.ToSingle(count) / 1000;
- diff = Math.Abs(tempResult * tempResult - number);
- if (diff <= minDiff)
- {
- minDiff = diff;
- result = tempResult;
- }
- else
- return result;
- count++;
- }
- }
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.
- public static float FindSquareRoot_BS(int number)
- {
- float precision = 0.0001f;
- float min = 0;
- float max = number;
- float result = 0;
- while (max-min > precision)
- {
- result = (min + max) / 2;
- if ((result*result) >= number)
- {
- max = result;
- }
- else
- {
- min = result;
- }
- }
- return result;
- }
-
Please let me know your comments/suggestion or if you have any better ways to do that.