13

Calculate nth power of P (both p and n are positive integer) using a recursive function myPowerFunction(int p, int n, int &currentCallNumber). currentCallNumber is a reference parameter and stores the number of function calls made so far. myPowerFunction returns the nth power of p.

int myPowerFunction(int p, int n, int &z)
{
    z++;
    if(n==1)return p;
    else if(n==0)return 1;
    else if(n%2==0)return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z);
    else return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z)*p;
}

int main()
{
    cout << myPowerFunction(3,4,1);
}
kfsone
  • 23,617
  • 2
  • 42
  • 74
Rajat Patel
  • 139
  • 1
  • 1
  • 4

4 Answers4

15

You need a variable to pass as the third argument in main_program. You can't pass a constant as a non-const reference.

int count = 0;
std::cout << myPowerFunction(3, 4, count) << 'n';
std::cout << count << '\n';
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
3

You don't have to give a reference as parameter as many here state. But yes, your input for z cannot be modified as it comes from read-only memory. Treat the input for z as const, copy z internally and give the copy as reference. Then your desired usage works:

int myPowerFunction(int p, int n, const int &z) // z is now const !
{
    int _z = z + 1; // copy !
    if (n == 1) return p;
    else if (n == 0) return 1;
    else if (n % 2 == 0) return myPowerFunction(p, n /2 , _z) * myPowerFunction(p, n / 2, _z);
    else return myPowerFunction(p, n / 2, _z) * myPowerFunction(p, n / 2, _z) * p;
}

int main()
{
  std::cout << myPowerFunction(3, 4, 1);
}
m.w.
  • 471
  • 4
  • 9
2

Third parameter expects a lvalue, so you cannot pass numeric constant there, so possible solution can be:

int z = 1;
cout<< myPowerFunction(3,4,z);

or better to create a function that calls recursive one:

int myPowerFunction(int p, int n)
{
    int z = 1;
    return myPowerFunction(p,n,z);
}
Slava
  • 43,454
  • 1
  • 47
  • 90
2

In myPowerFunction(3,4,1) the literal 1 cannot be passed to a non const reference as it is a prvalue [basic.lval]. You need to store the value into a variable and then use that variable when calling the function.

int z = 0;
std::cout << myPowerFunction(3, 4, z);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402