素数在python中怎么表示_Python中最接近的素数

如果我正确地理解了你的问题,你就是在试图找到一种方法来找到与输入的号码最接近的号码。如果是这样的话,埃拉托申斯筛法计算出给定范围内的所有质数,然后找到你输入的质数

# Import math for the infinity functionality

import math

# The Sieve of Eratosthenes method of calculating the primes less than the limit

def getPrimes(limit):

# The list of prime numbers

primes = []

# The boolean list of whether a number is prime

numbers = [True] * limit

# Loop all of the numbers in numbers starting from 2

for i in range(2, limit):

# If the number is prime

if numbers[i]:

# Add it onto the list of prime numbers

primes.append(i)

# Loop over all of the other factors in the list

for n in range(i ** 2, limit, i):

# Make them not prime

numbers[n] = False

# Return the list of prime numbers

return primes

# The number to find the closest prime of

number = int(input("Enter a number: > "))

# The list of primes using the function declared above

primes = getPrimes(number + 100)

# The distance away from the closest prime

maxDist = math.inf

# The closest prime

numb = 0

# Loop all of the primes

for p in primes:

# If the prime number is closer than maxDist

if abs(number - p) < maxDist:

# Set maxDist to the number

maxDist = abs(number - p)

# Set numb to the number

numb = p

# Print the output

print(numb, "is the closest prime number to the number you entered!")

我希望这能回答你的问题

您说过不能使用python数学库,因此下面是稍微调整过的不使用它的代码:

# The Sieve of Eratosthenes method of calculating the primes less than the limit

def getPrimes(limit):

# The list of prime numbers

primes = []

# The boolean list of whether a number is prime

numbers = [True] * limit

# Loop all of the numbers in numbers starting from 2

for i in range(2, limit):

# If the number is prime

if numbers[i]:

# Add it onto the list of prime numbers

primes.append(i)

# Loop over all of the other factors in the list

for n in range(i ** 2, limit, i):

# Make them not prime

numbers[n] = False

# Return the list of prime numbers

return primes

# The number to find the closest prime of

number = int(input("Enter a number: > "))

# The list of primes using the function declared above

primes = getPrimes(number + 100)

# The distance away from the closest prime

maxDist = 99999999

# The closest prime

numb = 0

# Loop all of the primes

for p in primes:

# If the prime number is closer than maxDist

if abs(number - p) < maxDist:

# Set maxDist to the number

maxDist = abs(number - p)

# Set numb to the number

numb = p

# Print the output

print(numb, "is the closest prime number to the number you entered!")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值