Na dole jest krótka dokumentacja jaką robiłem razem z kodem. Problem jest taki, że chociaż wszystko działa poprawnie, to przy bardzo dużych liczbach pętla trwa zdecydowanie za długo.
Generalnie, to musimy znaleźć pierwszą parę liczb, której odstęp wynosi "g". Liczby te muszą być pierwsze, zaczynając od "m" i kończąc na "n".
Mam nadzieję, że rozumiecie mój problem, który dotyczy głównie optymalizacji i refaktoryzacji kodu.
Wiem też, że kata nie na tym polega, ale nie mam pojęcia co z tym zrobić, wszelka pomoc bardzo przydatna :)
Steps in Primes (13.04)
Entry
I have to find the first pair with gained spacing in range of two next parameteres.
Data
-
g (integer >= 2) which indicates the step we are looking for,
-
m (integer >= 2) which gives the start of the search (m inclusive),
-
n (integer >= m) which gives the end of the search (n inclusive)
Examples:
step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"
step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++
step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}
Reference:
-
A "gap" is more restrictive: there must be no primes in between (101-107 is a "step" but not a "gap". Next kata will be about "gaps":-).
- "step" vs "gap"
Ways
-
Go through parameters to get actual numbers - Filter Prime Numbers
-
Find a closest pair of prime numbers (with correct step between) - Refactor and Submit
Code (Unsolved yet)
def step(g, m, n):
primes = []
##FILTER PRIMES##
for x in range(m, n):
if x > 1:
# check for factors
for i in range(2, x):
if (x % i) == 0:
break
else:
primes.append(x)
##FIND A PAIR##
y = 0
print(primes)
for x in range(0, len(primes)):
i = 1
while y != g:
if i+x >= len(primes)-1:
break
y = primes[x+i] - primes[x]
i += 1
if y == g:
return sorted([primes[x+i-1], primes[x]])
return None
#EASY CHECK
x = step(4,130,200) #[163, 167]
#HARDCORE CHECK
#x = step(4,30000,100000) #[359, 367]
print(x)