I programmed this function in haskell of the Towers of Hanoi problem. The function gives the numbers of steps from source stick to destination stick with only one alternative stick.
numStepsHanoi :: Integer -> Integer
numStepsHanoi 0 = 0
numStepsHanoi n = numStepsHanoi (n-1) + numStepsHanoi (n-1) + 1
This function works fine ... until n, the number of discs, gets too high. GHCi does not finish. I know the complexity of this problem and I know it can't run faster.
For example, if I call it with n = 64
, I can wait 20 minutes and get no output (it doesn't complete). Even if n = 20
, it takes approximately 2 seconds.
With another implementation (below), the time is quite reduced.
numStepsHanoi :: Integer -> Integer
numStepsHanoi 0 = 0
numStepsHanoi n = 2 * numStepsHanoi (n-1) - 1
Now, with n = 64
, I get the result instantly. Obviously this has only one recursive call, but does that have such a large effect?
Could this be a problem of GHCi optimization?
x + x
to2 * x
. The reason that the latter is much faster than the former is because you are wrong about the complexity of your first solution (exponential) vs. your second (linear). – user2407038