6. is_prime


Trying to make sure I understand how range works, and looking for clarification.

In the code for the solution it shows a line as for n in range (2,x-1).

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

I’m wondering how the value for n is found. Say I input an 8. Does this line of the code go through numbers from 8 to 2 in order to see if 8 can be divided evenly for the next line of code?


If x is 8, the loop will terminate when n is 2. The chance that iteration reaches the end of the range is slim, save for when x is Prime.

range(2, x)  =>  [2, 3, 4, 5, 6, 7]

Being as 8 is even, 2 is the only divisor it will be tested against.


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