2

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.

2 Answers 2

3

With your method at some point you end up doing:

pow(pow(x,1),2) -> pow(x*pow(x,0),2) -> pow(x,2) -> pow(pow(x,1),2) -> ...

This is because n==2 is only handled by the last condition which ends up calling itself over and over again...

Sign up to request clarification or add additional context in comments.

Comments

2

You always call pow(...,2) in the last case, and the last case is the only one that handles n==2. So....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.