私信  •  关注

Pencilcaseman

Pencilcaseman 最近创建的主题
Pencilcaseman 最近回复了
5 年前
回复了 Pencilcaseman 创建的主题 » 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!")