2011-10-19 17 views
1

我是Haskell的初學者,我在Project Euler Problem 10遇到問題。下面是我有:Haskell項目歐拉數10,找不到Bug

primes :: Integral a => [a] 
primes = filter isPrime [1,3..] 

isPrime :: Integral a => a -> Bool 
isPrime 1 = False 
isPrime n = not $ any isDivisibleBy [2..maxTry] 
    where isDivisibleBy x = n `mod` x == 0 
      maxTry = floor $ sqrt $ fromIntegral n 

solution :: Integral a => a 
solution = sum $ takeWhile (<2000000) primes 

main = putStrLn $ show solution 

當我跑,我得到142913828920.項目歐拉說,這是不正確。這讓我感到莫名其妙,因爲我在問題7中成功使用了primesisPrime的相同定義,即找到10001個素數。幫幫我?

回答

5

我會質疑行

primes = filter isPrime [1,3..] 

,因爲2是一個素數。

+2

而且1不是質數,除非你是[世界上最精英的黑客](http://www.imdb.com/title/tt0298814/goofs) – hugomg

+0

我希望isPrime會過濾掉1。 2明確排除我無法理解。我很確定這是問題... –

+0

哦,我錯過了明確的檢查。我想知道他是如何正確獲得10001素數的。 – hugomg