python / python/cpython

Add math.integer.isprime() and math.integer.primes()

未關閉
#153,222 8 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

extension-modules type-feature
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Feature or enhancement

Add prime-number functions to the math.integer module:

  • isprime(n, /) -- return True if n is a prime number, False
    otherwise.
  • primes(start=2, stop=None) -- return an iterator of the prime
    numbers p with start <= p < stop, in increasing order. If stop
    is None (the default), the iteration does not stop.

The arguments must be less than 2**64; larger values raise
OverflowError.

>>> import math.integer
>>> math.integer.isprime(2**61 - 1)
True
>>> math.integer.isprime(561)
False
>>> list(math.integer.primes(stop=30))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
>>> from itertools import islice
>>> list(islice(math.integer.primes(10**18), 3))
[1000000000000000003, 1000000000000000009, 1000000000000000031]

isprime() uses the deterministic Miller-Rabin test ({2, 7, 61} below
4759123141, Jim Sinclair's seven bases up to 2**64, verified against
the Feitsma-Galway exhaustive list of base-2 strong pseudoprimes), so
the result is always exact. The implementation is small and
self-contained: modular arithmetic on C uint64_t, about a microsecond
for the hardest inputs. primes() tests each candidate with the same
code, so it works for unbounded iteration and for ranges with an
arbitrary large start, with O(1) memory.

Primality testing is one of the most commonly reimplemented number
routines, and hand-written versions are often subtly wrong (trial
division stopping too early, Miller-Rabin with an insufficient base
set) or quadratically slow. PEP 791 explicitly deferred primality
testing out of the initial scope of the module; this proposes it as the
first extension.

Support for larger integers (e.g. a Baillie-PSW implementation in
_pylong.py, following the precedent of other huge-int algorithms
there) can be added later: raising OverflowError now makes that a
backward compatible extension.

Previously discussed in gh-57812 (closed in 2011 with a suggestion to
publish on PyPI; predates the math.integer module).

Linked PRs
  • gh-153224

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

首先查看 math.integer 模組進入點和連結的 PR gh-153224,因為該 issue 提供了提議的 API、界限、範例和演算法需求。完成意味著實作並測試 isprime() 和 primes(),使其對於文件所述的輸入、限制和迭代器語意具有完全一致的行為。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
c, python
領域
backend
Issue 類型
功能
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。