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

Jean Lopes hawu.bnu at gmail.com
Tue Jan 27 23:29:22 UTC 2015


Hello everyone! I'm learning Haskell by solving simple exercises on
www.hackerrank.com...


The problem to be solved:
https://www.hackerrank.com/contests/projecteuler/challenges/euler001

as stated in this section: https://www.hackerrank.com/environment
constraints
version: haskell-plataform 2013.2.0.0
time limit: 5 seconds
memory: 512mb

I keep getting "timed out" on some test cases (#2 and #3). Trying to
process 10^5 numbers between 1 to 10^9 *seems* impossible to me (Please,
prove me wrong!)

here is my code:
import Data.Maybe
import qualified Data.ByteString.Char8 as B

nearestMultipleOf :: Integral a => a -> a -> a
nearestMultipleOf n k = if mod n k == 0 then n else nearestMultipleOf (n-1)
k

sumMultiplesOf :: Integral a => a -> a -> a
sumMultiplesOf n k = foldl (+) 0 [k,k*2..nearest]
    where nearest = nearestMultipleOf n k

solution :: Integral a => a -> a
solution n = s03 + s05 - s15
    where s03 = sumMultiplesOf (n-1) 3
          s05 = sumMultiplesOf (n-1) 5
          s15 = sumMultiplesOf (n-1) 15

main = do
    c <- B.getContents
    let ns = tail $ B.lines c
    putStr $ unlines $ map show $ map (solution . fst . fromJust .
B.readInt) ns

as always, any input is really welcome!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20150127/e1fc1107/attachment.html>


More information about the Beginners mailing list