How to optimize this prime number check?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 13 2025
0162

To optimize the prime number check, you can implement several improvements to reduce the number of iterations and checks. Here are some strategies:

Optimized Prime Check

  1. Check Up to the Square Root:
    Instead of checking all numbers up to num, check only up to the square root of num. If num is divisible by any number greater than its square root, it must also be divisible by a number smaller than its square root.

  2. Skip Even Numbers:
    After checking for 2, you can skip all even numbers since they cannot be prime (except for 2).

Optimized Code Example

Here’s an optimized version of the prime number check:

import math

def is_prime(num):
    if num <= 1:
        return False
    if num == 2:
        return True  # 2 is the only even prime number
    if num % 2 == 0:
        return False  # Exclude all other even numbers

    for i in range(3, int(math.sqrt(num)) + 1, 2):  # Check only odd numbers
        if num % i == 0:
            return False
    return True

# Check for prime numbers in the range
for num in range(2, 10):
    if is_prime(num):
        print(f"{num} is prime")
    else:
        print(f"{num} is not prime")

Explanation of the Optimizations

  1. Square Root Check:

    • The loop runs from 3 to the square root of num, which significantly reduces the number of iterations for larger numbers.
  2. Skip Even Numbers:

    • After checking for 2, the loop increments by 2, checking only odd numbers (3, 5, 7, etc.), which further reduces the number of checks.

Summary

These optimizations make the prime number check more efficient, especially for larger numbers. If you have any further questions or need additional examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!