A prime number is an integer greater than one that is only divisible by one and itself.
def check_prime(number):
if number <= 1:
return False
for divisor in range(2, int(number**0.5)+1):
if (number % divisor) == 0:
print(divisor,'*', number//divisor, '=', number)
return False
return True
check_prime(2)
#output: True
check_prime(11)
#output: True
check_prime(35)
#output:
#5 * 7 = 35
#False
check_prime(97)
#output: True
check_prime(273)
#output:
#3 * 91 = 273
#False
check_prime(5003)
#output: True
First, if the number
passed as argument is less than or equal to 1 and return False
for those since they are not prime numbers by definition, prime numbers have two factors, 1 and itself, but 1 only has 1 factor, itself.
Second, we loop through all the numbers from 2 until int(number**0.5)+1
and verify if number
is divisible by any of them, that is, if the remainder of the division is 0, the number is not prime.
If there is no exact divisible number in that range, then the number
is prime.
The range range(2, int(number**0.5)+1)
takes into consideration only up until the square root of the number
.
The range()
function just goes until right before the second number, so to test it until the exact square root I have to add +1
.
The reason to consider only the square root and not all the number up until number
is better explained with an example.
Let’s take 12.
12 is divisible by 1, 2, 3, 4, 6, and 12.
Dividing 12 by 2 we have 6 and, of course, the opposite also works, that is, 12 is divisible by 6 to gives us 2.
Dividing 12 by 4 we have 3, so there is no need to divide by 3 to know it is also divisible by 3.
The point is, you just need to reach the halfway point in the factors to check all the pairs of divisors.
The square root of a number gives you this halfway point because these pairs of divisors are either on one of the sides of the square root or are the same, that is, the exact square root.
If you want to know more about for
loops and if
statements, I recommend the following: