开发者

Finding if a number is prime using Python [duplicate]

开发者 https://www.devze.com 2023-03-17 00:55 出处:网络
This question already has answers here: 开发者_如何学Go Closed 11 years ago. Possible Duplicates: Fastest way to list all primes below N in python
This question already has answers here: 开发者_如何学Go Closed 11 years ago.

Possible Duplicates:

Fastest way to list all primes below N in python

Checking if a number is a prime number in Python

I am working on Project Euler Problem 10, which states as follows:

Find the sum of all the primes below two million.

Here's my program:

numbers = []
sum = 0
range_number = 2000000

#Appends all numbers in range
for i in range(2, range_number):
    numbers.append(i)

#i is every entry in numbers, n is the multiples of numbers[i] starting at one 
#value of numbers[i] after i. This is the Sieve of Eratosthenes.
for i in range(0, len(numbers)-1):
    if numbers[i] != None:
        for n in range(i + numbers[i], len(numbers)-1, numbers[i]):
            numbers[n] = None

#Adds all the numbers that are not None
for i in numbers:
    if i != None:
        sum += i

print(sum)

My program changes all multiples of every number below the range to None, which should eliminate all composites and leave only primes.

When I plug in a simple number for range_number like 10, I get the wrong answer. Instead of just posting your own program, please tell me where I went wrong. Other posts mentioned using the square root, but I didn't really get that.

Thanks.


Your problem is that you never eliminate the last number in numbers. If range_number is 21, then len(numbers) is 20 and len(numbers)-1 is 19. So this line here:

for n in range(i + numbers[i], len(numbers)-1, numbers[i]):

Never actually removes the number 20 from the list. You could have seen this if you'd printed out the list. So currently your solution gives the correct answer if range_number is one more than a prime number, but is off by range_number-1 when range_number is one more than a composite.

To fix that problem, simply change the line to be:

for n in range(i + numbers[i], len(numbers), numbers[i]):
0

精彩评论

暂无评论...
验证码 换一张
取 消