Answer the question
In order to leave comments, you need to log in
How can I speed up the code?
Hello! I wrote a code to search for a prime number, on the site for which it is written, it does not pass in time and is interrupted. How can I edit this code to avoid this problem?
import math
import random
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
k = int(input())
number = 2
i = 0
while True:
if is_prime(number):
i += 1
if i == k:
break
number += 1
print(number)
Answer the question
In order to leave comments, you need to log in
at a minimum, you need to add not +1, but +2, so as not to take even numbers.
Here you already accelerate twice
And this game is generally braking
all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
I'll give you another option:
import math
def npr(k):
x = 2*k*math.log(k)
xp = 1
while abs(x/xp-1) > 0.001:
xp = x
x = x - (x - k*math.log(x)) * math.log(x) / (math.log(x) - 1)
return x
def rwh_primes(n):
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return [2] + [i for i in range(3,n,2) if sieve[i]]
k = int(input())
print( rwh_primes( int(npr(k)) + 1 )[k-1] )
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question