Calculation of power by means of Recursion

hi,

i calculated the power of a number with the help of a recursion:

[code]
double power(double x, int n)
{
double product;
int count;

if (x==0)
assert(n>0);

if(n >= 0)
{
product = 1;
for (count = 1; count <= n; ++count)
product = product * x;
return product;
}
else
return 1/power(x, -n);
}
[/code]

But now i want to rewrite this function in order to ensure that the time to computer power(x,n) is only log(n). I think i need to use this formula: x^2n = x^n x^n.
But i do not exactly understand how do i have to redefine this function, has anybody here some hints for that... :(

matti


Answer this question

Calculation of power by means of Recursion

  • Deanrm

     mattii wrote:
    hi,

    i calculated the power of a number with the help of a recursion:

    [code]
    double power(double x, int n)
    {
    double product;
    int count;

    if (x==0)
    assert(n>0);

    if(n >= 0)
    {
    product = 1;
    for (count = 1; count <= n; ++count)
    product = product * x;
    return product;
    }
    else
    return 1/power(x, -n);
    }
    [/code]

    But now i want to rewrite this function in order to ensure that the time to computer power(x,n) is only log(n). I think i need to use this formula: x^2n = x^n x^n.
    But i do not exactly understand how do i have to redefine this function, has anybody here some hints for that... :(

    matti


    First thing Array Index always start with 0 .means you can say size of array is 0 to n-1 where n is the total no of argument in your array.so Better if you try to Keep these small thing in your Mind and then Proceed.here is a Small recursive Function to calculate the Power of a Number.

    int power(int b,int a)
    {
        static int c=b;
        if(a==1)
            return b;
        else
            return (power((c*b),a-1));
    }
    int main()
    {
    int a =5;
    cout<<power(a,4);
    return 0;
    }


    Thanx


  • n_jagan

    hi,

    i develeoped a recursive function for the power

    [code]
    double power(double x, int n) {
    if (n < 0)
    return 1/power(x, -n);
    else if (n == 0)
    return 1.0;
    else
    return
    x * power(x, n-1);
    }
    [/code]

    Has this function now already a runtime of log(n), because i thought i have to use this formula x^2n = x^n x^n in any way...

    matti

  • KeithCourage

    Hello,

    You could use pow function instead of writting your own ;)

    Otherwise you could do something like


    bool isOdd = false;
    if (1 == n%2)
    {
    isOdd = true;
    }
    for(int i=0; i<(isOdd (n-1/2):n/2;i++)
    {
    product = product*x;
    }
    product = product*product;
    if (isOdd)
    product=product*x;

    Richard


  • Calculation of power by means of Recursion