-3

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.

Community
  • 1
  • 1
LonelyWebCrawler
  • 2,866
  • 4
  • 37
  • 57
  • There's no way this is your actual code; you can't assign an integer to `range` and then try to call `range()`. You don't get the wrong answer, you get an exception telling you that integers aren't callable. – Wooble Jul 02 '11 at 04:11
  • You're right, I just added the variable for clarity. Thank, I'll fix it. – LonelyWebCrawler Jul 02 '11 at 04:13
  • 1
    The function is_prime(a) on that post is different, it checks every number smaller than the input if it is a factor, and that is too long for my program. – LonelyWebCrawler Jul 02 '11 at 04:16
  • 1
    Why are you using `for i in range(2, range_number): numbers.append(i)` instead of `numbers = range(2, range_number)` (or `numbers = list(range2, range_number))` for newer Pythons)? – Chris Lutz Jul 02 '11 at 04:19
  • This is not a duplicate for the reason the poster stated. – ninjagecko Jul 02 '11 at 04:20

1 Answers1

1

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]):
Keith Irwin
  • 5,628
  • 22
  • 31