I have this function to calculate x to the power of n recursively:
def pow(x:Double,n:Int):Double={
if (n==0) 1
else if (n<0) 1/pow(x,-n)
else if (n%2 == 1) x*pow(x,n-1)
else pow(pow(x,n/2),2)
}
But this won't work for the last case properly (i.e. positive even numbers). It just hangs there. However if I give this:
def pow(x:Double,n:Int):Double={
if (n==0) 1
else if (n<0) 1/pow(x,-n)
else if (n%2 == 1) x*pow(x,n-1)
else {val y=pow(x,n/2); y*y}
}
It runs as expected. Can anyone tell me what makes the first implementation wrong. I am attempting to answer Question 10 from Chapter 2 of the book Scala For Impatient.