Infinite range in my python prime finder?

可紊 提交于 2020-01-24 06:57:05

问题


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!


回答1:


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.




回答2:


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



回答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.




回答4:


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!")



回答5:


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? ...



来源:https://stackoverflow.com/questions/20446006/infinite-range-in-my-python-prime-finder

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