Skip to content Skip to sidebar Skip to footer

Closest Prime Number In Python

I need a user to enter a number and enter out the closest prime number to the value they put in. I am struggling on how to check the prime numbers before and after the number they

Solution 1:

If I understood your question correctly, you are trying to find a way of finding the closest number to the inputted number. If this is the case, the Sieve of Eratosthenes method to calculate all of the prime numbers up to a given range, and then find the prime to the number you entered

# Import math for the infinity functionalityimport math

# The Sieve of Eratosthenes method of calculating the primes less than the limitdefgetPrimes(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 2for i inrange(2, limit):
        # If the number is primeif numbers[i]:
            # Add it onto the list of prime numbers
            primes.append(i)
            # Loop over all of the other factors in the listfor n inrange(i ** 2, limit, i):
                # Make them not prime
                numbers[n] = False# Return the list of prime numbersreturn 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 primesfor p in primes:
    # If the prime number is closer than maxDistifabs(number - p) < maxDist:
        # Set maxDist to the number
        maxDist = abs(number - p)
        # Set numb to the number
        numb = p

# Print the outputprint(numb, "is the closest prime number to the number you entered!")

I hope this answers your question

***** EDIT *****

You said that you cannot use the python math library, so below is the slightly adjusted code that does not use it:

# The Sieve of Eratosthenes method of calculating the primes less than the limitdefgetPrimes(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 2for i inrange(2, limit):
        # If the number is primeif numbers[i]:
            # Add it onto the list of prime numbers
            primes.append(i)
            # Loop over all of the other factors in the listfor n inrange(i ** 2, limit, i):
                # Make them not prime
                numbers[n] = False# Return the list of prime numbersreturn 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 primesfor p in primes:
    # If the prime number is closer than maxDistifabs(number - p) < maxDist:
        # Set maxDist to the number
        maxDist = abs(number - p)
        # Set numb to the number
        numb = p

# Print the outputprint(numb, "is the closest prime number to the number you entered!")

Solution 2:

Even though I didn't debug your code, the following piece of code should work to find the closest prime number :

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

defchk_prime(n):
    if n>1:
        for i inrange(2, n//2+1):
            if n%i==0:
                returnFalsebreakelse:
            returnTrueelse:
        returnFalseif chk_prime(n):
    print(f"{n} is itself a prime.")
else:
    count = 1while 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}")
            breakelif holder1_chk andnot holder2_chk:
            print(f"closest prime is {holder1}")
            breakelif holder2_chk andnot holder1_chk:
            print(f"closest prime is {holder2}")
            breakelse:
            count = count + 1

First, we define a function specifically to check whether a number is prime or not. Next we initiate count = 1 and create two place-holder values by subtracting count from original number and adding count to the original number. If both of these place-holder values are prime numbers, then we print both of them as closest primes, else the closest one between them.

Post a Comment for "Closest Prime Number In Python"