Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Trying to find the prime numbers using Python

Below is my code to find the prime number using Python which is not working. Here the function prime will take an integer as input and return whether its a prime number or not. Could you please sort out the problem and explain it.

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

I think i have sorted out the first issue, the first "if" statement should be if x == 0 or x == 1. Now what about the rest.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

What does your for loop?

if x % n == 0:
    return False
else:
    return True

which by the way eqals return bool(x % n)

So, you return in first iteration, when n == 2.

The whole for loop equals return bool(x % 2), which simply checks if x is diviseable by 2.
That's not what you want.

So, what do you want?

You want to check if x is not diviseable by any numer from range(2, x).

You know that x is not prime, if you find one n from range(2, x), for which x % n == 0 is True.
You know that x is prime, when there is no n in range(2, x), for which x % n == 0 is True.

When can you say that none of n from range is a divisor of x?
After checking all ns from range!

After is the key here.
After the loop, in which you try to find divisor, you can only tell that x is prime.

I hope you now understand the code others posted without explanation.


Note: alternative syntax

Code others posted is correct. However, in Python there is second way writing the for, using for .. else:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...