The question was:
Write a function that calculates the root of a given number.
- Answer A = I wrote it for integers. just run up to half of the number
- Answer B+C = are for double, using Newton's law.
I just implemented this in C#.
They all work and were tested.Please comment me about anything from not well written code, complexity, style, or give a better solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class FindSquareRoot
{
public FindSquareRoot()
{
int numberToFind = 49;
int res = SquareRoot(numberToFind);
Console.WriteLine(res);
double doubleNumberToFind = 157.0;
double resDouble = SquareRoot(doubleNumberToFind);
Console.WriteLine(resDouble);
resDouble = SquareRootBetter(doubleNumberToFind);
Console.WriteLine(resDouble);
}
public int SquareRoot(int number)
{
int half = number / 2;
int counter = 0;
while (counter < half)
{
if (Math.Pow(counter, 2.0) == number)
{
return counter;
}
counter++;
}
return half;
}
public double SquareRoot(double number)
{
double precision = 10e-8;
double low = 0.0;
double high = 0.0;
double prev = 0.0;
double mid = number / 2.0;
while(Math.Abs(mid - prev) > precision )
{
if(Math.Pow(mid,2) > number)
{
high = mid;
}else
{
low = mid;
}
prev = mid;
mid = (low+high)/ 2.0;
}
return mid;
}
public double SquareRootBetter(double number)
{
double precision = 10e-8;
double prev = 0.0;
double mid = number;
while(Math.Abs(mid - prev ) > precision)
{
prev = mid;
mid = (mid +(number/ mid))/2.0;
}
return mid;
}
}
}