Hi all,

I need to write a recursive function to calculate a^n. When the 
function call ends, it needs to return the number of multiplications 
it did. I've written the code, which calculates a^n, but I can't get 
the count to work properly. Could you tell me where I'm going wrong. 
I'm getting the following error:

power_alg.cpp:33: error: reference to âcountâ is ambiguous
power_alg.cpp:5: error: candidates are: int count

Below is the complete code I'm using.


#include <iostream>
using namespace std;

int count = 0;
float Power(float a, int n)
{
  float result;

  if (n == 0)
    {
      result = 1;
      count = 0;
    }
  else if (n == 1)
    {
      result = a;
      count = 0;
    }
  else if (n % 2 == 0)
    {
      result = Power(a*a, n/2);
      count++; //count as one multiplication
    }
  else if (n % 2 == 1)
    {
      result = Power(a*a, (n-1)/2) * a;
      count += 2; //count as two multiplications
    }

  return result;

} //end Power function

int main()
{
  float a; 
  int n;

  cout << "Please enter a number: ";
  cin >> a;

  cout <<"Please enter the power you're raising the number to: ";
  cin >> n;

  float answer = Power(a, n);

  cout << "The result is: " << answer << endl;
  cout << "The number of multiplications it takes is: " << count << 
endl;

} //end main function

I would appreciate it very much if someone could help me out here.

Thanks,
Chai.

Reply via email to