寻找最接近的素数

时间:2019-11-06 20:07:06

标签: python python-3.x

我需要打印出最接近输入数字的素数。 该代码适用于输入的素数,但不适用于非素数。见下文 我是一个相对较新的编码器,并且是Python的新手

输入为16 预期结果是最接近16的素数是17 实际结果是最接近16的素数是18

x = int(input("Enter a number: "))
y = x-1
z = x+1
counter = 0
valid = True
while valid == True:
    for i in range (2,x):
        if x%i == 0:
            counter += 1
    if counter <= 1:
        print("The closest prime to ",x," is ",x)
        valid = False
    counter = 0
    for i in range (2,y):
        if y%i == 0:
            counter += 1
    if counter <= 1:
        print("The closest prime to ",x," is ",y)
        valid = False
    counter = 0
    y -= 1
    for i in range (2,z):
        if y%i == 0:
            counter += 1
    if counter <= 1:
        print("The closest prime to ",x," is ",z)
        valid = False
    counter = 0
    z += 1

1 个答案:

答案 0 :(得分:0)

请尝试此操作,它会打印从1到100的最接近的质数。您可以尝试使用具有随机值的此功能。

def is_prime(n):
    if n == 1:
        return True
    if n == 2:
        return True
    for i in range(2, int(n/2) + 1):
        if n % i != 0:
            continue
        else:
            return False
    return True

def get_nearest_prime(n):
    if is_prime(n):
        return n
    for i in range(1, n*n):
        if is_prime(n+i):
            return n+i
        if is_prime(n-i):
            return n-i

if __name__ == "__main__":
    for i in range(1, 100):
        print('%s: %s' % (i, get_nearest_prime(i)))