Ближайшее простое число в Python - PullRequest
0 голосов
/ 03 ноября 2019

Мне нужно, чтобы пользователь ввел число и ввел ближайшее простое число к значению, которое он ввел. Я пытаюсь выяснить, как проверять простые числа до и после введенного ими числа. Последняя часть состоит в печатименьшее значение двух простых чисел, если они находятся на одинаковом расстоянии от введенного числа.

n = int(input("Enter n: "))

holder1 = n
holder2 = n

prime = True

holder3 = 0
holder4 = 0

for i in range(2,n):
    if (n % i) == 0:
        prime = False


if(prime == True):
    print("The prime closest to " + str(n) + " is " + str(n))
else:
    while (prime == False):

        holder1 -= 1
        holder2 += 1

        for i in range(2,holder1):
            if (n % i) == 0:
                prime = False
            else:
                prime = True
                holder3 = holder1

        for i in range(2,holder2):
            if (n % i) == 0:
                prime = False
            else:
                prime = True
                holder4 = holder2


    if(abs(n - holder3) <= abs(n-holder4)):
        print("The prime closest to " + str(n) + " is " + str(holder3))
    elif (abs(n - holder3) > abs(n-holder4)):
        print("The prime closest to " + str(n) + " is " + str(holder4))

Ответы [ 2 ]

0 голосов
/ 03 ноября 2019

Несмотря на то, что я не отлаживал ваш код, следующий фрагмент кода должен работать для поиска ближайшего простого числа:

n = int(input("Enter n: "))

def chk_prime(n):
    if n>1:
        for i in range(2, n//2+1):
            if n%i==0:
                return False
                break
        else:
            return True
    else:
        return False

if chk_prime(n):
    print(f"{n} is itself a prime.")
else:
    count = 1
    while count<n:
        holder1 = n-count
        holder2 = n+count
        holder1_chk = chk_prime(holder1)
        holder2_chk = chk_prime(holder2)
        if holder1_chk and holder2_chk:
            print(f"closest primes are {holder1}, {holder2}")
            break
        elif holder1_chk and not holder2_chk:
            print(f"closest prime is {holder1}")
            break
        elif holder2_chk and not holder1_chk:
            print(f"closest prime is {holder2}")
            break
        else:
            count = count + 1

Сначала мы определим функцию специально для проверки, является ли число простымили нет. Затем мы инициируем count = 1 и создаем два значения заполнителя, вычитая count из исходного числа и добавляя счет к исходному числу. Если оба эти значения заполнителя являются простыми числами, то мы печатаем оба из них как самые близкие простые числа, в противном случае самое близкое между ними.

0 голосов
/ 03 ноября 2019

Если я правильно понял ваш вопрос, вы пытаетесь найти способ найти ближайшее число к введенному номеру. Если это так, используйте метод Сита Эратосфена для вычисления всех простых чисел до заданного диапазона, а затем найдите простое число для введенного вами числа

# 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!")

...