A prime is a number that can only be divided by one and itself. So, if we test x
, we should test every number y
such that 1 < y < x
. A good way to test this is to use a for loop. Here is an example:
def isPrime(n):
for i in range(2,n):
if n % i == 0:
return False # because that means that something divides into n perfectly
return True
There are a few problems with this:
isPrime(1)
returns True
- Any negative number will return
True
- The program gets quite a bit slower as the numbers get bigger. For example, it takes 0.145 seconds to complete
isPrime(1000003)
, but primes take longer to process, because as soon as a factor is found, the entire function stops and returns, whereas for a prime to be found, it has to run through every iteration up to n
.
I'll leave those problems to you for the moment. In the meantime, we need a way to return the smallest factor. This is actually very easily done:
def isPrime(n):
for i in range(2,n):
if n % i == 0:
return i # i at this iteration is equal to the smallest factor
return True
So isPrime(20)
returns 2
, and isPrime(19)
returns True
. Hopefully this satisfies your needs.