随机生成一个质数的python代码_python中的随机素数

博客给出了用Python编写的脚本,可在两个给定整数之间生成n个随机素数整数。定义了`getRandomPrimeInteger`函数用于生成随机素数,`isPrime`函数用于判断素数,并给出了在100到10000之间生成50个随机素数的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是用python编写的脚本,用于在两个给定整数之间生成n个随机素数整数:import numpy as np

def getRandomPrimeInteger(bounds):

for i in range(bounds.__len__()-1):

if bounds[i + 1] > bounds[i]:

x = bounds[i] + np.random.randint(bounds[i+1]-bounds[i])

if isPrime(x):

return x

else:

if isPrime(bounds[i]):

return bounds[i]

if isPrime(bounds[i + 1]):

return bounds[i + 1]

newBounds = [0 for i in range(2*bounds.__len__() - 1)]

newBounds[0] = bounds[0]

for i in range(1, bounds.__len__()):

newBounds[2*i-1] = int((bounds[i-1] + bounds[i])/2)

newBounds[2*i] = bounds[i]

return getRandomPrimeInteger(newBounds)

def isPrime(x):

count = 0

for i in range(int(x/2)):

if x % (i+1) == 0:

count = count+1

return count == 1

#ex: get 50 random prime integers between 100 and 10000:

bounds = [100, 10000]

for i in range(50):

x = getRandomPrimeInteger(bounds)

print(x)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值