-4
for x in range (3,21):
    if(x%2==0):
        print (x,'is a not a prime number')
    else:
        print (x,'is a prime number')

This is my code but when it prints it says 9 is a prime number and 15 is a prime number.

Which is wrong because they aren't so how do I fix that?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

0

Your code only checks if a number is even. All odd numbers are not prime. So write a for-loop that checks if a odd number is divisible by any of the odd number less than that. Sometying like:

For i in (3 to n): If n mod i == 0, n is not prime.

nnut
  • 35
  • 7
  • I know the issue is with the if loop, but every other method of finding a prime number ends up messing up the whole list somehow. When I run the program I want it to say '3 is a prime number' '4 is not a prime number' all the way to 20 all at once – Brendo Campos Dec 13 '18 at 03:00
0

.

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

JoshuaCS
  • 2,524
  • 1
  • 13
  • 16
  • thank you! do you mind explaining how this works really quickly? Like why the +1 in the range and what the first part is? Sorry I'm a complete beginner. – Brendo Campos Dec 13 '18 at 03:09
  • @BrendoCampos I edited the answer explaining what that code does. The +1 in the range is just to ensure that 21 is included in the checks, because `range(3, 21)` returns an open interval on the right: **[3, 21)** – JoshuaCS Dec 13 '18 at 03:54