To optimize the prime-checking code, you can implement the following improvements:
-
Limit the Inner Loop: Instead of checking all numbers up to
num, check only up to the square root ofnum. This reduces the number of iterations significantly. -
Skip Even Numbers: After checking for 2, you can skip all even numbers, as they cannot be prime (except for 2).
Here’s the optimized version of the code:
import math
for num in range(2, 10):
if num == 2:
print(f"{num} is prime")
continue
if num % 2 == 0:
print(f"{num} is not prime")
continue
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
print(f"{num} is not prime")
break
else:
print(f"{num} is prime")
Key Changes:
- Square Root Check:
int(math.sqrt(num)) + 1limits the inner loop to only necessary checks. - Skip Even Numbers: The code checks if
numis even right after handling 2, reducing unnecessary checks.
This optimization improves performance, especially for larger ranges. For further exploration, consider practicing with prime number algorithms in LabEx!
