1

I need to write a program in python that given an integer as input calculates the digit in a continuous row of natural numbers starting by 1 and continuing to infinite(ex. 12345678910111213141516171819202122 etc...) So for example if we input 17 it calculates the 17th digit in this row, which is 3.

I have written a program that can calculate till the 189th digit but I need to make it for very big number(till position 2**31-1)

def digit_finder():
    if pos < 10: #Position is equal to digit.
        digit=pos
        return(digit)

    elif pos >= 10 en pos < 189: #Number between 10 and 99.
        number=(pos-9) 
        if pos%2==0: 
            new_number=(10+(number//2))
            digit=(new_number//10)
            return digit
        else: 
            new_number=(9+(number//2))
            digit=(new_number-((new_number//10)*10))
            return digit

I don't know how to continue it for bigger numbers. Please help !

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
buster
  • 167
  • 1
  • 5
  • 11

2 Answers2

1

One way is to convert each number to a string and chain them all together in an endless generator. You then ignore from the start a certain amount of characters, and then take the next one..., eg:

from itertools import chain, count, islice

def digit_finder(n):
    digits = chain.from_iterable(str(i) for i in count(1))
    return int(next(islice(digits, n - 1, None)))

print(digit_finder(17))
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

This can be solved using two equations that will generate the nth digit. Please take a look here: https://math.stackexchange.com/a/626217/48057 and here: https://myows.com/protects/copyright/67407_mathexploration-pdf.

In the second link, please read through p. 9-12 (specially 12, since there are some tips on how it can be implemented.

Community
  • 1
  • 1
Artem
  • 1,000
  • 1
  • 15
  • 30