A
A
Andrey Nill2020-06-14 13:01:45
Python
Andrey Nill, 2020-06-14 13:01:45

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

2 answer(s)
D
Developer, 2020-06-14
@samodum

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))

get rid of her

G
galaxy, 2020-06-15
@galaxy

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] )

How it works:
rwh_primes - sieve of Eratosthenes, not the fastest implementation, honestly peeped on SO
npr - function to calculate natural n, the number of primes less than which is greater than or equal to k
(based on the inequality : k > n/ln(n) - function implements Newton's method for the equation x/ln(x) = k)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question