0

I have to calculate the 10001th prime numbers. My code is working, but it takes about 30 minutes for it to find the correct prime number. I am looking for some help to make this code run faster, I guess there is a faster way. I just started with Python, so I am partially just missing the knowlegde I guess.

number = 1
a = []
length = len(a)
d= 0

while length < 10001:
    if number == 1 or number == 2:
        a.append(number)
    for getal in range(2, number):
        if number % getal == 0:
            d = 0
            break
        else:
            d = 1
    if d > 0:
        a.append(number)
    length = len(a)
    print(length)
    number += 1

print(a[10000]) 
  • 1
    in a nutshell: `range(2, number):` => `range(2, int( number**0.5) + 1):`. Check on http://codereview.stackexchange.com, they have several duplicate questions about that: https://codereview.stackexchange.com/search?q=[python]+prime – Jean-François Fabre Aug 28 '17 at 14:32
  • I'm voting to close this question as off-topic because it belongs to codereview where several Q & A cover this classic issue. – Jean-François Fabre Aug 28 '17 at 14:33
  • Why do they do the (number ** 0.5) +1? – Lisa Van Der Tier Aug 28 '17 at 14:34
  • because if you don't find any divisors up to that value you won't find any afterwards. This reduces complexity (and execution time) drastically, specially if the number is big. – Jean-François Fabre Aug 28 '17 at 14:42
  • 1 is not a prime number, though 2 is. Since 2 is the only even prime you can skip all other even numbers in your main loop. – rossum Aug 29 '17 at 08:06

0 Answers0