Infinite Range In My Python Prime Finder?
Solution 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.
Solution 2:
You can just use a while loop
num = 1whileTrue:
option = raw_input("continue(y/n)")
if option != "y": breakifall(num%i!=0for i inrange(2,int(math.sqrt(num))+1)):
print num
num += 1
Solution 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.
defgen_primes():
D = {}
q = 2whileTrue:
if q notin D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1if __name__ == "__main__":
prime_generator = gen_primes()
whileTrue:
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 BenderskyDavid Eppstein of UC Irvine.
Solution 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.
defgen_next_prime():
n = 0whileTrue:
n += 1if (check_prime(n)):
yield n
defcheck_prime(n):
if n <= 3:
return n > 1elif n%2 == 0or n%3 == 0:
returnFalse
i = 5while i*i <= n:
if n%i == 0or n%(i+2) == 0:
returnFalse
i = i+6returnTrue
g = gen_next_prime()
whileTrue:
key_input = input("press 'y' to get next prime ('n' to exit): ")
if key_input == "y":
print(next(g))
elif key_input == "n":
breakelse:
print("Error! Invalid Input!")
Solution 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? ...
Post a Comment for "Infinite Range In My Python Prime Finder?"