将轮分解添加到不定筛

2024-04-08

我正在修改埃拉托色尼的不定筛here https://stackoverflow.com/a/10733621因此,它使用轮分解来跳过比当前仅检查所有赔率的形式更多的组合。

我已经弄清楚了如何生成到达轮子上所有间隙所需的步骤。从那里我想我可以用 +2 代替这些轮子步骤,但它会导致筛子跳过素数。这是代码:

from itertools import count, cycle

def dvprm(end):
    "finds primes by trial division. returns a list"
    primes=[2]
    for i in range(3, end+1, 2):
        if all(map(lambda x:i%x, primes)):
            primes.append(i)
    return primes

def prod(seq, factor=1):
    "sequence -> product"
    for i in seq:factor*=i
    return factor

def wheelGaps(primes):
    """returns list of steps to each wheel gap
    that start from the last value in primes"""
    strtPt= primes.pop(-1)#where the wheel starts
    whlCirm= prod(primes)# wheel's circumference

    #spokes are every number that are divisible by primes (composites)
    gaps=[]#locate where the non-spokes are (gaps)
    for i in xrange(strtPt, strtPt+whlCirm+1, 2):
        if not all(map(lambda x:i%x,primes)):continue#spoke 
        else: gaps.append(i)#non-spoke

    #find the steps needed to jump to each gap (beginning from the start of the wheel)
    steps=[]#last step returns to start of wheel
    for i,j in enumerate(gaps):
        if i==0:continue
        steps.append(j - gaps[i-1])
    return steps

def wheel_setup(num):
    "builds initial data for sieve"
    initPrms=dvprm(num)#initial primes from the "roughing" pump
    gaps = wheelGaps(initPrms[:])#get the gaps
    c= initPrms.pop(-1)#prime that starts the wheel

    return initPrms, gaps, c

def wheel_psieve(lvl=0, initData=None):
    '''postponed prime generator with wheels
    Refs:  http://stackoverflow.com/a/10733621
           http://stackoverflow.com/a/19391111'''

    whlSize=11#wheel size, 1 higher prime than
    # 5 gives 2- 3 wheel      11 gives 2- 7 wheel 
    # 7 gives 2- 5 wheel      13 gives 2-11 wheel
    #set to 0 for no wheel

    if lvl:#no need to rebuild the gaps, just pass them down the levels
        initPrms, gaps, c = initData
    else:#but if its the top level then build the gaps
        if whlSize>4:
            initPrms, gaps, c = wheel_setup(whlSize) 
        else:
            initPrms, gaps, c= dvprm(7), [2], 9

    #toss out the initial primes
    for p in initPrms:
        yield p

    cgaps=cycle(gaps)
    compost = {}#found composites to skip

    ps=wheel_psieve(lvl+1, (initPrms, gaps, c))

    p=next(ps)#advance lower level to appropriate square
    while p*p < c:
        p=next(ps)
    psq=p*p

    while True:
        step1 = next(cgaps)#step to next value

        step2=compost.pop(c, 0)#step to next multiple

        if not step2:

            #see references for details
            if c < psq:
                yield c
                c += step1
                continue

            else:
                step2=2*p
                p=next(ps)
                psq=p*p

        d = c + step2
        while d in compost:
            d+= step2
        compost[d]= step2

        c += step1

我用这个来检查它:

def test(num=100):
    found=[]
    for i,p in enumerate(wheel_psieve(), 1):
        if i>num:break
        found.append(p)

    print sum(found)
    return found

当我将轮大小设置为 0 时,我得到前 100 个素数的正确总和 24133,但是当我使用任何其他轮大小时,我最终会得到素数丢失、总和和合成错误。即使是 2-3 轮(使用 2 和 4 的交替步骤)也会使筛子错过素数。我究竟做错了什么?


赔率,即 2-互质数,由下式生成“滚轮子” [2],即从初始值 3 开始(类似地从 5、7、9、...)开始重复添加 2,

n=3; n+=2; n+=2; n+=2; ...           # wheel = [2]
  3     5     7     9

2-3-互质是通过重复添加 2、然后 4、再添加 2、然后 4 等生成的:

n=5; n+=2; n+=4; n+=2; n+=4; ...     # wheel = [2,4]
  5     7    11    13    17

