[英]Out of memory error while calculating sum of multiples of 3 and 5 in Haskell
This is my code:这是我的代码:
import Data.Bits
main = print . sum . takeWhile( < 200000) $ multSum 999
multSum m = 3 : multiples [6..m] where
multiples (p:xs)
| ((p `mod` 3 == 0) || (p `mod` 5 == 0)) = p : multiples([p..m])
| otherwise = p : xs
Error: out of memory (requested 1048576 bytes)错误:内存不足(请求 1048576 字节)
Where am I going wrong?我哪里错了?
multSum
isn't doing what you think it is. multSum
并没有按照您的想法行事。 Try debugging it directly:直接调试试试:
*Main> take 20 $ multSum 999
[3,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6]
multSum
为所有参数返回无限列表[3,6,6,6,6...]
,因此它永远不会超过 200000,因此无法打印您请求的总和。
try尝试
mults35 m = multiples [3..m] .....
............
....| ...... = p : multiples xs
... | otherwise = multiples xs
there will be one more thing for you to add there.还有一件事要添加。 Try this, and you'll see.试试这个,你会看到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.