DEV Community

DAVID ARAVINDHRAJ
DAVID ARAVINDHRAJ

Posted on

Understanding Prime Numbers and How to Find the Nearest Prime in Python

Prime numbers are a foundational concept in mathematics and programming. If you're preparing for coding interviews or just want to brush up on logic building in Python, learning to work with primes is essential.
In this post, we’ll:

  • Understand what a prime number is.

  • Learn the logic to check if a number is prime manually.

  • Build a Python script to find the nearest prime number from a given input.

🔢 What is a Prime Number?

A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.

Examples:

  • 2, 3, 5, 7, 11, 13, 17...

Not Prime:

  • 1 (by definition)

  • 4 (divisible by 2)

  • 9 (divisible by 3)

💡 How Do You Manually Check If a Number is Prime?

To manually check if a number n is prime:

  • If n <= 1, it’s not a prime. -If n == 2, it’s a prime (smallest and only even prime).
  • If n is divisible by 2, it’s not a prime.
  • Check divisibility from 3 up to √n (square root of n) — if divisible, it's not a prime.

This logic is efficient and avoids unnecessary checks.

🚀 Goal: Find the Nearest Prime to a Given Number

Let’s say a user inputs a number like 10. The nearest primes are 7 (lower) and 11 (upper). Since 11 is closer, the program should return 11.

🧑‍💻 Python Code to Find the Nearest Prime Number


def is_prime(n):
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    for i in range(3, int(n ** 0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

def nearest_prime(n):
    if is_prime(n):
        return n

    offset = 1
    while True:
        lower = n - offset
        upper = n + offset
        if lower > 1 and is_prime(lower):
            return lower
        if is_prime(upper):
            return upper
        offset += 1

Enter fullscreen mode Exit fullscreen mode

Example usage

num = int(input("Enter a number: "))
print("Nearest prime:", nearest_prime(num))
Enter fullscreen mode Exit fullscreen mode

🔍 How the Code Works

  1. is_prime(n): Checks if the number is prime using the logic we discussed earlier.
  2. nearest_prime(n):
  • First, it checks if the number itself is prime.
  • If not, it expands outward by 1 step each time (offset), checking:
  • n - offset
  • n + offset
  • It returns the first prime it finds, ensuring it's the closest one.

🧪 Example Runs

Enter a number: 10
Nearest prime: 11

Enter a number: 24
Nearest prime: 23
Enter fullscreen mode Exit fullscreen mode

Top comments (0)