0

I am trying to solve a Project Euler problem using Python 3 and I faced this problem. I want to find the nth element from this infinite series which the generator is producing where n = 1015 Here's the generator:

def test_gen():
  yield 1
  yield 1
  sum_till_now = 1
  while True:
    sum_till_now += sum_of_digits(sum_till_now)
    yield sum_till_now

The series is 1, 1, 2, 4, 8, 16, 23, 28,... and is produced fine by the generator

I tried the following approach:

def cal():
  for index, item in enumerate(a):
    if index == 1000000000000000:
      print(item)
      return

but it takes too much time to solve it. Is there any faster way to find the nth element of the generator when n is quite large? If my generator is inefficient do tell me. I don't want the correct answer to the problem if my approach itself is wrong. Thanks for the help.

Vivek
  • 123
  • 7
  • You cannot get the *i*-th element of such generator faster than iterating over it. So you have to find a way to calculate the *i*-th element faster yourself. – Willem Van Onsem Jun 18 '17 at 14:04
  • Possible duplicate: [Get the nth item of a generator in Python](https://stackoverflow.com/questions/2300756/get-the-nth-item-of-a-generator-in-python?rq=1) – Szymon Jun 18 '17 at 14:08
  • This isn't an easy problem. You need to look for patterns in order to skip many iterations. See http://eulersolutions.fr.yuku.com/forum/getrefs/id/6688/type/0 – Eric Duminil Jun 18 '17 at 14:12

0 Answers0