我正在尝试计算前20个素数,它们之间有2个数字差距-例如G3和5。
divides :: Integer -> Integer -> Bool
divides x y = y `mod` x == 0
prime :: Integer -> Bool
prime n = n > 1 && and [not(divides x n) | x <- [2..(n-1)]]
allprimes :: [Integer]
allprimes = [x | x<- [2..], prime x]
primeTest3 :: Integer -> [Integer]
primeTest3 n = [ if y - x == 2 then y else x | x <- [3..n], y <- [2..n], prime x]
这在一定程度上是有效的,如果为n = 20
,则输出为3, 5, ,5, 5, 5, 5, 7, 7, 7, 7, 7, 9, 7, 7, 7, 7, 9, 9, 9..
,依此类推。这显然是由于if else语句造成的。我怎么才能打印出一个没有重复的数字之间有多少个孪生素数呢?
发布于 2015-11-08 05:07:21
要整理我在评论中写的内容:
areTwoApart (x,y) = y - x == 2
filter areTwoApart (zip allprimes (tail allprimes))
...will给出了素数对的列表,没有重复:
Prelude> take 10 $ filter areTwoApart (zip allprimes (tail allprimes))
[(3,5),(5,7),(11,13),(17,19),(29,31),(41,43),(59,61),(71,73),(101,103),(107,109)]
至于你的最后一个问题“在一个没有重复的数字之间有多少个孪生质数”,我不确定你所说的“之间”是什么意思。但您可能可以使用上面的函数来访问它。
https://stackoverflow.com/questions/33587614
复制相似问题