Reputation: 1713
hey this is a code that works fine. i am using in a bigger code and the program gives quick answer for like 999999 or 9999999.
prime=[2,3,5]
f=7
def next_prime(f): #whenever called, measures the next prime of the list and returns it
j=len(prime)
while j==len(prime):
for x in prime:
if f%x==0:
f+=2
break
else:
prime.append(f)
return f
But if i modify the code a little bit (I want add the condition that x should be less than f**.5), the program gives no results.
prime=[2,3,5]
f=7
main=[]
power=[]
def next_prime(f):
j=len(prime)
while j==len(prime):
for x in prime:
if (x<int(f**.5)+1) and f%x==0:
f+=2
break
else:
prime.append(f)
return f
Where is the mistake?
Upvotes: 1
Views: 109
Reputation: 10447
First of all this code does not work even numbers. You should write your code somthing like.
def next_prime(n):
assert(n>0)
while 1:
n+=1
if isprime(n):
return n
and if you can use any isprime() implementations.
You can write it on your own or use famous miller-rabin algorithm that works fast for any prime as long as you have enough ram to hold computations in it.
Upvotes: 1
Reputation: 2025
Both versions work fine in my python interpreter (2.7). Although both your versions will not return any result for an even number, so you probably should add a check for this condition:
f=7
main=[]
power=[]
prime = [2,3,5]
def next_prime(f):
#Added check:
if not f%2:
f += 1
j=len(prime)
while j==len(prime):
for x in prime:
if (x<int(f**.5)+1) and f%x==0:
f+=2
break
else:
prime.append(f)
return f
Upvotes: 2