简体   繁体   English

我的程序在范围内的质数有什么问题?

[英]What's wrong with my program for prime number in a range?

To print the prime numbers in range program: 要在范围程序中打印质数:

lower = int(input("Enter lower range: "))   
upper = int(input("Enter upper range: "))

for num in range(lower,upper + 1):

   # prime numbers are greater than 1

   if num > 1:

       for i in range(2,num):

           if (num % i) == 0:

               break
       else:
           print(num)

The output for the above is: 上面的输出是:

Enter lower range: 3
Enter upper range: 10

3
5
7

But,When I tried with the below code, the output is varying. 但是,当我尝试下面的代码时,输​​出是变化的。

min=int(input("enter the min num"))

max=int(input("Enter the max num"))

for i in range(min,max+1):

    if i > 1:

        for j in range(2,i):

            if (i%j) == 0:

                break

            else:

                print(i)

Output: 输出:

enter the min num: 3
Enter the max num: 10

3
5
5
5
7
7
7
7
7
9

You have an indentation difference: 您有一个缩进差异:

for j in range(2,i):

        if (i%j) == 0:

            break

## This piece
        else:

            print(i)
## This piece

In your first example: 在第一个示例中:

  • For each number, do a modulo calculation and break if it leads to 0 对于每个数字,进行模运算,如果结果为0,则中断
  • If none of the calculations lead to 0, you find a prime (and thus print it) 如果没有一个计算结果为0,则找到一个质数(并打印出来)

En your second example: 恩第二个例子:

  • For each number, do a modulo calculation and break if it leads to 0 对于每个数字,进行模运算,如果结果为0,则中断
  • If it doesn't lead to 0: print the number. 如果不等于0:请打印数字。 Which happens quite more often than the else in example 1. 与示例1中的else情况相比,发生这种情况的频率更高。

二维循环是这段代码的问题,当i = 5时,您求j(2,5),因此您经历了三次循环,您应该添加一条命令来防止重复

You;re printing the value after each check success. 您将在每次检查成功后打印该值。 You should put in a flag to print it out after all the checks. 在所有检查之后,您都应该标记一个标记以将其打印出来。 Something like below 像下面这样

for i in range(min,max+1):
    if i > 1:
        prime = True
        for j in range(2,i):
            if (i%j) == 0:
                prime = False
                break
        if prime:
            print(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM