我需要一个用户输入一个数字,并输入最接近他们输入的值质数。我正在努力研究如何在质数输入之前和之后检查质数。最后一部分是打印两个质数的较小值,如果它们距离输入的数字相同。在
n = int(input("Enter n: "))
holder1 = n
holder2 = n
prime = True
holder3 = 0
holder4 = 0
for i in range(2,n):
if (n % i) == 0:
prime = False
if(prime == True):
print("The prime closest to " + str(n) + " is " + str(n))
else:
while (prime == False):
holder1 -= 1
holder2 += 1
for i in range(2,holder1):
if (n % i) == 0:
prime = False
else:
prime = True
holder3 = holder1
for i in range(2,holder2):
if (n % i) == 0:
prime = False
else:
prime = True
holder4 = holder2
if(abs(n - holder3) <= abs(n-holder4)):
print("The prime closest to " + str(n) + " is " + str(holder3))
elif (abs(n - holder3) > abs(n-holder4)):
print("The prime closest to " + str(n) + " is " + str(holder4))
如果我没听错你的问题,你就是想找到一个最接近输入数字的数字。如果是这样的话,用筛子法计算所有质数达到给定的范围,然后找出质数到你输入的数
我希望这能回答你的问题
*****编辑*****
您说过不能使用python数学库,因此下面是稍作调整的不使用它的代码:
^{pr2}$即使我没有调试您的代码,下面的代码应该可以找到最接近的质数:
首先,我们定义一个函数来检查一个数是否是素数。接下来,我们启动
count = 1
,并通过从原始数字中减去count
并将count添加到原始数字来创建两个占位符值。如果这两个占位符值都是素数,那么我们将它们都打印为最接近的素数,否则就是它们之间最接近的素数。在相关问题 更多 >
编程相关推荐