Find sum of first 1000 prime numbers in python
Question: 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.


Answer: 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))
    

