1
primes = [2,3,5,7]
for n in range(10, 10000):
    isPrime = True
    for d in primes:
        if (n % d) == 0:
            isPrime = False
        else:
            primes.append(n)
            break
print(primes[n])

I have to print all the prime numbers from 10 to 10000 and then append them to the given array of first few prime numbers. My code was working earlier as I tested it multiple times. Now it throws me an an error "list index out of range". Not sure what's wrong thought I was on the right track.

Jeremy McGibbon
  • 3,527
  • 14
  • 22
  • 1
    Possible duplicate of [print series of prime numbers in python](https://stackoverflow.com/questions/11619942/print-series-of-prime-numbers-in-python) – eyllanesc Sep 21 '17 at 03:24
  • 1
    Remove the `[n]`. And BTW: it is sufficient to test factors up to 100. – Klaus D. Sep 21 '17 at 03:29
  • BTW, I know that 10,000 is not prime so you don't really need to do this but technically you should do `for n in range(10, 10001):` – Brandon Kheang Sep 21 '17 at 03:44
  • I tried printing just (n) or removing [n]. None worked, if I remove [n], it prints all the numbers from 2 to 10000 just incremented by 2(ei.[2,3,5,7,9,11,13,15] – Tomas Vesely Sep 21 '17 at 03:44
  • You're appending less than 9990 values to your list and trying to access position 10000 – OneCricketeer Sep 21 '17 at 03:46
  • You're also only appending odd numbers because you mod with 2, then get 1 then it's appended to the list – OneCricketeer Sep 21 '17 at 03:47

1 Answers1

0

I think you should start with something like this

You need to iterate over all the prime numbers before you can append to the list. Otherwise, you'll always break that loop on odd numbers (you modded with 2)

primes = [2,3,5,7]
for n in range(10, 10000):
    isPrime = True
    for d in primes:
        if n % d == 0:
            isPrime = False
            break 
    if isPrime:
        primes.append(n)
print(primes)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245