Bug Detector | Python

Prime Number Check Loop Fix

Explanation and corrected code for fixing the loop range bug in the is_prime function to correctly check for prime numbers. The code now ranges up to the square root of n for accurate prime checks.


Empty image or helper icon

Prompt

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

Answer

Code Inspection:

Bug:

  1. The bug in the code is the loop range in the for loop of the is_prime function.

Explanation:

  1. The loop should range from 2 to the square root of n rounded up to the nearest integer, inclusive. However, the current implementation ranges up to int(n**0.5) + 1, which is incorrect.

Fix:

  1. Update the range of the for loop to range(2, int(n**0.5) + 2) to include the square root of n for the correct prime number check.

Corrected Code:

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 2):
        if n % i == 0:
            return False
    return True

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

Explanation and corrected code for fixing the loop range bug in the is_prime function to correctly check for prime numbers. The code now ranges up to the square root of n for accurate prime checks.