Question about Project Euler problem 7 in Python

Question:

I’ve been figuring about question 7 of project Euler. I’ve worked out the
my Python code, but it has no output, and I don’t know if there are any grammatical and logical problems. Would you please help me check what’s wrong with it? Here is the original question:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number?

def isprime(n):
    for i in range(2,n):
        if n % i == 0:
            return False
    return True
x = 3
counter = 2
while counter <= 10001:
    if isprime(x):
        counter += 1
        x += 2
    else:
        x += 2
print (x)
Asked By: never0lie

||

Answers:

Your logic works fine after the following fixes:

  1. Correct indentation.
  2. Subtract 2 from your end result.

Note your implementation is inefficient. However, it does work.

def isprime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

x = 3

counter = 2

while counter <= 10001:
    if isprime(x):
        counter += 1
        x += 2
    else:
        x += 2

print(x-2)  # 104743
Answered By: jpp

No need to check the divisibility up to the number, just check till to the square root of the number.

import math

def is_prime(num):
    if (num < 2):
        return False
    elif (num == 2):
        return True
    else:
        divisible = False
        for i in range(2, int(math.sqrt(num)+1)):
            if (num%i == 0):
                divisible = True
        return not(divisible)
    
count = 2
number = 3

while count != 10001:
    number += 2
    if is_prime(number):
        count += 1

print(number)
Answered By: Nadeera Gayashan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.