How to optimize this code?

QuestionsQuestions8 SkillsProPython Control StructuresAug, 03 2025
0162

To optimize the prime-checking code, you can implement the following improvements:

  1. Limit the Inner Loop: Instead of checking all numbers up to num, check only up to the square root of num. This reduces the number of iterations significantly.

  2. 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)) + 1 limits the inner loop to only necessary checks.
  • Skip Even Numbers: The code checks if num is 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!

0 Comments

no data
Be the first to share your comment!