无限重复打印声明

时间:2017-05-04 02:59:51

标签: math printing repeat infinite

我目前正在开展一个项目,用户需要输入一个数字,程序将确定该数字是否为素数。这里的问题是print语句一旦执行就会重复,并且停止它的唯一方法是在程序正常工作时终止它。

以下是该计划的代码:

print("Here, you will be asked to enter a number and the program will 
       determine whether said number is prime. ")

print ("For the sake of simplicity, we'll only be using numbers that are 
        below 100. ")

Number = int (input("Please enter a number and we will determine if the 
number you entered if prime. "))

for Number in range (1,98):
    for y in range (1,98):
        if Number %y!=0:
            print ("This number is, in fact, a prime number. ")
        else:
            if Number %y==0:
                print ("This number is not prime.")

1 个答案:

答案 0 :(得分:1)

对于一个素数,它应该只能被自身和1整除。 所以,你需要检查的是[2,n]之间的数字,如果它可以被任何数字整除,那么它不是素数,你需要打破for循环。

如果for循环在到达结尾时被破坏,那么这意味着[2,n]之间没有数字是该数字的因子,因此数字是素数。我们使用isPrime boolean flag

检查循环是否自然破坏

PS。程序可能无法编译,因为我没有运行它,但逻辑是正确的

print ("Here, you will be asked to enter a number and the program will determine whether said number is prime. ") 
print ("For the sake of simplicity, we'll only be using numbers that are below 100. ")
isPrime = True
Number = int (input("Please enter a number and we will determine if the number you entered if prime. "))

for y in range (2,Number): 
    if Number%y==0 and Number!=y: 
       isPrime = False
       print ("This number is not prime.")
       break
if isPrime:
       print "Number is prime"