简体   繁体   中英

python: checking if a number is prime, specifying range

I have a problem with a this piece of code that I'm writing to check if a number is prime.

import sys
import math 

def is_prime(num):
    for j in range(2,(int(math.sqrt(num)+1))):
        if (num % j) == 0:
            return False
        else:
            return True

for a in range(1,10):
    if is_prime(a):
        print a

What I get is: 5, 7, 9

I don't understand why is 3 excluded? I went back to the first portion of the code and tried is_prime(3) , but it returned me neither True nor False. Does this mean that 3 is outside the range of divisors I'm checking? How should I correct the code such that 3 is included in my list of primes?

Edit: Hello again, thanks for the answers so far, so I've tried to solve the problem of truncation using int(round()). I've also tried putting the else block outside the loop, but it doesn't seem to work. Can anyone please explain why this is insufficient and suggest how I should correct it so it works? Thanks in advance! :)

import sys
import math 

def is_prime(num):
    for j in range(2,int(round(math.sqrt(num)+1)):
        if (num % j) == 0:
            return False
    return True

Your function returns True as soon as it sees that the number is not divisible by any j . It should only return True if the number is not divisible by all j .

As a side-effect of fixing this bug, you'll also fix the bug whereby your function sometimes returns None (for example, when num is 3 ).

int() truncates, not rounds, so int(math.sqrt(3) + 1) == 2 . range(2, 2) is empty, so nothing will be returned.

Another problem is that your else block is inside of the loop. If you test the first 100 numbers, you will quickly notice that your is_prime function will return True for any odd number.

3的平方根小于2,因此永远不会进入循环并且什么也不返回。

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