title: Count Sum Of Digits In Numbers From 1 To N
signature: count_sum_of_digits_in_numbers_from_1_to_n <- function(n) {
test_code: 
  
  
  # SOLUTION CODE
  # ============================================
  PLACEHOLDER_CODE_BODY
  
  # TESTING CODE 
  # ============================================
  validate_solution <- function(actual, expected) {
      toString(actual)==toString(expected)
  }
  
  driver <- function(n, expected){
      if (validate_solution(PLACEHOLDER_FN_NAME(n), expected)){
          "PASSED"
      } else{
          "FAILED"
      }
  }
  
  main <- function() {
      cat(sprintf("TEST-0...%s\n",driver(
          29L, 
          165L
      )))
  
      cat(sprintf("TEST-1...%s\n",driver(
          97L, 
          865L
      )))
  
      cat(sprintf("TEST-2...%s\n",driver(
          71L, 
          540L
      )))
  
      cat(sprintf("TEST-3...%s\n",driver(
          82L, 
          667L
      )))
  
      cat(sprintf("TEST-4...%s\n",driver(
          69L, 
          525L
      )))
  
      cat(sprintf("TEST-5...%s\n",driver(
          30L, 
          168L
      )))
  
      cat(sprintf("TEST-6...%s\n",driver(
          82L, 
          667L
      )))
  
      cat(sprintf("TEST-7...%s\n",driver(
          32L, 
          177L
      )))
  
      cat(sprintf("TEST-8...%s\n",driver(
          77L, 
          609L
      )))
  
      cat(sprintf("TEST-9...%s\n",driver(
          39L, 
          240L
      )))
  
  }
  
  main()
source_py: def count_sum_of_digits_in_numbers_from_1_to_n(n):
      if (n < 10):
          return ((n * (n + 1)) / 2)
      d = int(math.log10(n))
      a = ([0] * (d + 1))
      a[0] = 0
      a[1] = 45
      for i in range(2, (d + 1)):
          a[i] = ((a[(i - 1)] * 10) + (45 * int(math.ceil(math.pow(10, (i - 1))))))
      p = int(math.ceil(math.pow(10, d)))
      msd = (n // p)
      return int(((((msd * a[d]) + (((msd * (msd - 1)) // 2) * p)) + (msd * (1 + (n % p)))) + count_sum_of_digits_in_numbers_from_1_to_n((n % p))))
source_cpp: int count_sum_of_digits_in_numbers_from_1_to_n(int n) {
    if ( n < 10 ) return n * ( n + 1 ) / 2;
    int d = log10 ( n );
    int * a = new int [ d + 1 ];
    a [ 0 ] = 0, a [ 1 ] = 45;
    for ( int i = 2;
    i <= d;
    i ++ ) a [ i ] = a [ i - 1 ] * 10 + 45 * ceil ( pow ( 10, i - 1 ) );
    int p = ceil ( pow ( 10, d ) );
    int msd = n / p;
    return msd * a [ d ] + ( msd * ( msd - 1 ) / 2 ) * p + msd * ( 1 + n % p ) + count_sum_of_digits_in_numbers_from_1_to_n ( n % p );
  }