what did I do wrong in this functions. I am pretty sure the problem is at base = exp(base, pwr /= 2) * exp(base, pwr /= 2); but I cannot think of a logical reason. is there a possible way to write a parameter like that? thanks in advance. (p.s my output of this function is a 2 which is wrong)
#include <iostream>
using namespace std;
unsigned long& exp(unsigned long& base, unsigned long& pwr)
{
if(pwr == 0)
base = 1;
else if(pwr == 1)
base = base;
else
base = exp(base, pwr /= 2) * exp(base, pwr /= 2);
return base;
}
int main()
{
unsigned long n=2, m = 4;
cout << exp(n,m) << endl;
return 0;
}
Here are five things to note about this line:
baseis passed by reference, not value, so there is only one copy of it and you’re changing its value. This is a bad idea.pwris also passed by reference and you’re changing its value when you use/=instead of just/. There are two/=statements in this line, so after this line runs,pwrnow has one fourth its original value./2is integer division, so it will round down. So if you give it a number like 3 as an exponent, it will not work correctly because 3/2 is 1. If you correct the other mistakes and the call it with an exponent of 7, it will end up only doingexp(2,7) = exp(2,3)*exp(2,3) = exp(2,1)*exp(2,1)*exp(2,1)*exp(2,1) = 16when obviously the correct answer is 128. This function, as designed, will only work correctly when the exponent is a power of 2.