4

I am trying to get an infinite range in my python prime number finder! here is my code!

import math
print "Welcome to Prime Finder!"
option = raw_input("continue(y/n)")
 if option == "y":
    for num in range(1,(infinite number)):
        if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
           print num

I am trying to get where it says (infinite number) to actually be an infinite number. Is there some value or something that I can use to find that? Any help would be greatly appreciated!

Jan Vorcak
  • 17,297
  • 13
  • 46
  • 85
  • A bazillion gazillion makes the intentions less clear than an infinite endpoint, and if you don't type enough zeros, your code breaks. – user2357112 supports Monica Dec 07 '13 at 20:10
  • because anything over 100000001 returns an overflow error. –  Dec 07 '13 at 20:12
  • also, any idea how to add a little bit of code so that any time, if you press q or something, than it will stop finding and display results. Also a counting system would be nice, like if you press q, it prints," found _ amount of primes. –  Dec 07 '13 at 20:22

5 Answers5

10

You can import itertools and use count function

import itertools
for num in itertools.count(1):
    print num

count(1) --> 1 2 3 4 5 ...

count(10) --> 10 11 12 13 14 ...

count(1, 2) --> 1 3 5 7 9 ...

The first argument is the starting point.

Jan Vorcak
  • 17,297
  • 13
  • 46
  • 85
5

You can just use a while loop

num = 1
while True:
    option = raw_input("continue(y/n)")
    if option != "y": break

    if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
       print num
    num += 1
samrap
  • 5,245
  • 5
  • 29
  • 55
3

This is a modification of @samrap's answer, basically use a generator in conjunction with a while loop. Then generator will ensure that you don't have to recalculate primes for every iteration of the loop.

def gen_primes():
    D = {}  
    q = 2  

    while True:
        if q not in D:
            yield q        
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]

        q += 1

if __name__ == "__main__":

    prime_generator = gen_primes()

    while True:

        option = raw_input("continue(y/n)")
        if option == "y":
            prime = next(prime_generator)
            print prime
        else:
            break

That sieve is not mine, credit goes to Eli Bendersky David Eppstein of UC Irvine.

Community
  • 1
  • 1
John
  • 12,028
  • 4
  • 46
  • 95
  • 2
    actually the post by Eli Bendersky you link to says that this code is due to David Eppstein of UC Irvine, 2002. Also, it can / should be [improved](http://stackoverflow.com/a/10733621/849891). – Will Ness Dec 07 '13 at 22:20
  • 1
    @WillNess, thank you for coming up with the better algorithm. I'll start referring to that question from now on =). – John Dec 07 '13 at 22:30
  • Glad it helps. :) I spent a lot of time on this some time in 2002-2004, reading SICP and tweaking their primes code, and coming up with the idea of postponing the firing up of filters on my own... that was fun. :) (of course I wasn't the only one... and they already had another code in Haskell that achieved the postponement automatically... ) :) – Will Ness Dec 07 '13 at 23:42
0

You will eventually get an overflow. Please check my code, it is a prime number generator. Just change n to the number you want to start generating primes from.

def gen_next_prime():
    n = 0
    while True:
        n += 1
        if (check_prime(n)):
            yield n

def check_prime(n):
    if n <= 3:
        return n > 1
    elif n%2 == 0 or n%3 == 0:
        return False
    i = 5
    while i*i <= n:
        if n%i == 0 or n%(i+2) == 0:
            return False
        i = i+6
    return True

g = gen_next_prime()

while True:
    key_input = input("press 'y' to get next prime ('n' to exit): ")

    if key_input == "y":
        print(next(g))
    elif key_input == "n":
        break
    else:
        print("Error! Invalid Input!")
0

What I mean below is, even if your code has an infinite range, at some point, it will be so slow that it won't seem to be doing anything at all. For me, that some point was around n=1000,000 I think.

As somebody else pointed out above, you can use a while loop and that's easy to do. Note however, that from a practical point of view, your effective range is still going to be limited, even if we ignore the fact that the time for the printing will slow processing down at some point.

I managed to analyse at most, if I recall correctly, the first million numbers, using my version of the sieve. I optimized the code quite a bit. Long story there(less than square root, only checked previous primes, used python lists (I found numpy too slow), skipped even numbers, ...) No matter how smart your code is, the amount of computation required per prime increases significantly over time. I didn't for example use parallel processing but even if I did, I think you'd get stuck fairly soon. If you were getting primes less than N^2, maybe you could sequentially compute all of the primes up to N and use that to spawn some calculations in parallel? ...

georgejo
  • 9
  • 3