0

I have written the below code in python to print out prime numbers but its giving output like:

3,5,7,**9**,11,13,**15**,17,19,**21**,23,25............99

below is the code:

def isprime(n):
    if n == 1:
        return False
    for x in range(2, n):
        if n % x == 0:
            return False
        else:
            return True

def primes(n = 1):
    while(True):
        if isprime(n): yield n
        n += 1
for n in primes():
    if n > 100: break
    print(n)
2
  • What is the question? What were you expecting to happen? Commented Mar 11, 2016 at 21:11
  • 1
    @starf: I think it's pretty clear. The list of primes contains numbers that are not primes. Rahul was expecting prime numbers only. Commented Mar 11, 2016 at 21:15

2 Answers 2

4

You are returning True after the number fails to be divisible by one number. You need to return true after you have checked all the numbers. Instead, you should write

def isprime(n):
    if n == 1:
        return False
    for x in range(2, n):
        if n % x == 0:
            return False

    return True

One other note: if you are testing for prime numbers, you only need to test up to the square root of the number. If the number is not divisible by any numbers less than its square root, then it is also is not divisible by any that are greater and thus must be prime. This will help make your code more efficient.

Sign up to request clarification or add additional context in comments.

3 Comments

Also, it's worthwhile to treat n == 2 as a special case and then only test for odd factors in the loop.
Indeed. Also, something like a Sieve of Eratosthenes would best for finding all primes below a given value.
Definitely! Or this for primes in a given range. For a comparison of various prime sieving algorithms in Python, see Fastest way to list all primes below N. And for testing individual large numbers for primality there's Miller-Rabin... but that might be a getting a bit too advanced for the OP. :)
1

Your isprime function says:

for x in range(2, n):
    if n % x == 0:
        return False
    else:
        return True

This means that on the first iteration (when x==2), if n%x is not zero, it will return True. So it will return True for any odd number (above 1, which you skipped).

Instead, you want to return True if none of the numbers in the loop were factors.

for x in range(2, n):
    if n % x == 0:
        return False
# the loop finished without returning false, so none of the numbers was a factor
return True

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.