In below implementation, the above formula is implemented using dynamic programming as there are overlapping subproblems.
The above formula is one core step of the idea. Below is complete algorithm

Algorithm: sum(n)

1) Find number of digits minus one in n. Let this value be 'd'.
For 328, d is 2.
2) Compute some of digits in numbers from 1 to 10d - 1.
Let this sum be w. For 328, we compute sum of digits from 1 to
99 using above formula.
3) Find Most significant digit (msd) in n. For 328, msd is 3.
4) Overall sum is sum of following terms
a) Sum of digits in 1 to "msd * 10d - 1". For 328, sum of
digits in numbers from 1 to 299.
For 328, we compute 3*sum(99) + (1 + 2)*100. Note that sum of
sum(299) is sum(99) + sum of digits from 100 to 199 + sum of digits
from 200 to 299.
Sum of 100 to 199 is sum(99) + 1*100 and sum of 299 is sum(99) + 2*100.
In general, this sum can be computed as w*msd + (msd*(msd-1)/2)*10d
b) Sum of digits in msd * 10d to n. For 328, sum of digits in
300 to 328.
For 328, this sum is computed as 3*29 + recursive call "sum(28)"
In general, this sum can be computed as msd * (n % (msd*10d) + 1)
+ sum(n % (10d))

Below is the implementation of above aglorithm.

C++

filter_none

editclose

play_arrow

linkbrightness_4code

// C++ program to compute sum of digits in numbers from 1 to n

#include<bits/stdc++.h>

usingnamespacestd;

// Function to computer sum of digits in numbers from 1 to n

// Comments use example of 328 to explain the code

intsumOfDigitsFrom1ToN(intn)

{

// base case: if n<10 return sum of

// first n natural numbers

if(n<10)

returnn*(n+1)/2;

// d = number of digits minus one in n. For 328, d is 2

intd = log10(n);

// computing sum of digits from 1 to 10^d-1,

// d=1 a[0]=0;

// d=2 a[1]=sum of digit from 1 to 9 = 45

// d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900

// d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500

int*a = newint[d+1];

a[0] = 0, a[1] = 45;

for(inti=2; i<=d; i++)

a[i] = a[i-1]*10 + 45*ceil(pow(10,i-1));

// computing 10^d

intp = ceil(pow(10, d));

// Most significant digit (msd) of n,

// For 328, msd is 3 which can be obtained using 328/100

intmsd = n/p;

// EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE

// First two terms compute sum of digits from 1 to 299

// (sum of digits in range 1-99 stored in a[d]) +

// (sum of digits in range 100-199, can be calculated as 1*100 + a[d]

// (sum of digits in range 200-299, can be calculated as 2*100 + a[d]

// The above sum can be written as 3*a[d] + (1+2)*100

// EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE

// The last two terms compute sum of digits in number from 300 to 328

// The third term adds 3*29 to sum as digit 3 occurs in all numbers

// from 300 to 328

// The fourth term recursively calls for 28

returnmsd*a[d] + (msd*(msd-1)/2)*p +

msd*(1+n%p) + sumOfDigitsFrom1ToN(n%p);

}

// Driver Program

intmain()

{

intn = 328;

cout << "Sum of digits in numbers from 1 to "<< n << " is "

<< sumOfDigitsFrom1ToN(n);

return0;

}

chevron_right

filter_none

Java

filter_none

editclose

play_arrow

linkbrightness_4code

// JAVA program to compute sum of digits

// in numbers from 1 to n

importjava.io.*;

importjava.math.*;

