Sunday 5 June 2016

Haskell: Compute sum of factorials

Write a function, which computes sum of factorials.

For example,
sumOfFacts 2 = factorial(0) + factorial(1) + factorial(2)
                      = 1 + 1 + 2
                      = 4 

 Sample.hs
factorial :: Integer -> Integer
factorial num
    | (num == 0) = 1
    | (num > 0) = num * factorial (num-1)
    | otherwise = error "Factorail is not defined for -ve numbers"

sumOfFacts :: Integer -> Integer
sumOfFacts num
    | (num == 0) = 1
    | otherwise = (factorial num) + sumOfFacts (num-1)

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> sumOfFacts 0
1
*Main> sumOfFacts 1
2
*Main> sumOfFacts 2
4
*Main> sumOfFacts 3
10
*Main> sumOfFacts 4
34
*Main> sumOfFacts 5
154
*Main> 

One problem with above program is, it is calculating the factorial many times. Following is the enhanced version of above program.


Sample.hs
{-# LANGUAGE BangPatterns #-}

sumOfFacts' :: Integer -> Integer -> Integer -> Integer
sumOfFacts' num !res !counter
    | num == counter = (res * (counter+1))
    | otherwise = res + sumOfFacts' num (res * counter) (counter+1)

sumOfFacts num
    | (num == 0) = 1
    | otherwise = sumOfFacts' num 1 1



Previous                                                 Next                                                 Home

No comments:

Post a Comment