0

So I'm trying to write a short programme that will find prime numbers, and discard non-prime numbers. This was my attempt at writing it:

def prime(x):
    while True:
        for y in range(2,x):
            if x%y == 0  :
                x = x + 1

            else:
                print( str(x) + " is a prime number")
                x = x + 1
            return x
            prime(x)
try:
    x = 3
    while True:
        x = prime(x)
except:
    print("NO MORe")

Instead of giving prime numbers this programme just gives all odd numbers, and im fairly sure its to do with the line:

for y in range(2,x):

But I'm not sure how to fix it, any pointers?

  • 5
    I'm not 100% sure what you're trying to do, but are you aware that the `return` statement causes a function to immediately terminate? That `prime(x)` call just after `return x` will never run, and your `while True` loop will never go past the first iteration, and `y` will never be larger than 2. – Kevin Feb 02 '16 at 19:58
  • I'm trying to write a function to just spit out every prime number it finds until it is interrupted. I tried removing the `return x` but the same thing happened and it just spat out every odd number it encountered – Findlay Smith Feb 02 '16 at 20:01
  • 1
    don't reinvent a wheel, check http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python and http://stackoverflow.com/questions/19345627/python-prime-numbers-sieve-of-eratosthenes – MaxU Feb 02 '16 at 20:02
  • 1
    if you want a infinite generator of primes number check: http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python – Copperfield Feb 02 '16 at 20:43

2 Answers2

1

Here is a stub for something you can do. Just make a function that classifies if the number is prime. Then do what ever kind of loop you want and check if its prime. If it is then print it.

def isprime(n):
  for m in range(2, int(n**0.5)+1): #only check odd numbers and only go till sqrt of the value (you dont need to check all the way till n)
     if not n%m:
        return False
  return True

for m in range(1, 1000):
    if isprime(m):
       print(m)
Jay
  • 2,558
  • 1
  • 14
  • 22
1

Your algorithm seems chaotic. At first, try it this way:

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True


def primes_up_to(x):
    result = [2]
    for number in range(3, x):
        if is_prime(number):
            result.append(number)
    return result

print(is_prime(4))
print(primes_up_to(23))

which results to:

False
[2, 3, 5, 7, 11, 13, 17, 19]
ferdy
  • 6,127
  • 3
  • 32
  • 41