We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importmath# using sieve_of_eratosthenes to find primes with a range [2, nth]deffind_primes(n):ifn<1:return[]ifn==1:return[2]# Estimate upper bound for nth prime using prime number theoremifn<6:upper_bound=15else:upper_bound=int(n*(math.log(n)+math.log(math.log(n))))+10sieve=[True]*(upper_bound+1)sieve[0],sieve[1]=False,Falseprimes=[]foriinrange(2,upper_bound+1):ifsieve[i]:primes.append(i)iflen(primes)==n:returnprimesforjinrange(i*i,upper_bound+1,i):sieve[j]=False# In case the sieve didn't reach enough primes (very rare with this padding)# Fill with extra primes if neededi=upper_bound+1whilelen(primes)<n:is_prime=Trueforpinprimes:ifp*p>i:breakifi%p==0:is_prime=Falsebreakifis_prime:primes.append(i)i+=1returnprimes# my codedefwaiter(number,q):# Write your code hereprimes=find_primes(q)ans=[]forpinprimes:a,b=[],[]whilenumber:n=number.pop()ifn%p==0:b.append(n)else:a.append(n)ans.extend(reversed(b))number=aans.extend(reversed(a))returnans
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Waiter
You are viewing a single comment's thread. Return to all comments →