这里我们确实需要知道从哪里开始添加 2 或 4 的差异,具体取决于初始值。对于 5、11、17...,它是 2(即轮盘的第 0 个元素);对于 7、13、19...,它是 4(即第 1 个元素)。

我们怎样才能知道从哪里开始呢?轮优化的要点是我们只处理这个互质序列(在本例中为 2-3-互质)。因此,在获得递归生成素数的代码部分中,我们还将维护滚轮流,并推进它,直到看到其中的下一个素数。轧制顺序需要产生two结果 - 值和车轮位置。因此,当我们看到质数时,我们也得到了相应的轮子位置,并且我们可以从轮子上的该位置开始生成其倍数。我们将所有内容乘以p当然,要从p*p:

for (i, p) # the (wheel position, summated value) 
           in enumerated roll of the wheel:
  when p is the next prime:
    multiples of p are m =  p*p;       # map (p*) (roll wheel-at-i from p)
                       m += p*wheel[i]; 
                       m += p*wheel[i+1];    ...

因此,字典中的每个条目都必须保持其当前值、其基素数和当前轮位置(在需要时,环绕到 0 以实现循环)。

为了产生结果素数,我们滚动另一个互素序列,并只保留其中不在字典中的元素,就像参考代码中一样。


update:经过几次迭代进行代码审查 https://codereview.stackexchange.com/q/92365/9064(非常感谢那里的贡献者!)为了提高速度,我尽可能多地使用 itertools 得到了这段代码:

from itertools import accumulate, chain, cycle, count
def wsieve():  # wheel-sieve, by Will Ness.    ideone.com/mqO25A

    wh11 = [ 2,4,2,4,6,2,6,4,2,4,6, 6,2,6,4,2,6,4,6,8,4,2, 4,
             2,4,8,6,4,6,2,4,6,2,6, 6,4,2,4,6,2,6,4,2,4,2, 10,2,10]
    cs = accumulate(chain([11], cycle(wh11)))    # roll the wheel from 11
    yield(next(cs))       # cf. ideone.com/WFv4f,
    ps = wsieve()         # codereview.stackexchange.com/q/92365/9064
    p = next(ps)          # 11
    psq = p**2            # 121
    D = dict(zip(accumulate(chain([0], wh11)), count(0)))  # wheel roll lookup dict
    mults = {}
    for c in cs:          # candidates, coprime with 210, from 11
        if c in mults:
            wheel = mults.pop(c)
        elif c < psq:
            yield c
            continue
        else:    # c==psq:  map (p*) (roll wh from p) = roll (wh*p) from (p*p)
            i = D[(p-11) % 210]                 # look up wheel roll starting point
            wheel = accumulate( chain( [psq], 
                             cycle( [p*d for d in wh11[i:] + wh11[:i]])))
            next(wheel)
            p = next(ps)
            psq = p**2
        for m in wheel:   # pop, save in m, and advance
            if m not in mults:
                break
        mults[m] = wheel  # mults[143] = wheel@187

def primes():
    yield from (2, 3, 5, 7)
    yield from wsieve()

