简体   繁体   English

Python程序查找素数(3.5)

[英]Python program to find prime numbers (3.5)

I am making a program that finds prime numbers. 我正在编写一个查找素数的程序。 The user is asked to provide a number greater than 2 (n) the program then makes a list starting at 2 and ending at the user's number (n). 要求用户提供一个大于2(n)的数字,然后程序列出从2开始并以用户的数字(n)结尾的列表。 In my program, I am supposed to set a variable called current to 2 and then loop through the list looking for multiples of current and removing them. 在我的程序中,我应该将一个称为current的变量设置为2,然后遍历列表以查找current的倍数并将其删除。 At the end of a loop I add 1 to current and the program loops again doing the same as before. 在循环结束时,我将1加到current上,程序再次循环执行与以前相同的操作。 The list is printed each time. 每次打印该列表。 My program works correctly (I am testing by using the number 10 as n) when it gets to the end 10 is left even though it should have been removed. 我的程序可以正常工作(我正在通过将数字10用作n进行测试),直到结尾10了,即使它应该已被删除也是如此。 Please help. 请帮忙。

Here is my code: 这是我的代码:

while True:
    global n
    n = int ( input ( "Please enter a number larger than 2. " ) )
    if n > 2:
        break
    else:
        print ( "Your number is not larger than 2." )
        continue

current = 2
myList = list ( range ( 2, n + 1 ) )
while current < n:
    if current == []:
        break
    for i in reversed ( range ( len( myList )-1 ) ):
        if myList[i] % current == 0 and myList[i] != current and ( myList[i] / current ).is_integer(): myList.pop(i)
        print ( myList )
    current = current + 1

for i in reversed ( range ( len( myList )-1 ) ): should be for i in reversed ( range ( len( myList ) ) ): for i in reversed ( range ( len( myList )-1 ) ):应该for i in reversed ( range ( len( myList ) ) ):

range by default doesn't include the last number: range(5) gives 0,1,2,3,4 默认情况下,range不包含最后一个数字: range(5)给出0,1,2,3,4

To make it only output a line when it makes a change: 要使其仅在进行更改时输出一行:

if myList[i] % current == 0 and myList[i] != current and ( myList[i] / current ).is_integer():
    myList.pop(i)
    print ( myList )

If you do the print inside the if statement, then only when it makes a change will it display the new list. 如果在if语句中进行打印,则只有在进行更改时才会显示新列表。

Your "for" loop has the problem. 您的“ for”循环有问题。 Remove the "-1" and you should be fine, since range is inclusive, exclusive. 删除“ -1”,就可以了,因为范围是包含的,排他的。 Just a note, when looking for primes within a range(2,n) you don't have to check to n, just to sqrt(n). 请注意,在查找范围(2,n)内的质数时,不必检查n,而只需检查sqrt(n)。 Check this link. 检查此链接。 https://www.quora.com/Why-do-we-first-find-the-prime-numbers-up-to-square-root-of-N-in-segmented-sieve https://www.quora.com/Why-do-we-first-find-the-prime-numbers-up-to-square-root-of-N-in-segmented-sieve

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

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