In this tutorial, we are going to see the different methods to find prime numbers and time required for every method. We are going to use the time module to calculate the execution time.
Method-1
It's a general method to find prime numbers.
- If the number is less than or equal to one, return False.
- If the number is divisible by any number, then the function will return False.
- After the loop, return True.
Example
# importing time module
import time
# checking for prime
def is_prime(n):
if n <= 1:
return False
else:
for i in range(2, n):
# checking for factor
if n % i == 0:
# return False
return False
# returning True
return True
# starting time
start_time = time.time()
primes = 0
for i in range(100000):
if is_prime(i):
primes += 1
print(f'Total primes in the range {primes}')
# ending time
end_time = time.time()
print(f'Execution time: {end_time - start_time}')Output
If you run the above program, you will get the following results.
Total primes in the range 9594 Execution time: 63.1301212310791
Method-2
In this method, we are reducing the number of iteration by cutting them to the square root of n.
Let's see the code.
Example
# importing time module
import time
# importing math module for sqrt function
import math
# checking for prime
def is_prime(n):
if n <= 1:
return False
else:
# iterating loop till square root of n
for i in range(2, int(math.sqrt(n)) + 1):
# checking for factor
if n % i == 0:
# return False
return False
# returning True
return True
# starting time
start_time = time.time()
primes = 0
for i in range(100000):
if is_prime(i):
primes += 1
print(f'Total primes in the range {primes}')
# ending time
end_time = time.time()
print(f'Execution time: {end_time - start_time}')Output
If you run the above program, you will get the following results.
Total primes in the range 9592 Execution time: 0.2039644718170166
Method-3
In the previous method, we have checked for the even numbers. We all know that even numbers can't be prime except two. So, in this method, we will remove all evens to reduce the time.
Example
# importing time module
import time
# importing math module for sqrt function
import math
# checking for prime
def is_prime(n):
# checking for less than 1
if n <= 1:
return False
# checking for 2
elif n == 2:
return True
elif n > 2 and n % 2 == 0:
return False
else:
# iterating loop till square root of n
for i in range(3, int(math.sqrt(n)) + 1, 2):
# checking for factor
if n % i == 0:
# return False
return False
# returning True
return True
# starting time
start_time = time.time()
primes = 0
for i in range(100000):
if is_prime(i):
primes += 1
print(f'Total primes in the range {primes}')
# ending time
end_time = time.time()
print(f'Execution time: {end_time - start_time}')Output
If you run the above program, you will get the following results.
Total primes in the range 9592 Execution time: 0.10342741012573242
Conclusion
If you any doubts regarding the tutorial, mention them in the comment section.