Project Euler #40: Champernowne's constant

  • + 0 comments

    I used more math than programming in this question.

    def formposicaodig(x):
        '''
        How many digits are there up to the first digit of x
        (x-10^(n-1))*n + [sum 9*(10^(k-2))*(k-1), from k = 2 to n]
        = (x-10**(n-1))*n + n * 10**(n-1) + (1 - 10**n)//9
        '''
        n = len(str(x))
    
        return 1 +  (x-10**(n-1))*n + n * 10**(n-1) + (1 - 10**n)//9
    
    def formInvposicaodig(pos):
        '''
        x = The position digit 'pos' is contained in which number
        n = len(str(x)) : Number of digits in x
        x = ( pos + (10**n  -1)//9 - n * 10**(n-1) -1) / n + 10**(n-1) 
        return : What is the nth digit of Champernowne's constant
        '''
        n = len(str(pos))
        xcalc = (pos + (10**n-1)//9 - 1) // n
        # As I don't know the number of digits of x, 
        # I iterate until the xcal found is equal to the size of the formula to determine it.
        while n != len(str(xcalc)):
            n = len(str(xcalc))
            xcalc = (pos + (10**n-1)//9 - 1) // n
        return int(str(xcalc)[pos - formposicaodig(xcalc)])
    
    
    n = int(input())
    for k in range(n):
        prd = 1
        for j in map(int,input().split()):
            nth = formInvposicaodig(j)
            if nth == 0:
                prd = 0
                break
            else:
                prd *= nth
        print(prd)