Is_prime Codecademy-provided answer appears to have a mistake (spoiler alert)


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/isprime?action=lesson_resume&link_content_target=interstitial_lesson

The following code is what Codecademy supplied when I gave up and selected “Get code.” I understand it except why is the last number in the range set to x-1, rather than simply x, given that range already excludes the last number? It runs correctly. Is it a mistake?


def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        return True


#2

It really doesn’t matter what the range is. Any more than half the value will not divide in, anyway.

range(2, int(x / 2) + 1)

In point of fact, we can even reduce that to the square root of x.

range(2, int(x ** 0.5) + 1)

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.