classGFG{

// Function to computer sum of digits in

// numbers from 1 to n. Comments use

// example of 328 to explain the code

staticintsumOfDigitsFrom1ToN(intn)

{

// base case: if n<10 return sum of

// first n natural numbers

if(n < 10)

return(n * (n + 1) / 2);

// d = number of digits minus one in

// n. For 328, d is 2

intd = (int)(Math.log10(n));

// computing sum of digits from 1 to 10^d-1,

// d=1 a[0]=0;

// d=2 a[1]=sum of digit from 1 to 9 = 45

// d=3 a[2]=sum of digit from 1 to 99 =

// a[1]*10 + 45*10^1 = 900

// d=4 a[3]=sum of digit from 1 to 999 =

// a[2]*10 + 45*10^2 = 13500

inta[] = newint[d+1];

a[0] = 0; a[1] = 45;

for(inti = 2; i <= d; i++)

a[i] = a[i-1] * 10+ 45*

(int)(Math.ceil(Math.pow(10, i-1)));

// computing 10^d

intp = (int)(Math.ceil(Math.pow(10, d)));

// Most significant digit (msd) of n,

// For 328, msd is 3 which can be obtained

// using 328/100

intmsd = n / p;

// EXPLANATION FOR FIRST and SECOND TERMS IN

// BELOW LINE OF CODE

// First two terms compute sum of digits from

// 1 to 299

// (sum of digits in range 1-99 stored in a[d]) +

// (sum of digits in range 100-199, can be

// calculated as 1*100 + a[d]

// (sum of digits in range 200-299, can be

// calculated as 2*100 + a[d]

// The above sum can be written as 3*a[d] +

// (1+2)*100

// EXPLANATION FOR THIRD AND FOURTH TERMS IN

// BELOW LINE OF CODE

// The last two terms compute sum of digits in

// number from 300 to 328. The third term adds

// 3*29 to sum as digit 3 occurs in all numbers

// from 300 to 328. The fourth term recursively

// calls for 28

return(msd * a[d] + (msd * (msd - 1) / 2) * p +

msd * (1+ n % p) + sumOfDigitsFrom1ToN(n % p));

}

// Driver Program

publicstaticvoidmain(String args[])

{

intn = 328;

System.out.println("Sum of digits in numbers "+

"from 1 to "+n + " is "+

sumOfDigitsFrom1ToN(n));

}

}

/*This code is contributed by Nikita Tiwari.*/

chevron_right

filter_none

Python3

filter_none

editclose

play_arrow

linkbrightness_4code

# PYTHON 3 program to compute sum of digits

# in numbers from 1 to n

importmath

# Function to computer sum of digits in

# numbers from 1 to n. Comments use example

# of 328 to explain the code

defsumOfDigitsFrom1ToN( n) :

# base case: if n<10 return sum of

# first n natural numbers

if(n<10) :

return(n*(n+1)/2)

# d = number of digits minus one in n.

# For 328, d is 2

d =(int)(math.log10(n))

"""computing sum of digits from 1 to 10^d-1,

d=1 a[0]=0;

d=2 a[1]=sum of digit from 1 to 9 = 45

d=3 a[2]=sum of digit from 1 to 99 = a[1]*10

+ 45*10^1 = 900

d=4 a[3]=sum of digit from 1 to 999 = a[2]*10

+ 45*10^2 = 13500"""

a =[0] *(d +1)

a[0] =0

a[1] =45

fori inrange(2, d+1) :

a[i] =a[i-1] *10+45*(int)(math.ceil(math.pow(10,i-1)))

# computing 10^d

p =(int)(math.ceil(math.pow(10, d)))

# Most significant digit (msd) of n,

# For 328, msd is 3 which can be obtained

# using 328/100

msd =n//p

"""EXPLANATION FOR FIRST and SECOND TERMS IN

BELOW LINE OF CODE

First two terms compute sum of digits from 1 to 299

(sum of digits in range 1-99 stored in a[d]) +

(sum of digits in range 100-199, can be calculated

as 1*100 + a[d]. (sum of digits in range 200-299,

can be calculated as 2*100 + a[d]

The above sum can be written as 3*a[d] + (1+2)*100

EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW

LINE OF CODE

The last two terms compute sum of digits in number

from 300 to 328. The third term adds 3*29 to sum

as digit 3 occurs in all numbers from 300 to 328.

The fourth term recursively calls for 28"""

