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)
Answers:
Your logic works fine after the following fixes:
- Correct indentation.
- 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
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)
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)
Your logic works fine after the following fixes:
- Correct indentation.
- 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
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)