Function to computer sum of digits in numbers from 1 to n
def sumOfDigitsFrom1ToNUtil ( n , a ) : NEW_LINE INDENT if ( n < 10 ) : NEW_LINE INDENT return ( n * ( n + 1 ) ) // 2 NEW_LINE DEDENT d = int ( math . log ( n , 10 ) ) NEW_LINE p = int ( math . ceil ( pow ( 10 , d ) ) ) NEW_LINE msd = n // p NEW_LINE return ( msd * a [ d ] + ( msd * ( msd - 1 ) // 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToNUtil ( n % p , a ) ) NEW_LINE DEDENT def sumOfDigitsFrom1ToN ( n ) : NEW_LINE INDENT d = int ( math . log ( n , 10 ) ) NEW_LINE a = [ 0 ] * ( d + 1 ) NEW_LINE a [ 0 ] = 0 NEW_LINE a [ 1 ] = 45 NEW_LINE for i in range ( 2 , d + 1 ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] * 10 + 45 * int ( math . ceil ( pow ( 10 , i - 1 ) ) ) NEW_LINE DEDENT return sumOfDigitsFrom1ToNUtil ( n , a ) NEW_LINE DEDENT