简体   繁体   中英

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). 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. At the end of a loop I add 1 to current and the program loops again doing the same as before. 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. 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 ) ) ):

range by default doesn't include the last number: range(5) gives 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.

Your "for" loop has the problem. Remove the "-1" and you should be fine, since range is inclusive, exclusive. Just a note, when looking for primes within a range(2,n) you don't have to check to n, just to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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