6. is_prime


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#

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

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

whether i write range 2 to x or 2 to x-1, i still passed the test. why?


#2

Because checking if a number is prime, is basicaly . Dividing n by each prime from 2 to ceiling( square root of n). Reason being both those blocks of code can work :slight_smile:


#3

Hmm I still don't get it. Suppose my input is is_prime(16).
if start,stop is 2, x-1, then 16-1 % 2 = 15 % 2 = 0. then it break, return false because x % n == 0.
if start,stop is 2, x, then 16 % 2 = 1. then it break, return true..?


#4

The SCT for that lesson is not as strict as it needs to be but just imagine you were doing it in a rel world,

More explanation here: http://www.wikihow.com/Check-if-a-Number-Is-Prime


#5

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