find the nth root of a number in csharp

To find the nth root of a number in C#, you can use the Math.Pow() function along with some math calculations. Here's an example:

main.cs
public static double NthRoot(double number, int n)
{
    if (n == 0) return 0; // Undefined
    if (number < 0 && n % 2 == 0) return double.NaN; // Undefined
    if (number == 0) return 0; // Zero

    double x = number / n;
    double lastX = 0;

    while (Math.Abs(x - lastX) > 0.000001)
    {
        lastX = x;
        x = ((n - 1.0) * x + number / Math.Pow(x, n - 1)) / n;
    }

    return x;
}
402 chars
18 lines

This function takes in two parameters: the number you want to find the nth root of, and the value of n (the root you want to find). It first handles some edge cases such as undefined values or zero. It then initializes the first guess for x to be number / n. It then iteratively calculates a better guess for x using the formula (n - 1) * x + number / x^(n - 1) / n until the difference between the current guess and the last guess is small enough (in this example, we use a tolerance of 0.000001). The final value of x is returned as the nth root of the number.

gistlibby LogSnag