I can't seem to make random prime numbers using this code, please can someone help me?
def RandomPrime():
prime = False
while prime == False:
n = random.randint(10000, 100000)
if n % 2 != 0:
for x in range(3, int(n**0.5), 2):
if n % x ==0:
prime = False
else:
prime = True
return n
Correct logic, you are setting
True
whenn % x
! =0
for first time:should be:
Read break and continue Statements, and else Clauses on Loops.
The shorter way of writing equivalent code will be (from @Steve Jesso):
There're errors in your code:
The possible solution is
Imagine what happens if the last number in
range(3, int(n**0.5), 2)
is not an integer divisor ofn
:So even if all previous checks evaluated
False
, you calln
a prime. The minimal change to your code to fix this is:So if
prime
is alreadyFalse
, it remainsFalse
.However, bear in mind that, for primality, if any of those checks is
False
n
is not prime. You can use this and Python'sand
andall
(which are evaluated lazily, i.e. don't keep checking once finding aFalse
) to implement much more efficiently:For even better performance, note that
randrange
incorporates astep
argument, just likerange
, so you can skip all of the even numbers (which definitely aren't prime!):Note:
sqrt(n)
(frommath
) is, in my opinion, a little clearer to other, less-technical readers thann ** 0.5
(although it may or may not be more efficient).Take a look to the tabs: The else should refer to the whole for loop, not to the iF