1

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?

1
  • Why is f passed as a parameter, while prime is slips in as a global variable? Isn't f=next_prime(f) the only meaningful way of calling this function? Commented Jul 28, 2012 at 12:32

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

http://ideone.com/XO74b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.