Search code examples
pythonalgorithmnumbers

calculate the digits of the Nth number using the given numbers


I'd like to get the digits of the Nth number by using the given numbers which are 3 and 9. From these numbers, I've got the numbers like 3, 9, 33, 39, 93, 99, 333 ... in order. So the digits of the 4th number is 2 and that of the 7th number is 3. What I want to do is to calculate the digits of the Nth number from this logic. Any suggestions? Thanks. (You may assume that N is 1000000)

+What I've found was that there are 2 1-digit numbers (=2^1), 4 2-digit numbers (=2^2), and 8 3-digit numbers(=2^3). So I tried to apply the concept of geometric sequence but wasn't able to make it.


Solution

  • You already know that quantity of numbers with length k is 2^k, so we can exploit this fact. Essentially this is implementation of int(log2(n+1)) without any math libraries:

    def nlen(n):
        lng = 0
        lcnt = 1
        overall = 0
        while overall < n:
            lcnt *= 2
            overall += lcnt
            lng += 1
        return lng