.
def isPrime(N):
i = 2
while i**2 <= N:
if N % i == 0:
return False
i+=1
return True
for i in range(3, 21 + 1):
if isPrime(i):
print(i, 'is prime')
else:
print(i, 'is not a prime number')
First of all, create a function for determining whether or not a given number is prime (this is not a requirement but just a good practice). That function is not that hard: it just starts at i = 2
(starting at 1 makes no sense because every number can be divided by it) and check if N can be divided by it. If that is the case, we have found a divisor of N and thus, it isnt prime. Otherwise, continue with the next number: i += 1
. The most tricky part of the loop is the stoping condition: i**2 <= N
: we dont have to look further, because if some j > i
is a divisor of N, then there is some other k < i
that is also a divisor of N: k * j == N
. If such k exists, we will find it before getting to the point where i * i == N
. Thats all. After that, just iterate over each number you want to check for primality.
Btw, the best way to check for the primality of a set of number is using the Sieve of Eratosthenes
2
solved listing prime numbers from 3 to 21 in python 3