Compute sum of digits in all numbers from 1 to n | Function to computer sum of digits in numbers from 1 to n ; Driver code
function sumOfDigitsFrom1ToNUtil ( n , a ) { if ( n < 10 ) return ( n * ( n + 1 ) / 2 ) ; var d = ( parseInt ) ( Math . log10 ( n ) ) ; var p = ( Math . ceil ( Math . pow ( 10 , d ) ) ) ; var msd = ( parseInt ) ( n / p ) ; return ( msd * a [ d ] + ( msd * ( msd - 1 ) / 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToNUtil ( n % p , a ) ) ; } function sumOfDigitsFrom1ToN ( n ) { var d = ( parseInt ) ( Math . log10 ( n ) ) ; var a = new Array ( d + 1 ) . fill ( 0 ) ; a [ 0 ] = 0 ; a [ 1 ] = 45 ; for ( var i = 2 ; i <= d ; i ++ ) a [ i ] = a [ i - 1 ] * 10 + 45 * ( parseInt ) ( Math . ceil ( Math . pow ( 10 , i - 1 ) ) ) ; return sumOfDigitsFrom1ToNUtil ( n , a ) ; } var n = 328 ; document . write ( " " + n + " " + sumOfDigitsFrom1ToN ( n ) )