1

I have a coding assignment in which I need to ask the user to enter a number n, then output the prime number closest to n. If there are two primes equally close to n, then output the smaller of the two primes. Currently I have the code posted below which obviously isn't correct, but I can't get the correct solution.

n = int(input("enter a number: "))
x = n
y = n
for i in range(2, n):
    while n % i  == 0:
            x += 1
            y -= 1
            if n % i != 0 and (x-n) < (n-y):
                print("The prime number closest to", n, "is", x)
            elif n % i != 0 and (n-y) < (x-n):
                print ("The prime number closest to" , n, "is", y)
    else:
            print ("The prime number closest to" , n, "is", n)  
  • first try simple algorithm to find prime numbers then make it fit your problem. In your code some wrong logics for example : ```while n % i == 0: if n%i!=0 ... : ``` this expression will be always false so you cant access to x y prime numbers because your `n%i` is always `0` – Tserenjamts Nov 05 '19 at 01:07

2 Answers2

2

It's easier to tackle this type of problem by breaking it into parts:

  1. Write a function is_prime that takes a number as its argument and returns True if it's prime. The standard way to do this is to repeatedly test smaller numbers to see if they work as factors (it looks like your code is trying to do something along these lines already).
  2. Once you get n from the user, iterate over nearby numbers (similar to what you're doing with x and y) and check them with is_prime. If neither is prime, go to the next nearest numbers and repeat until you find something.

Each of these parts (separately) will involve writing a loop. Your current code doesn't quite work because you're trying to do everything in a single loop. :)

Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Try this simple code:

credit for the is_prime function in this stackoverflow answer by @alf

from itertools import count


def is_prime(x):
    for i in range(2, x-1):
        if x % i == 0:
            return False
    else:
        return True


def closest_prime(n):
    if n <= 0:
        return 1
    closest = 0
    for p1 in count(n, step=-1):
        if is_prime(p1):
            closest = p1
            break
    for p2 in count(n, step=1):
        if is_prime(p2):
            if p2 - n < n - p1:
                closest = p2
                break
            else:
                closest = p1
                break
    return closest


# Tests
print(closest_prime(10))  # => 11
print(closest_prime(20))  # => 19
print(closest_prime(30))  # => 29
print(closest_prime(-100))  # => 1
print(closest_prime(0))  # => 1
print(closest_prime(1))  # => 1

Edit: add demo to print in shell

# Demo
n = int(input("enter a number: "))
print("The prime number closest to", n, "is", closest_prime(n))
moctarjallo
  • 1,479
  • 1
  • 16
  • 33