- Naive method
- sqrt(n) prime testing (the efficient method)
The Naive method
One method would be to check all possibilities from 2 to n - 1, n being the number we are testing. This would mean that if a number is prime we will have to search through all the numbers from 2 to n - 1. But if a number is not a prime then we will not have to search through all the possibilities, we will just return false if a number is completely divisible by another number that means it doesn't leave any remainder.
def isPrime(n):
    for i in range(2,n):
        if n%i==0:
            return False
    return True
Sqrt(n) method
Okay, so the logic behind this method is that every composite number has at least one factor that lies between 0 and the square root of n. Thus, we only check if it has a factor and if it does indeed have a factor, it's not a prime.
import math
def isPrime(n):
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    m = int(math.sqrt(n))
    for i in range(3,m,2):
        if n % i == 0:
            return False
    return True
Comments
Post a Comment