Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python - I want to check if a number is prime or not,but the code below is not working,when i input 65 it shows,this is a prime number

def prime (num) :
    if num == 1 or num == 0 or num == 2:
        return 'This is not a prime number'
    for number in range(2,num):
        if num % number == 0 :
            return 'This is not a prime number'
        else:
            return 'This is a prime number'

This is the code and this is not working result for 65 is prime, why?

question from:https://stackoverflow.com/questions/65942583/i-want-to-check-if-a-number-is-prime-or-not-but-the-code-below-is-not-working-wh

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is you are iterating from 2 till that number. So it goes into the loop, number is 2, and 65 % 2 != 0. Hence It returns 'This is a prime number'. Instead try this:

def prime(num):
    if num == 1 or num == 0:
        return 'This is not a prime number'
    for number in range(2, num):
        if num % number == 0 :
            return 'This is not a prime number'
    return 'This is a prime number'

What this does is it keeps looping until remainder is 0. If the remainder is never 0, it returns 'This is a prime number'.

P.S. 2 is a prime number.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...