I am writing a simple program to calculate base--exp. The problem I am having is that the function "forgets" the prior calculated value to that my answer is always "4" since apparently the var I want to use to aggregate the values is cleared every time the loop recycles:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int pow(int base, int exponent)
{
int total = 1;
for (int count=0; count < exponent; ++count)
{total = base * base; cout<<total;}
return total;
}
main()
{
cout<<pow(2,7);
return 0;
How do get the loop to "remember" the total var when it recycles?
That's because you never increment the total amount, what you are exactly doing is calculating the square over and over again. You need to multiply the previous result by the base, like this:
// invariant: does not cause integer overflow, if exponent == 0 then base != 0
long long ipow( int base, unsigned int exponent ) // logarithmic complexity
{
if( exponent == 0 ) return 1 ;
else if( exponent == 1 ) return base ;
return ipow( base, exponent/2 ) * ipow( base, (exponent+1)/2 ) ;
}
Are you sure about the complexity? Any way I look at it, I need (exponent -1) multiplications to calculate the total.
Granted, a sufficient number of separate processors could theoretically calculate the total in logarithmic time if you sent each recursive ipow call to a new processor, but I don't think that's what you meant.
Alright, here's a working solution for me, but the real question is at the bottom:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
usingnamespace std;
int main()
{
int total(1);
for (int j(1); j<=7; ++j)
{
total = total * 2;
cout<<total<<endl;
}
return 0;
}
What threw me was the overloaded operator in another working example. I wanted to know how this worked but also a workaround (above).
1 2 3 4 5 6 7 8 9 10
// returns the value nBase ^ nExp
int pow(int base, int exponent)
{
int total = 1;
for (int count=0; count < exponent; ++count)
total *= base;
return total;
}
How does this overloaded operator work. I've googled and no clear answer for me.