简体   繁体   English

在 python 中生成大素数

[英]Generating large prime numbers in python

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

Imagine what happens if the last number in range(3, int(n**0.5), 2) is not an integer divisor of n : 想象一下如果range(3, int(n**0.5), 2)最后一个数字range(3, int(n**0.5), 2)不是n的整数除数会发生什么:

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

So even if all previous checks evaluated False , you call n a prime. 因此, 即使所有先前的检查都评估为False ,也可以将n称为素数。 The minimal change to your code to fix this is: 修复此问题的代码的最小更改是:

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

So if prime is already False , it remains False . 因此,如果prime 已经为 False ,则它仍为False

However, bear in mind that, for primality, if any of those checks is False n is not prime. 但是,请记住,对于素性,如果这些检查中的任何一个是False n不是素数。 You can use this and Python's and and all (which are evaluated lazily, ie don't keep checking once finding a False ) to implement much more efficiently: 你可以使用它和Python的and all (它们被懒惰地评估,即一旦找到False就不再检查)来更有效地实现:

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 incorporates a step argument, just like range , so you can skip all of the even numbers (which definitely aren't prime!): 为了获得更好的性能,请注意randrange包含一个step参数,就像range一样,所以你可以跳过所有偶数(绝对不是素数!):

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 ) is, in my opinion, a little clearer to other, less-technical readers than n ** 0.5 (although it may or may not be more efficient ). 注意:在我看来, sqrt(n) (来自math )对于其他技术性较差的读者而言比n ** 0.5更清晰(尽管它可能会或可能不会更有效 )。

Correct logic, you are setting True when n % x ! 正确的逻辑,你在n % x时设置为True = 0 for first time: 第一次= 0

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

should be: 应该:

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

Read break and continue Statements, and else Clauses on Loops . 读取中断并继续语句,以及循环上的子句

The shorter way of writing equivalent code will be (from @ Steve Jesso ): 编写等效代码的较短方式是(来自@ Steve Jesso ):

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

Take a look to the tabs: The else should refer to the whole for loop, not to the iF 看一下标签:else应该引用整个for循环,而不是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

There're errors in your code: 您的代码中存在错误:

  1. Incorrect "else:"; 不正确的“else:”; you can't declare number being prime if a remainder is not 0; 如果余数不为0,则不能将数字声明为素数; All the remaiders should be non-zeros 所有的备用者都应该是非零的
  2. int(n* 0.5) should be int(n *0.5 + 1) to prevent round-up errors int(n * 0.5)应该是int(n * 0.5 + 1)以防止舍入错误

The possible solution is 可能的解决方案是

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

Generating big primes over and over can cost a lot of time.一遍又一遍地生成大素数可能会花费大量时间。 For this reason I used increments.出于这个原因,我使用了增量。

import random

def generate_big_prime(size):
    p = random.randrange(2 ** (size - 1), 2 ** size - 1)
    if p % 2 == 0:
        p += 1
    while not is_prime(p):
        p += 2
    return p

Where is_prime() is a primality test.其中 is_prime() 是素数测试。 I would recommend the Miller-Rabin primality test for its efficiency.我会推荐Miller-Rabin 素数测试的效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM