Search code examples
recursionfactorial

How to calculate double factorial (multiply odds) with recursion?[homework]


How should I alter the factorial recursion, to calculate only the odd or only the double elements of the factorial?For example if:

 multiplyOdds(4)

the result should return 1*3*5*7 =105

I know how recursion works, I just need a bit of help which approach I should use.


Solution

  • Your function multiplyOdds(n) needs to multiply the first n odd numbers? Given that the nth odd number is equal to 2 * n - 1, you can easily write a recursive solution like the one below in Haskell:

    multiplyOdds :: Int -> Int
    multiplyOdds n = multiplyOddsTail n 1
    
    multiplyOddsTail :: Int -> Int -> Int
    multiplyOddsTail n acc = case n of
      1 -> acc
      n -> multiplyOddsTail (n - 1) (acc * (n * 2 - 1))