return(int)(msd *a[d] +(msd*(msd-1) //2) *p +

msd *(1+n %p) +sumOfDigitsFrom1ToN(n %p))

# Driver Program

n =328

print("Sum of digits in numbers from 1 to",

n ,"is",sumOfDigitsFrom1ToN(n))

# This code is contributed by Nikita Tiwari.

chevron_right

filter_none

C#

filter_none

editclose

play_arrow

linkbrightness_4code

// C# program to compute sum of digits

// in numbers from 1 to n

usingSystem;

publicclassGFG {

// Function to computer sum of digits in

// numbers from 1 to n. Comments use

// example of 328 to explain the code

staticintsumOfDigitsFrom1ToN(intn)

{

// base case: if n<10 return sum of

// first n natural numbers

if(n < 10)

return(n * (n + 1) / 2);

// d = number of digits minus one in

// n. For 328, d is 2

intd = (int)(Math.Log(n) / Math.Log(10));

// computing sum of digits from 1 to 10^d-1,

// d=1 a[0]=0;

// d=2 a[1]=sum of digit from 1 to 9 = 45

// d=3 a[2]=sum of digit from 1 to 99 =

// a[1]*10 + 45*10^1 = 900

// d=4 a[3]=sum of digit from 1 to 999 =

// a[2]*10 + 45*10^2 = 13500

int[] a = newint[d+1];

a[0] = 0; a[1] = 45;

for(inti = 2; i <= d; i++)

a[i] = a[i-1] * 10 + 45 *

(int)(Math.Ceiling(Math.Pow(10, i-1)));

// computing 10^d

intp = (int)(Math.Ceiling(Math.Pow(10, d)));

// Most significant digit (msd) of n,

// For 328, msd is 3 which can be obtained

// using 328/100

intmsd = n / p;

// EXPLANATION FOR FIRST and SECOND TERMS IN

// BELOW LINE OF CODE

// First two terms compute sum of digits from

// 1 to 299

// (sum of digits in range 1-99 stored in a[d]) +

// (sum of digits in range 100-199, can be

// calculated as 1*100 + a[d]

// (sum of digits in range 200-299, can be

// calculated as 2*100 + a[d]

// The above sum can be written as 3*a[d] +

// (1+2)*100

// EXPLANATION FOR THIRD AND FOURTH TERMS IN

// BELOW LINE OF CODE

// The last two terms compute sum of digits in

// number from 300 to 328. The third term adds

// 3*29 to sum as digit 3 occurs in all numbers

// from 300 to 328. The fourth term recursively

// calls for 28

return(msd * a[d] + (msd * (msd - 1) / 2) * p +

msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p));

}

// Driver Program

publicstaticvoidMain()

{

intn = 328;

Console.WriteLine("Sum of digits in numbers "+

"from 1 to "+n + " is "+

sumOfDigitsFrom1ToN(n));

}

}

// This code is contributed by shiv_bhakt.

chevron_right

filter_none

PHP

filter_none

editclose

play_arrow

linkbrightness_4code

<?php

// PHP program to compute sum of digits

// in numbers from 1 to n

// Function to computer sum of digits in

// numbers from 1 to n. Comments use

// example of 328 to explain the code

functionsumOfDigitsFrom1ToN($n)

{

// base case: if n<10 return sum of

// first n natural numbers

if($n< 10)

return($n* ($n+ 1) / 2);

// d = number of digits minus one in

// n. For 328, d is 2

$d= (int)(log10($n));

// computing sum of digits from 1

// to 10^d-1, d=1 a[0]=0;

// d=2 a[1]=sum of digit from 1 to 9 = 45

// d=3 a[2]=sum of digit from 1 to 99 =

// a[1]*10 + 45*10^1 = 900

// d=4 a[3]=sum of digit from 1 to 999 =

// a[2]*10 + 45*10^2 = 13500

$a[$d+ 1] = array();

$a[0] = 0;

$a[1] = 45;

for($i= 2; $i<= $d; $i++)

$a[$i] = $a[$i- 1] * 10 + 45 *

(int)(ceil(pow(10, $i- 1)));

// computing 10^d

$p= (int)(ceil(pow(10, $d)));

// Most significant digit (msd) of n,

// For 328, msd is 3 which can be obtained

// using 328/100

$msd= (int)($n/ $p);

// EXPLANATION FOR FIRST and SECOND

// TERMS IN BELOW LINE OF CODE

// First two terms compute sum of

// digits from 1 to 299

// (sum of digits in range 1-99 stored

// in a[d]) + (sum of digits in range

// 100-199, can be calculated as 1*100 + a[d]

// (sum of digits in range 200-299,

// can be calculated as 2*100 + a[d]

// The above sum can be written as

// 3*a[d] + (1+2)*100

// EXPLANATION FOR THIRD AND FOURTH

// TERMS IN BELOW LINE OF CODE

// The last two terms compute sum of digits in

// number from 300 to 328. The third term adds

// 3*29 to sum as digit 3 occurs in all numbers

// from 300 to 328. The fourth term recursively

// calls for 28

return($msd* $a[$d] + ($msd* (int)($msd- 1) / 2) * $p+

$msd* (1 + $n% $p) + sumOfDigitsFrom1ToN($n% $p));

}

