Calculate the Nth root of a number in C#

To calculate the Nth root of K you can simply use the formula:

    root = K1/N

The following code gets the numbers, calculates the root, and checks the result.

// Calculate the root.
private void btnCalculate_Click(object sender, EventArgs e)
{
double number = double.Parse(txtNumber.Text);
double root = double.Parse(txtRoot.Text);

// Calculate the root.
double result = Math.Pow(number, 1 / root);
txtResult.Text = result.ToString();

// Check the result.
double check = Math.Pow(result, root);
txtCheck.Text = check.ToString();
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 4/29/2013 4:58 PM TheGuyWhoDisliked wrote:
    This uses the math features of C#. This does not do it recursively. Those are the reasons I disliked this.
    Reply to this
    1. 5/1/2013 8:57 AM Rod Stephens wrote:
      The intent here was to just do the job, not to show how to calculate the number yourself. If you do want to do it yourself, you can use Newton's method as shown in this example:

      Use Newton's method to find the roots of equations in C#

      Simply find the roots of the equation Y = XN.

      Or you can use subdivision. Pick an upper and lower bound, perhaps lower = 1 and upper = N / 2. Then check the value in the middle M. If MN > N, set lower = M and repeat. If MN < N, set upper = M and repeat.

      Either way it still doesn't need to be recursive, though.
      Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.