简体   繁体   中英

python code giving wrong output

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM