Thread: Need help in calculating powers/roots

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    14

    Need help in calculating powers/roots

    Hi, I wrote this function to calculate powers, like x^n. It works for integer values, but I can't get it to calculate roots, like root 5 = 5^(1/2).

    Can someone tweek this a little bit for me? thx in advance.

    (The base is x, the exponent is n)

    int power(int x, int n)
    {
    int r; // result of calculation
    int p;

    r = 1;
    p = x;

    while (n > 0)
    {
    if (n % 2) // n is even
    r = r * p;

    p = p * p;
    n = n / 2;
    }

    return r;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > int power(int x, int n)
    How do you represent a half (0.5, 1/2) in the integer 'n'?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Root finding is much more difficult. You might want to look up the Newton root finding method (sometimes calles Newton-Raphson).
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calculating : high numbers
    By MiraX33 in forum C++ Programming
    Replies: 9
    Last Post: 06-08-2006, 11:08 PM
  2. Calculating CPU Usage
    By vitaliy in forum Linux Programming
    Replies: 3
    Last Post: 08-21-2005, 09:38 AM
  3. Recursion
    By Lionmane in forum C Programming
    Replies: 11
    Last Post: 06-04-2005, 12:00 AM
  4. Taking input while calculating
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 07-12-2002, 04:47 PM
  5. Calculating window sizes
    By Mox in forum Windows Programming
    Replies: 3
    Last Post: 11-08-2001, 09:17 PM