Haskell中的项目euler问题3 [英] Project euler problem 3 in haskell
问题描述
我是Haskell的新手,尝试从 http://projecteuler.net/ 解决3个问题。
13195的主要因素是5,7,13和29.
什么是最大的素数数字的因子是600851475143?
我的解决方案:
import Data.List
getD :: Int - > Int
getD x =
- 找到deviders
let deriveList = filter(\y - >(x`mod` y)== 0)[1 .. x]
filteredList =过滤器isSimpleNumber派生列表
中的最大过滤列表
- 支票是简单的
isSimpleNumber :: Int - > Bool
isSimpleNumber x = let deriveList = map(\y->(x`mod` y))[1..x]
filterLength = length(filter(\ z - > z == 0)deriveList)
in
case
2的filterLength - > True
_ - >假
我尝试运行例如:
getD 13195
> 29
但是当我尝试时:
getD 600851475143
我得到错误Exception:Prelude.maximum:empty list为什么?
谢谢@Barry Brown,我认为我必须使用:
getD :: Integer - >整数
但是我得到错误:
无法匹配实际类型为'Integer'的预期类型'Int'
期望类型:[Int]
实际类型:[Integer]
在filter'的第二个参数,即`deriveList'
在表达式中:filter isSimpleNumber deriveList
Thank you。
您的类型签名将整数值限制为大约2 ^ 29。尝试将> Int
更改为整数
。
编辑:
我看到你已经意识到你需要使用Integer而不是Int。你需要改变getD和isSimpleNumber的类型,否则你会得到一个类型不匹配。
另外一般情况下,如果您遇到类型问题,只需删除类型声明并让Haskell告诉你正确的类型。
Main> :t getD
getD :: Integral a => a - > a
Main> :t isSimpleNumber
isSimpleNumber :: Integral a => a - > Bool
I'm new in Haskell and try to solve 3 problem from http://projecteuler.net/.
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My solution:
import Data.List
getD :: Int -> Int
getD x =
-- find deviders
let deriveList = filter (\y -> (x `mod` y) == 0) [1 .. x]
filteredList = filter isSimpleNumber deriveList
in maximum filteredList
-- Check is nmber simple
isSimpleNumber :: Int -> Bool
isSimpleNumber x = let deriveList = map (\y -> (x `mod` y)) [1 .. x]
filterLength = length ( filter (\z -> z == 0) deriveList)
in
case filterLength of
2 -> True
_ -> False
I try to run for example:
getD 13195
> 29
But when i try:
getD 600851475143
I get error Exception: Prelude.maximum: empty list Why?
Thank you @Barry Brown, I think i must use:
getD :: Integer -> Integer
But i get error:
Couldn't match expected type `Int' with actual type `Integer'
Expected type: [Int]
Actual type: [Integer]
In the second argument of `filter', namely `deriveList'
In the expression: filter isSimpleNumber deriveList
Thank you.
Your type signature limits the integer values to about 2^29. Try changing Int
to Integer
.
Edit:
I see that you already realised that you need to use Integer instead of Int. You need to change the types of both getD and isSimpleNumber otherwise you will get a type mismatch.
Also in general, if you are having trouble with types, simply remove the type declarations and let Haskell tell you the correct types.
Main> :t getD
getD :: Integral a => a -> a
Main> :t isSimpleNumber
isSimpleNumber :: Integral a => a -> Bool
这篇关于Haskell中的项目euler问题3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!