i assumed the numbers are positive..
--
Amol Sharma
Third Year Student
Computer Science and Engineering
MNNIT Allahabad
http://gplus.to/amolsharma99
http://twitter.com/amolsharma99http://in.linkedin.com/pub/amol-sharma/21/79b/507http://www.simplyamol.blogspot.com/
On Fri, Jun 1, 2012 at
the return type is int, hence when xpowern becomes bigger than INT_MAX, it
should throw an exception.
Best Regards
Ashish Goel
Think positive and find fuel in failure
+919985813081
+919966006652
On Thu, May 31, 2012 at 11:59 AM, Amol Sharma amolsharm...@gmail.comwrote:
i didn't got your
for checking overflow you can check the value after and before the
multiplication..if value after multiplication is less then there is
overflow for sure
now code will look like this :
int pow(int b, int e)
{
int result = (e 1) ? b:1;
int prev;
while( e 1 )
{
prev=b;
@Amol: You've chosen to use -1 as an error return. But -1 is the correct
response if b = -1 and e is odd. Furthermore, isn't the inequality in the
if(prevresult) statement backwards. E.g., if b = 2 and e = 3, then the
code returns -1. Even reversing the inequality doesn't fix the problem when
This algo is log(n) algo for finding power. However, this also has a
problem of overflow. How do we control this.
int power(int x, int n) {
int expo =1;
int even=x;
while (n0)
{
while (n 0x1==0) {
n=1; /*divide by 2*/
even*=even;
}
expo = expo*even;