python 8个完数 运算超时?

Python015

python 8个完数 运算超时?,第1张

在你的这个思路中,可以优化的主要就是几方面:

1:求因数可以仅算到n的平方根q为止,对于n,每有一个小于q的因数,就有一个对应的大于q的因数,两者之积为n。

2:在完数函数中已经完成了求因数的工作,不需要另做一次,直接在完数函数中拼装结果即可。

3:目前来说,已知的完全数都是偶数,因此,最后那行那里可以做num+=2优化,但数学上目前还没有证明不存在奇完全数,这种做法从理论上来说是不严谨的。

实际上,当一个数比较大的时候,做因数分解是一个很费时的工作,要找更大的完数,需要更好的因数分解的方式。比如先求出所有的质因数,在使用这些质因数的组合来寻找非质因数。因为质因数必然是在质数表中,而质数表可以建立一次然后重复使用,相对一个个的试商就快得多了。

如果要进一步优化以寻找更大的完全数,那么,就需要利用更多的关于完全数的规律了,比如,除6以外,其它的完全数都是9n+1,都是p^2*q……,这些优化在你这个框架下实现就比较麻烦。

总体来说,不解决因数分解的问题,主要就是上述三种优化了。

碰到这种需求时不要惊慌,可以使用wait()里的timeout参数来设置等待时间,也就是从这个函数开始运行算起,如果时间到达协程没有执行完成,就可以不再等它们了,直接从wait()函数里返回,返回之后就可以判断那些没有执行成功的,可以把这些协程取消掉。例子如下

import asyncio

async def phase(i):

    print('in phase {}'.format(i))

    try:

        await asyncio.sleep(0.1 * i)

    except asyncio.CancelledError:

        print('phase {} canceled'.format(i))

        raise

    else:

        print('done with phase {}'.format(i))

        return 'phase {} result'.format(i)

async def main(num_phases):

    print('starting main')

    phases = [

        phase(i)

        for i in range(num_phases)

    ]

    print('waiting 0.1 for phases to complete')

    completed, pending = await asyncio.wait(phases, timeout=0.1)

    print('{} completed and {} pending'.format(

        len(completed), len(pending),

    ))

    # Cancel remaining tasks so they do not generate errors

    # as we exit without finishing them.

    if pending:

        print('canceling tasks')

        for t in pending:

            t.cancel()

    print('exiting main')

event_loop = asyncio.get_event_loop()

try:

    event_loop.run_until_complete(main(3))

finally:

    event_loop.close()

结果输出如下:

starting main

waiting 0.1 for phases to complete

in phase 0

in phase 2

in phase 1

done with phase 0

1 completed and 2 pending

canceling tasks

exiting main

phase 1 canceled

phase 2 canceled

是为了防止url不可访问,或者响应速度太慢而造成的时间浪费。

比如,你要爬取1000个网站,如果有100个需要30s才能返回数据,你等待他们返回的话就需要3000s了,如果你设置10s超时,那么就能知道最长需要多久1000个可以爬完。

如果解决了您的问题请采纳!

如果未解决请继续追问