You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中正确使用length函数统计指定区间内的素数数量

现有代码问题与修正方案

  1. 首先countPrimesUntil的辅助函数定义语法错误,你使用了while关键字,Haskell中绑定局部函数需要用where。
  2. 你的countPrimes逻辑冗余错误:countPrimesUntil已经能直接返回指定区间的素数列表,统计数量直接对返回结果调用length即可,不需要额外写列表推导遍历判断。

修正后完整代码

import Data.List

countPrimesUntil :: Integral a => a -> a -> [a]
countPrimesUntil a b = takeWhile (<= b) $ dropWhile (< a) $ sieve [2..]
    where sieve (n:ns) = n : sieve [m | m <- ns, m `mod` n /= 0]

-- 统计2到n区间内的素数总数
countPrimes :: Integral a => a -> Int
countPrimes n = length $ countPrimesUntil 2 n

-- 可选:统计任意[a,b]区间内的素数总数
countPrimesBetween :: Integral a => a -> a -> Int
countPrimesBetween a b = length $ countPrimesUntil a b

测试效果

  • 执行countPrimesUntil 2 10 输出 [2,3,5,7],和原有功能一致
  • 执行countPrimes 10 输出 4,符合你需要的总数统计需求
  • 执行countPrimesBetween 3 10 输出 3,对应区间[3,10]内的3、5、7三个素数

内容的提问来源于stack exchange,提问作者Jeff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:54:04