parmigiano
parmigiano

Reputation: 105

Calculate power with a recursive function on C++

I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.

#include"stdafx.h"
#include<stdio.h>
#include<iostream>

using namespace std;

float power(float a, unsigned int b);

int main()
{

    float a = 0;
    unsigned int b = 0;

    cout << "Insert base - ";

    cin >> a;

    cout << "Insert index - ";

    cin >> b;

    float result;

    result = power(a, b);

    cout << result;

    return 0;
}

float power(float a, unsigned int b)
{

    if (b <= 0)
    {
        return a; 
    }

    return (a*power(a, b--));
}

Upvotes: 0

Views: 2217

Answers (3)

zeb
zeb

Reputation: 100

Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.

Stopping criteria

X ^ 0 = 1

Unwinding the stack

The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.

  • If A is the base and B the power, as a first step, take the absolute value of B.
  • Secondly, store A in the stack and decrement B. Repeat until B = 0 (stopping criterion). Store the result in the stack.
  • Thirdly, multiply all the A's stored by unwinding the stack.

Now the code

float power(float a, int b)
{
    int bx = -b ? b < 0 : b;
    if (bx == 0)
    {
        a = 1;
        return a;
    }
    return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}

Upvotes: 0

Morlacke
Morlacke

Reputation: 61

if ( b <= 0) return 1;
return a * power(a, --b);

But this question was asked so many times....

Recursion function to find power of number

Upvotes: 1

JSF
JSF

Reputation: 5321

Instead of b-- you need b-1 (or --b)

b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.

Also, when b is zero, the result should be 1 rather than a

Upvotes: 7

Related Questions