[Haskell-beginners] Project Euler #01 on HackerRank, Performance issue‏

Chaddaï Fouché chaddai.fouche at gmail.com
Wed Jan 28 21:04:54 UTC 2015


Well I did it pretty dirty, not trying to simplify my solution (I'm skeptic
of "k * n/k = n" given that this "n / k" is really "floor (n / k)" ... does
this really work for you ?), this gave me :

import Control.Monad (replicateM_)

main = do
    t <- readLn
    replicateM_ t (readLn >>= print . pe1 . subtract 1)

pe1 n = ( (3 + m3 * 3) * m3 + (5 + m5 * 5) * m5 - (15 + m15 * 15) * m15 )
`quot` 2
  where
    m3 = n `quot` 3
    m5 = n `quot` 5
    m15 = n `quot` 15


Note that the sum of multiples of 3/5/15 can be seen as a sum of terms of
an arithmetic sequence which is always "number of terms * (first term +
last term) / 2", easily proven by the expedient of writing the sequence
twice : one in the right order and the other in reverse under it, you then
see that the sum of two term in column is always the same so ...

-- 
Jedaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20150128/9821b0c1/attachment.html>


More information about the Beginners mailing list