Find sum of first 1000 prime numbers in python [duplicate]

别来无恙 提交于 2019-12-14 03:37:59

问题


I have written a program which counts the sum of the primes uptill 1000. The program is as follows:

limit = 1000

def is_prime(n):
    for i in range(2, n):
        if n%i == 0:
            return False
    return True

sum = 0
for i in range(2, int(limit+1)):
    if is_prime(i):
        sum = sum + i
        count += 1
print sum

What changes can I make to find 1000 primes instead of upto 1000 numbers? Also, I am looking for space complexity as O(1) and time complexity as O(n) (As I know other methods can do it :-) such as "Sieve of Eratosthenes" and finding prime while iterating upto sqrt(n) http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/)

Please correct me if I am going wrong some where. Thank you.


回答1:


Just a small improvement based on your code to find limit primes instead of limit numbers.

limit = 1000

def is_prime(n):
    for i in range(2, n):
        if n%i == 0:
            return False
    return True

sum = 0
num = 2
for i in xrange(limit):
    while not is_prime(num):
        num += 1
    sum += num
    num += 1 # sorry, miss this
print sum

And you could also use a single loop when looking for certain amount of things you are interested in, it could be just a matter of taste.

limit = 1000

def is_prime(n):
    for i in range(2, n):
        if n%i == 0:
            return False
    return True

sum = 0
count = 0
num = 2
while count != limit:
    if is_prime(num):
        sum += num
        count += 1
    num += 1

print sum



回答2:


Code:

def f():
    i = 2
    while True:
        if all(i % x != 0 for x in range(2, i-1)):
            yield i
        i += 1

primes = f()
print sum(primes.next() for _ in range(1000))

Or a one liner:

import itertools
print sum(itertools.islice(itertools.ifilter(lambda x: all(x % i != 0 for i in range(2, x)), f()), 0, 1000))



回答3:


I wish to propose the following algorithm (Sieve of Eratosthenes)

n=1000
limit_sieve = 10000
primes = set()
notPrimes = set()
i = 2
while len(primes)<n:
  if not i in notPrimes:
    primes.add(i);
    for notPrime in range(i*2, limit_sieve, i):
      notPrimes.add(notPrime)
  i+=1

sum(primes)



回答4:


The simplest way to do what you've requested is probably with itertools.

def gen_primes():
    for i in itertools.count(2):
        if is_prime(i):
            yield i 

first_one_thousand = list(itertools.islice(gen_primes(), 1000))

Shoot, everyone likes a one-liner:

first_one_thousand = list(itertools.islice((i for i in itertools.count(2) 
                                            if is_prime(i)), 
                                           1000))


来源:https://stackoverflow.com/questions/29617690/find-sum-of-first-1000-prime-numbers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!