当前位置:  开发笔记 > 编程语言 > 正文

Python中的简单Prime生成器

如何解决《Python中的简单Prime生成器》经验,为你挑选了5个好方法。

请问有人请告诉我这段代码我做错了什么?无论如何,它只是打印'计数'.我只想要一个非常简单的素数发生器(没什么特别的).

import math

def main():
    count = 3
    one = 1
    while one == 1:
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                continue
            if count % x != 0:
                print count

        count += 1

Eli Bendersk.. 147

有一些问题:

当它没有除以x时,为什么要打印计数?它并不意味着它是素数,它只意味着这个特定的x不会分裂它

continue 移动到下一个循环迭代 - 但你真的想停止使用它 break

这是你的代码,有一些修复,它只打印出素数:

import math

def main():
    count = 3
    
    while True:
        isprime = True
        
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                isprime = False
                break
        
        if isprime:
            print count
        
        count += 1

对于效率更高的黄金时代,请参阅其他人建议的Erastothenes筛选.这是一个很好的,优化的实现,有很多注释:

# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/

def gen_primes():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}
    
    # The running integer that's checked for primeness
    q = 2
    
    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        
        q += 1

请注意,它返回一个生成器.



1> Eli Bendersk..:

有一些问题:

当它没有除以x时,为什么要打印计数?它并不意味着它是素数,它只意味着这个特定的x不会分裂它

continue 移动到下一个循环迭代 - 但你真的想停止使用它 break

这是你的代码,有一些修复,它只打印出素数:

import math

def main():
    count = 3
    
    while True:
        isprime = True
        
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                isprime = False
                break
        
        if isprime:
            print count
        
        count += 1

对于效率更高的黄金时代,请参阅其他人建议的Erastothenes筛选.这是一个很好的,优化的实现,有很多注释:

# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/

def gen_primes():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}
    
    # The running integer that's checked for primeness
    q = 2
    
    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        
        q += 1

请注意,它返回一个生成器.


这个筛子非常简洁.它从哪里来的?
如果您想查看此代码的来源,请参阅此主题http://code.activestate.com/recipes/117119-sieve-of-eratosthenes/,以及一些更快的改进(在我的测试中为4倍)
@xiao我认为"in"操作平均在时间上是恒定的,在最坏的情况下是线性的

2> aatifh..:
def is_prime(num):
    """Returns True if the number is prime
    else False."""
    if num == 0 or num == 1:
        return False
    for x in range(2, num):
        if num % x == 0:
            return False
    else:
        return True

>> filter(is_prime, range(1, 20))
  [2, 3, 5, 7, 11, 13, 17, 19]

我们将在列表中获得最多20个素数.我本来可以使用Eratosthenes的Sieve,但你说你想要一些非常简单的东西.;)



3> SergioAraujo..:
print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]]


它很简单,但效率不高.在典型的PC上,在范围内工作需要几秒钟(10000)

4> FelixHo..:

重要的是:

import re


def isprime(n):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None

print [x for x in range(100) if isprime(x)]

###########Output#############
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]



5> dansalmo..:
def primes(n): # simple Sieve of Eratosthenes 
   odds = range(3, n+1, 2)
   sieve = set(sum([list(range(q*q, n+1, q+q)) for q in odds],[]))
   return [2] + [p for p in odds if p not in sieve]

>>> primes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

要测试数字是否为质数:

>>> 541 in primes(541)
True
>>> 543 in primes(543)
False

推荐阅读
TXCWB_523
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有