Big prime numbers generation in python

I cannot imagine random primes 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 
+2
source share
4 answers

Imagine what happens if the last number in range(3, int(n**0.5), 2) not an integer divisor of n :

 if n % x ==0: prime = False # not this else: prime = True # this 

So, even if all previous checks are evaluated False , you call n prime. The minimum change for your code to fix is:

 prime = prime and True # or 'prime &= True' 

So, if prime already False , it remains False .

However, keep in mind that for primitiveness, if any of these checks are False n not simple. You can use this with Python and and all (which are evaluated lazily, i.e. Do not check as soon as you find False ) to implement it much more efficiently:

 def rand_prime(): while True: p = randint(10000, 100000) if (r % 2 != 0 and all(p % n != 0 for n in range(3, int(((p ** 0.5) + 1), 2))): return p 

For even better performance, note that randrange contains a step argument, like range , so you can skip all even numbers (which is definitely not easy!):

 def rand_prime(): while True: p = randrange(10001, 100000, 2) if all(p % n != 0 for n in range(3, int((p ** 0.5) + 1), 2)): return p 

Note: sqrt(n) (from math ), in my opinion, is a bit clearer for other, less technical readers than n ** 0.5 (although it may or may not be more efficient ).

+3
source

Correct logic, you set True when n % x ! = 0 for the first time:

  for x in range(3, int(n**0.5), 2): if n % x ==0: prime = False else: prime = True 

it should be:

  prime = False for x in range(3, int(n**0.5), 2): if n % x ==0: break else: prime = True 

Read the split and continue posts, as well as Clause's looping .

A shorter way to write equivalent code would be (from @ Steve Jesso ):

 prime = all(n % x != 0 for x in range(3, int(n**0.5), 2) 
0
source

Take a look at the tabs: else should reference the for for loop, not iF

 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: break else: prime = True return n 
0
source

There are errors in your code:

  • Invalid "else:"; you cannot declare a number simple if the remainder is not 0; All repeaters must be non-zeros
  • int (n * 0.5) must be int (n * 0.5 + 1) to prevent rounding errors

Possible Solution

 def RandomPrime(): while True: n = random.randint(10000, 100000) if n % 2 == 0: continue; prime = True; for x in range(3, int(n**0.5 + 1), 2): if n % x == 0: prime = False; break; if prime: return n 
0
source

Source: https://habr.com/ru/post/1210625/


All Articles