calculate square root of n in csharp

To calculate the square root of a number in C#, you can use the Math.Sqrt() function:

main.cs
double result = Math.Sqrt(n);
30 chars
2 lines

where n is the number you want to find the square root of. The function returns a double value that represents the square root of the given number.

Alternatively, you can implement your own algorithm to calculate the square root of a number. One simple method is the Babylonian method, also known as Heron's method, which uses an iterative formula to approach the square root of a number:

main.cs
double sqrt(double n)
{
    double x = n;
    double y = 1;
    double epsilon = 0.000001;  // tolerance for numeric error
    
    while (x - y > epsilon)
    {
        x = (x + y) / 2;
        y = n / x;
    }
    
    return x;
}
233 chars
15 lines

In this algorithm, we start with an initial guess x for the square root of n, and improve the guess iteratively by the formula x = (x + n / x) / 2. We continue this process until the difference between x and n / x is less than a given tolerance epsilon, which ensures a reasonable level of numerical accuracy. Finally, we return the estimated square root x.

gistlibby LogSnag