// Driver Code

$n= 328;

echo("Sum of digits in numbers "),

"from 1 to ", $n, " is ",

sumOfDigitsFrom1ToN($n);

// This code is contributed by Sachin

?>

chevron_right

filter_none

Output:

Sum of digits in numbers from 1 to 328 is 3241

The efficient algorithm has one more advantage that we need to compute the array ‘a[]’ only once even when we are given multiple inputs.

Improvement:
Above implementation takes O(d2) time as each recursive call calculates dp[] array once again. First call takes O(d), second call takes O(d-1), third call O(d-2) and so on. We don’t need to recalculate dp[] array in each recursive call. Below is the modified implementation which works in O(d) time. Where d is number of digits in input number.

Java

filter_none

editclose

play_arrow

linkbrightness_4code

// JAVA program to compute sum of digits

// in numbers from 1 to n

importjava.io.*;

importjava.math.*;

classGFG{

// Function to computer sum of digits in

// numbers from 1 to n

staticintsumOfDigitsFrom1ToN(intn)

{

intd = (int)(Math.log10(n));

inta[] = newint[d+1];

a[0] = 0; a[1] = 45;

for(inti = 2; i <= d; i++)

a[i] = a[i-1] * 10+ 45*

(int)(Math.ceil(Math.pow(10, i-1)));

returnsumOfDigitsFrom1ToNUtil(n, a);

}

staticintsumOfDigitsFrom1ToNUtil(intn, inta[])

{

if(n < 10)

return(n * (n + 1) / 2);

intd = (int)(Math.log10(n));

intp = (int)(Math.ceil(Math.pow(10, d)));

intmsd = n / p;

return(msd * a[d] + (msd * (msd - 1) / 2) * p +

msd * (1+ n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));

}

// Driver Program

publicstaticvoidmain(String args[])

{

intn = 328;

System.out.println("Sum of digits in numbers "+

"from 1 to "+n + " is "+

sumOfDigitsFrom1ToN(n));

}

}

/*This code is contributed by Narendra Jha.*/

chevron_right

filter_none

C#

filter_none

editclose

play_arrow

linkbrightness_4code

// C# program to compute sum of digits

// in numbers from 1 to n

usingSystem;

classGFG

{

// Function to computer sum of digits in

// numbers from 1 to n

staticintsumOfDigitsFrom1ToN(intn)

{

intd = (int)(Math.Log10(n));

int[]a = newint[d+1];

a[0] = 0; a[1] = 45;

for(inti = 2; i <= d; i++)

a[i] = a[i-1] * 10 + 45 *

(int)(Math.Ceiling(Math.Pow(10, i-1)));

returnsumOfDigitsFrom1ToNUtil(n, a);

}

staticintsumOfDigitsFrom1ToNUtil(intn, int[]a)

{

if(n < 10)

return(n * (n + 1) / 2);

intd = (int)(Math.Log10(n));

intp = (int)(Math.Ceiling(Math.Pow(10, d)));

intmsd = n / p;

return(msd * a[d] + (msd * (msd - 1) / 2) * p +

msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));

}

// Driver code

publicstaticvoidMain(String []args)

{

intn = 328;

Console.WriteLine("Sum of digits in numbers "+

"from 1 to "+n + " is "+

sumOfDigitsFrom1ToN(n));

}

}

// This code contributed by Rajput-Ji

chevron_right

filter_none

Output :

Sum of digits in numbers from 1 to 328 is 3241

This article is computed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above