Your function crashed on 0 as input because your function throws a "empty range for randrange() (2,0, -2)" error.

Hello. I'm a total newbie when it comes to coding, (i started learning my first language, Python, just a couple of weeks ago). And can't figure out a solution to this problem... i would really appreciate some insights :slight_smile: Thank you

What i'm trying to do is:

import random

def is_prime(x):
    n=random.randint(2, x-1)
    if x%n==0:
        return False
    elif x%n!=0:
        return True

print is_prime(3)


This is not a problem that involves random numbers. First off, what is a Prime number?

1. greater than 1
2. integer
3. indivisible by any number except 1 and itself
4. odd parity (except for 2)

We won't need to concern ourselves with the last point as this exercise is about using brute force (throw everything at it) to test an input.

This line is right, except it needs to be in a loop:

The one that follows is not.

Our program needs to test the input only for value (we will assume inputs to be integer)...

if x < 2: return False

Now set up a loop,

for n in range(2, x):
    # divisibility check from above

and finally,

return True

on the last line, not inside the loop. When x is 2, the loop does not run and the flow drops to the last line, returning True. Any values that survive the loop will also drop to that line, indicating they too are prime.


Thank you mtf, but my thought process was that randint(2, x-1) would limite the numbers processed between 2 and X-1 (X being a random number), would you mind explaining why it doesn't work that way or the flaw in my thought process? Appreciate it.


We only use random numbers when we don't want predictibility, which is quite different from iterating a range of numbers. There is nothing random about that. Iterating a range gives us each number in the range only once. Random numbers can repeat. That is why they are not suitable for this problem.

Take the number 19, for example

range(2, 19) == [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

None of those numbers will divide evenly into 19, so the loop above will complete with no return, and drop down to,

return True


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