简体   繁体   English

Python 程序查找 1 - n 范围内的所有素数

[英]Python program to find all prime numbers in the range 1 - n

Hi I know there are lots of solutions to this problem but I wanted some help finding out why my answer is wrong.嗨,我知道这个问题有很多解决方案,但我需要一些帮助来找出我的答案错误的原因。

Here's my answer:这是我的答案:

number = int(input("enter a number: "))

for n in range(2, number + 1):
    for i in range(2, number // 2):
        if n == 2:
            print(n)
        elif n % i == 0:
            break
        else:
            print(n)

Here's the output on my terminal:这是我终端上的 output:

> enter a number: 12 
  2 2 2 2 3 5 5 5 7 7 7 7 9 11 11 11 11

thankss谢谢

The problem with your solution is that you haven't set up the inner loop properly.您的解决方案的问题是您没有正确设置内部循环。 The other problem (the lesser one in my opinion) is that the print is inside of your inner loop which causes the multiple prints.另一个问题(我认为较小的问题)是打印在您的内部循环内部,这会导致多次打印。

Here is a proper solution:这是一个适当的解决方案:

for n in range(2, number + 1):
    isPrime = True
    for i in range(2, n - 1):
        if n % i == 0:
            isPrime = False
    if isPrime:
        print(n)

thanks everyone i realised i made a lot of really silly mistakes.谢谢大家,我意识到我犯了很多非常愚蠢的错误。

i fixed my code in case anyone else sees this question and wants a solution:我修复了我的代码,以防其他人看到这个问题并想要一个解决方案:

number = int(input("enter the number: "))

for n in range(2, number + 1):
    for i in range(2, n):
        if n % i == 0:
            break
    else:
        print(n)

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

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