DEV Community

Cover image for Day 5: Nearest Prime Numbers

Day 5: Nearest Prime Numbers

mattryanmtl profile image Matt Ryan ・1 min read

Output two numbers: the nearest prime below the input, and the nearest prime above it.

from itertools import count

def is_prime(n):
    for x in range(2, n):
        if not n % x:
            return False
    return True

def prev_prime(n):
    for x in range(n, 2, -1):
        if is_prime(x):
            return x

def next_prime(n):
    for x in count(n + 1):
        if is_prime(x):
            return x

user_input = (270, 541, 993, 649)
for i in user_input:
    if is_prime(i):
        print(f'{i} is prime')
        print(f'{prev_prime(i)} < {i} < {next_prime(i)}')
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app