Recursion Help

I am trying to write a power function using recursion but having some issues. Any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include <iostream>
#include <cmath>

int power(int base, int exp); // return base to the power of exponent
                              // where base and exp are members of Integers  
using namespace std;

int main()
{
    cout << power(3,2) << endl;
    cout << power(4,1) << endl;
    cout << power(5,0) << endl;
    cout << power(-2,2) << endl;
    cout << power(-2,3) << endl;
    cout << power(-2,-2) << endl; // Out put here is 0
    cout << power(-2,-4) << endl; // Out put here is 0 as well.
}

int power(int base, int exp)
{
    if(exp == 0)
        return 1;
    else if(exp > 0)
        return  base * power(base,exp-1);
    else
        return 1.0 /(base * power(base,abs(exp)-1));
}
You've defined the power function to return an integer, but the actual result of power( -2, -4 ) is 0.0625, which is definitely not an integer.

Return a float or double and you'll be more in gear.
Change your power function’s return type to double to see why.

Also, keep it simple:

26
27
        return 1.0 / power(base,abs(exp));
}

Hope this helps.
Last edited on
Thank you guys!!! Rookies mistakes for a rookie.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cmath>

double power( int base, int exp )
{
    // note: std:pow(0,0) returns 1 (IEEE), but we return NaN
    // see: https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero
    if( base == 0 ) return exp == 0 ? NAN : 0 ;

    if( exp == 0 ) return 1 ;

    if( exp < 0 ) return 1.0 / power( base, -exp ) ;

    // exponentiation by repeated squaring
    // x^10 == x^5 * x^5 and x^11 == x^5 * x^5 * x
    const double root = power( base, exp/2 ) ;
    return root*root * ( exp%2 == 0 ? 1 : base ) ;
}

int main()
{
    for( int base = -3 ; base < 5 ; ++base ) for( int exp = -3 ; exp < 7 ; ++exp )
    {
       std::cout << "power( " << base << ", " << exp << " ) == " << power(base,exp)
                 << "   (" << std::pow(base,exp) << ")\n" ;
    }
}

http://coliru.stacked-crooked.com/a/3232a684f3854a13
Topic archived. No new replies allowed.