I have a code which computes a Motzkin number as:
module Main where
-- Program execution begins here
main :: IO ()
main = interact (unlines . (map show) . map wave . (map read) . words)
-- Compute Motzkin number
wave :: Integer -> Integer
wave 0 = 1
wave 1 = 1
wave n = ((3 * n - 3) * wave (n - 2) + (2 * n + 1) * wave (n - 1)) `div` (n + 2)
But the output for even a simple number as 30 takes a while to return.
Any optimization ideas??
With n=30, you need to compute
wave 29andwave 28, which, in turn, needs to computewave 28,wave 27twice andwave 26and so forth, this quickly goes in the billions.You can employ the same trick that is used in computation of the fibonacci numbers:
This runs in linear time, and the helper has, for every
kthe values forwave (k-2)andwave (k-1)ready.