I'm writing a 3 function program for homework. The first and third functions seem to work fine, but the second does not.
The function is a recursive function that should do x to n power. It works for whatever x is, and only up to the power of 5. After that, it always returns a 0.
Here's the code...any advice would be appreciated.
Only your first function is good.
What the second one does is not xn, but x2^n (^ is exponentiation. Apparently you can't have nested sup tags here..), so when n=5, 25=32 and for any x!=1, x32 is more than fits in an integer.
The correct way is return rec(x, n-1)*x;
I assume the purpose of the third one is a faster algorithm where x4 is (x2)2, and this should work fine. However, what if you have x6? Then it should be ((x2)*x))2. I suppose that's the purpose of line 34, but it will never be reached, since (n) evaluates to true when n != 0. Did you mean (n%2 == 0)?
Hamsterman....odd question here...I put in your recommended change and it worked. I then took the // away and ran the full three functions. Function 1 and 2 were supposed to give the same output.
I then went into function 1 and changed the int i = 1 to i=0, and now they both give the same output. I then double checked and they are giving the correct answer.
Thanks!
The third function....I took it verbatim out of my class notes the professor provided.....and when I put in the test numbers the output seems correct.
When I looked at it again, you are right, the (n) was wrong, it needed the n%==2.
integer is 32 bits. 1 for sign (sort of), 31 for the number, so the maximum value you can calculate with these functions is 231. If you feel that you need more, see http://gmplib.org/
x also has to be long long int. That's because C++ operators preserve type. int*int will always return int, even if you assign it to long long int. For operator * to return long long int, at least one of it's arguments has to be one too.