与上面的描述不同,这段代码直接计算每个素数从哪里开始滚动,以生成它的倍数

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将轮分解添加到不定筛 的相关文章

  • 为什么Python有最大递归深度?

    Python有最大递归深度 但没有最大迭代深度 为什么递归受到限制 把递归当成迭代来对待 而不限制递归调用的次数不是更自然吗 我只想说这个问题的根源来自于尝试实现流 参见这个问题 https stackoverflow com questi
  • ValueError:“连接”层需要具有匹配形状的输入(连接轴除外)

    我正在尝试为我的项目构建 Pix2Pix 并收到错误 值错误 Concatenate层需要具有匹配形状的输入 除了连接轴之外 获得输入形状 None 64 64 128 None 63 63 128 生成器是一个 U 网模型 我的输入高度
  • Celery计划任务中的打印语句不会出现在终端中

    当我跑步时celery A tasks2 celery worker B我想看到每秒打印 芹菜任务 目前没有打印任何内容 为什么这不起作用 from app import app from celery import Celery from
  • 带有指针数组的 cython

    我在 python 中有一个 numpy ndarrays 列表 具有不同的长度 并且需要非常快速地访问 python 中的列表 我认为指针数组就可以解决问题 我试过 float type t list of arrays no of ar
  • 无法在 mysql 表中的值中使用破折号(-)[重复]

    这个问题在这里已经有答案了 我一直在尝试从 python 将数据插入 MYSQL 表 我的sql表中的字段是id token start time end time和no of trans 我想存储使用生成的令牌uuid4在令牌栏中 但由于
  • Python 小数.InvalidOperation 错误

    当我运行这样的东西时 我总是收到此错误 from decimal import getcontext prec 30 b 2 3 Decimal b Error Traceback most recent call last File Te
  • 创建圆形图像 PIL Tkinter

    Currently I have a zoom feature in my application that works very well however I d like the actual zoom box to be a circ
  • 引发 RuntimeError(f"目录 '{directory}' 不存在") RuntimeError: 导入 fitz 时目录 'static/' 不存在

    当我运行 extract img py 文件时出现此错误 RuntimeError f 目录 directory 不存在 运行时错误 导入 fitz 时不存在目录 static 我不明白为什么这会给我发回此错误消息 我之前看到过关于这个话题
  • 使用opencv计算深度视差图

    我无法使用 opencv 从视差图计算深度 我知道两个立体图像中的距离是用以下公式计算的z baseline focal disparity p 但我不知道如何使用地图计算视差 我使用的代码如下 为我提供了两个图像的视差图 import n
  • 使用 Python 的文本中的词频但忽略停用词

    这给了我文本中单词的频率 fullWords re findall r w allText d defaultdict int for word in fullWords d word 1 finalFreq sorted d iterit
  • 理解@property装饰器和继承[重复]

    这个问题在这里已经有答案了 这里是 Python 3 以防万一它很重要 我试图正确理解如何实现继承 property使用 我已经搜索了 StackOverflow 并阅读了大约 20 个类似的问题 但无济于事 因为他们试图解决的问题略有不同
  • Selenium:等到 WebElement 中的文本发生变化

    我在用着selenium使用Python 2 7 从网页上的搜索框检索内容 搜索框动态检索结果并在框本身中显示结果 from selenium import webdriver from selenium webdriver common
  • 如何使用 msgpack 进行读写?

    如何序列化 反序列化字典data with msgpack http msgpack org The Python 文档 http msgpack python readthedocs io en latest badge latest似乎
  • 管理文件字段当前 url 不正确

    在 Django 管理中 只要有 FileField 编辑页面上就会有一个 当前 框 其中包含指向当前文件的超链接 但是 此链接会附加到当前页面 url 因此会导致 404 因为不存在这样的页面 例如 http 127 0 0 1 8000
  • 请求response.iter_content()获取不完整的文件(1024MB而不是1.5GB)?

    您好 我一直在使用此代码片段从网站下载文件 到目前为止 小于 1GB 的文件都很好 但我注意到 1 5GB 文件不完整 s is requests session object r s get fileUrl headers headers
  • 向量化 numpy bincount

    我有一个 2d numpy 数组 A我要申请np bincount 到矩阵的每一列A生成另一个二维数组B由原始矩阵每列的 bincounts 组成A 我的问题是 np bincount 是一个采用一维数组的函数 它不是像这样的数组方法B A
  • 从 Python 中编译的正则表达式中提取命名组正则表达式模式

    我有一个 Python 正则表达式 其中包含多个命名组 但是 如果先前的组已匹配 则可能会错过与一组匹配的模式 因为似乎不允许重叠 举个例子 import re myText sgasgAAAaoasgosaegnsBBBausgisego
  • 从 C 线程调用 Python 代码

    我对从 C 或 C 线程调用 Python 代码时如何确保线程安全感到非常困惑 The Python 文档 http docs python org c api init html non python created threads似乎是
  • 测试中的模型 - Django 1.7 问题

    我正在尝试将我的项目移植为使用 Django 1 7 除了一件事之外 一切都很好 测试文件夹内的模型 Django 1 7 新迁移在内部运行 migrate 命令 在运行syncdb之前 这意味着如果模型未包含在迁移中 它将不会填充到数据库
  • 如何使用 Python 将我的 GoPro Hero 4 相机直播连接到 openCV?

    我在尝试从我的新 GoPro Hero 4 相机捕获实时流并使用 openCV 对其进行一些图像处理时遇到麻烦 这是我的试用 创建的窗口上没有显示任何内容 import cv2 import argparse import time imp

随机推荐