P41 - 哥德巴赫猜想列表
Get Goldbach pairs in a given range
官方模块:
Problems.P41核心函数:goldbachList
题目描述
给定闭区间,依次对其中所有大于 2 的偶数调用 P40,返回对应的哥德巴赫分解。
函数签名
1goldbachList :: Integral a => a -> a -> [(a, a)]
实现
方法一:列表推导
1goldbachList :: Integral a => a -> a -> [(a, a)]
2goldbachList lo hi = map goldbach [start, start + 2 .. hi]
3 where
4 first = max 4 lo
5 start = if even first then first else first + 1
先把下界调整到区间中的第一个合法偶数,随后步长固定为 2。
方法二:显式过滤
1goldbachList :: Integral a => a -> a -> [(a, a)]
2goldbachList lo hi = [goldbach n | n <- [lo..hi], n > 2, even n]
不做提前调整,直接用 even n 过滤。代码更直观但多遍历了一半的数。
扩展:附原始数值的版本
1goldbachList :: Integral a => a -> a -> [(a, (a, a))]
2goldbachList lo hi = [(n, goldbach n) | n <- [lo..hi], n > 2, even n]
如果你需要在结果中包含原始偶数,可以用元组 (n, (p, q))。
方法对比
| 方法 | 特点 |
|---|---|
| 步长 2 枚举 | 无过滤,最直接 |
| 全范围 + even 过滤 | 代码最直观 |
| 附带原始值 | 适合需要回查的场景 |
测试
1>>> goldbachList 9 20
2[(3,7),(5,7),(3,11),(3,13),(5,13),(3,17)]
3>>> goldbachList 20 9
4[]