# This is a question about a program to determine whether a number is a prime number

Could the following code be used to determine whether a number is prime? I’ve tested it and can’t find any exceptions.

Could the following code be used to determine a prime number?

``````def prime_checker(number):
if number == 1:
print("It's not a prime number.")
if number % 2 == 0 or number % 3 == 0:
print("It's not a prime number.")
else:
print("It's a prime number") `````````
``````>>> prime_checker(2)
It's not a prime number
>>> prime_checker(3)
It's not a prime number
>>> prime_checker(25)
It's a prime number
``````
1 Like

I’m guessing you didn’t try huge numbers like… 25.

1 Like

A good way to check that code is working as intended, is to test it against a known outcome.

Prime numbers, for the most part, are well established and as such you can check your code against a list:

``````def prime_checker(number):
if number == 1:
return False
if number % 2 == 0 or number % 3 == 0:
return False
else:
return True

prime_list = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173
]

for n in range(174):
check = prime_checker(n)
if check and n in prime_list:
print(n, "checks out")
elif check and n not in prime_list:
print(n, "does not check out")
elif not check and n in prime_list:
print(n, "does not check out")
``````

I’ve include the first 40 prime numbers and modified your function so that it returns `True` or `False`.

This is the output for zero to 25:

``````2 does not check out
3 does not check out
5 checks out
7 checks out
11 checks out
13 checks out
17 checks out
19 checks out
23 checks out
25 does not check out
...
``````

As you can see, you’ve not nailed this, but you’re trying, so that’s no bad thing.

1 Like

Actually, I went bigger, like in the 900’s.

Thank you for both taking the time to answer and the encouragement! This was very helpful.

1 Like

Testing for primality is such a popular pastime at rowdy
mathematician parties that it has its own Wikipedia article, and
there are numerous other writeups about different approaches and
optimizations you can find all over the place. You might try picking
one of the simpler popular algorithms and working out how to codify
it, unless the point of the assignment is to find your own prime
number test algorithm.

I was about to link the Wikipedia article, and then realized it
contains an example in Python (a concise 11-line implementation), so
maybe avert your eyes if you read that one. Also be careful not to
accept party invites from mathematicians, no matter how innocent
they may seem!