Search code examples
pythonpython-3.xprimesprimality-test

what is the highest prime number between 1 and 10001


So I'm trying to find the 10,001 prime number. Yes, its the euler #7 problem. The code i wrote appears to give me all the prime numbers from 3 to 10,001 but my answer is still incorrect. I know there are other questions about this that have been answered but stealing someone else code does not help me learn. So I'm looking for insight into where i went wrong with this. First I seperated out all the odd numbers and added them to a list. I noticed that there were squares of some of the prime numbers in the list so I check the list against the squares of every number from 2 to 10,0001. That should have left me with nothing but prime numbers but I am still getting the wrong answer. Any ideas would be great thank you

prime = [i for i in range(2, 10002) if i % 2 != 0]

for i in range(2, 10002):
    if i * i in prime:
        prime.remove(i * i)

print(prime[-1])

Solution

  • Have you tried the case of 7*11=77? You're only looking in perfect squares when you should search multiples of all the known primes. In keeping with the theme of Project Euler, I'm not gonna give you the answer, but I_ can_ point you to the Sieve of Eratosthenes.

    well actually... Since it's such an early problem, I'll dangle a spoiler.

    Make a list of primes, initialize it to [2,3,5]. Starting from n=8 and increasing by six each time, check n-1 and n+1 for primality by testing modulos for each known primes from 2 to the square root of your number.