An efficient way of computing a power x^n (where n is a nonnegative integer) is given by the recursion
x^n = y^2 if n is even and positive, where y = x^(n / 2)
x^n = x· x^(n - 1) if n is odd
x^0 = 1
Write a Scala function pow(x : Double, n : Int) : Int that implements this algorithm. What is the code of your function?
Jesper de Jong wrote:
Can't you stop the program with Ctrl-C when it goes into an infinite loop? Does it maybe have to do with you using PowerShell instead of the old-fashioned command prompt window?
Samuel Cox wrote:The reason is because the former creates a function (no evaluation), whereas the latter tries to evaluate the function, pow(x, n/2), and assign the value to y. As Jesper pointed out, this evaluation causes the infinite loop. In the former, you are basically doing what you are trying to avoid, which is computing the same value twice. Scala is nice, but it's no Haskell;) Jesper's solution is what I was suggesting.
Samuel Cox wrote:did not. The reason is because the former creates a function (no evaluation), whereas the latter tries to evaluate the function, pow(x, n/2), and assign the value to y. As Jesper pointed out, this evaluation causes the infinite loop. In the former, you are basically doing what you are trying to avoid, which is computing the same value twice. Scala is nice, but it's no Haskell;) Jesper's solution is what I was suggesting.