I'm solving the following problem on a coding site. It's failing for some edge cases on the tests (hidden tests), but I'm not sure what they are. Anyone see any issues with this?
Problem: Let A
be a string of all the prime numbers sequentially squashed together (i.e. 235711131719...
). Given an index n
, return a string of 5 digits where the first digit is at index n
in A.
e.g. foo(0) => 23571
and foo(10) => 19232
Here's my code:
def gen_primes():
A = {}
i = 2
while True:
if i not in A:
yield i
A[i * i] = [i]
else:
for p in A[i]:
A.setdefault(p + i, []).append(p)
del A[i]
i += 1
def answer(n):
counter = 0
prime_string = ""
for p in gen_primes():
if (counter >= n):
prime_string += str(p)
counter += len(str(p))
if len(prime_string) >= 5:
break
return prime_string[:5]