Given a number n, find the sum of digits in all numbers from 1 to n.
Examples:
Input: n = 5
Output: Sum of digits in numbers from 1 to 5 = 15
Input: n = 12
Output: Sum of digits in numbers from 1 to 12 = 51
Input: n = 328
Output: Sum of digits in numbers from 1 to 328 = 3241
Naive Solution: A naive solution is to go through every number x from 1 to n and compute the sum in x by traversing all digits of x. Below is the implementation of this idea.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int sumOfDigits( int );
int sumOfDigitsFrom1ToN( int n)
{
int result = 0;
for ( int x = 1; x <= n; x++)
result += sumOfDigits(x);
return result;
}
int sumOfDigits( int x)
{
int sum = 0;
while (x != 0)
{
sum += x %10;
x = x /10;
}
return sum;
}
int main()
{
int n = 328;
cout << "Sum of digits in numbers from 1 to " << n << " is "
<< sumOfDigitsFrom1ToN(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int sumOfDigitsFrom1ToN( int n)
{
int result = 0 ;
for ( int x = 1 ; x <= n; x++)
result += sumOfDigits(x);
return result;
}
static int sumOfDigits( int x)
{
int sum = 0 ;
while (x != 0 )
{
sum += x % 10 ;
x = x / 10 ;
}
return sum;
}
public static void main(String args[])
{
int n = 328 ;
System.out.println( "Sum of digits in numbers"
+ " from 1 to " + n + " is "
+ sumOfDigitsFrom1ToN(n));
}
}
|
Python3
def sumOfDigitsFrom1ToN(n) :
result = 0
for x in range ( 1 , n + 1 ) :
result = result + sumOfDigits(x)
return result
def sumOfDigits(x) :
sum = 0
while (x ! = 0 ) :
sum = sum + x % 10
x = x / / 10
return sum
n = 328
print ( "Sum of digits in numbers from 1 to" , n, "is" , sumOfDigitsFrom1ToN(n))
|
C#
using System;
public class GFG {
static int sumOfDigitsFrom1ToN( int n)
{
int result = 0;
for ( int x = 1; x <= n; x++)
result += sumOfDigits(x);
return result;
}
static int sumOfDigits( int x)
{
int sum = 0;
while (x != 0)
{
sum += x % 10;
x = x / 10;
}
return sum;
}
public static void Main()
{
int n = 328;
Console.WriteLine( "Sum of digits"
+ " in numbers from 1 to "
+ n + " is "
+ sumOfDigitsFrom1ToN(n));
}
}
|
PHP
<?php
function sumOfDigitsFrom1ToN( $n )
{
$result = 0;
for ( $x = 1; $x <= $n ; $x ++)
$result += sumOfDigits( $x );
return $result ;
}
function sumOfDigits( $x )
{
$sum = 0;
while ( $x != 0)
{
$sum += $x %10;
$x = $x /10;
}
return $sum ;
}
$n = 328;
echo "Sum of digits in numbers from"
. " 1 to " . $n . " is "
. sumOfDigitsFrom1ToN( $n );
?>
|
Javascript
<script>
function sumOfDigitsFrom1ToN(n)
{
let result = 0;
for (let x = 1; x <= n; x++)
result += sumOfDigits(x);
return result;
}
function sumOfDigits(x)
{
let sum = 0;
while (x != 0)
{
sum += x % 10;
x = parseInt(x / 10, 10);
}
return sum;
}
let n = 328;
document.write( "Sum of digits"
+ " in numbers from 1 to "
+ n + " is "
+ sumOfDigitsFrom1ToN(n));
</script>
|
C
#include<stdio.h>
int sumOfDigits( int x);
int sumOfDigitsFrom1ToN( int n);
int sumOfDigitsFrom1ToN( int n)
{
int result = 0;
for ( int x = 1; x <= n; x++)
result += sumOfDigits(x);
return result;
}
int sumOfDigits( int x)
{
int sum = 0;
while (x != 0)
{
sum += x %10;
x = x /10;
}
return sum;
}
int main()
{
int n = 328;
printf ( "Sum of digits in numbers from 1 to %d is : %d" ,n,sumOfDigitsFrom1ToN(n));
return 0;
}
|
Output
Sum of digits in numbers from 1 to 328 is 3241
Time complexity: O(N*len(N)), where len(X) gives the no. of digits in X.
Auxiliary Space: O(1)
Efficient Solution:
Above is a naive solution. We can do it more efficiently by finding a pattern.
Let us take a few examples.
sum(9) = 1 + 2 + 3 + 4 ........... + 9
= 9*10/2
= 45
sum(99) = 45 + (10 + 45) + (20 + 45) + ..... (90 + 45)
= 45*10 + (10 + 20 + 30 ... 90)
= 45*10 + 10(1 + 2 + ... 9)
= 45*10 + 45*10
= sum(9)*10 + 45*10
sum(999) = sum(99)*10 + 45*100
In general, we can compute sum(10d – 1) using the below formula
sum(10d - 1) = sum(10d-1 - 1) * 10 + 45*(10d-1)
In the 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 the 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 the above algorithm.
C++
#include<bits/stdc++.h>
using namespace std;
int sumOfDigitsFrom1ToN( 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) + sumOfDigitsFrom1ToN(n%p);
}
int main()
{
int n = 328;
cout << "Sum of digits in numbers from 1 to " << n << " is "
<< sumOfDigitsFrom1ToN(n);
return 0;
}
|
Java
import java.io.*;
import java.math.*;
class GFG{
static int sumOfDigitsFrom1ToN( int n)
{
if (n < 10 )
return (n * (n + 1 ) / 2 );
int d = ( int )(Math.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 *
( int )(Math.ceil(Math.pow( 10 , i- 1 )));
int p = ( int )(Math.ceil(Math.pow( 10 , d)));
int msd = n / p;
return (msd * a[d] + (msd * (msd - 1 ) / 2 ) * p +
msd * ( 1 + n % p) + sumOfDigitsFrom1ToN(n % p));
}
public static void main(String args[])
{
int n = 328 ;
System.out.println( "Sum of digits in numbers " +
"from 1 to " +n + " is " +
sumOfDigitsFrom1ToN(n));
}
}
|
Python3
import math
def sumOfDigitsFrom1ToN( 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) + sumOfDigitsFrom1ToN(n % p))
n = 328
print ( "Sum of digits in numbers from 1 to" ,
n , "is" ,sumOfDigitsFrom1ToN(n))
|
C#
using System;
public class GFG {
static int sumOfDigitsFrom1ToN( int n)
{
if (n < 10)
return (n * (n + 1) / 2);
int d = ( int )(Math.Log(n) / Math.Log(10));
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 *
( int )(Math.Ceiling(Math.Pow(10, i-1)));
int p = ( int )(Math.Ceiling(Math.Pow(10, d)));
int msd = n / p;
return (msd * a[d] + (msd * (msd - 1) / 2) * p +
msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p));
}
public static void Main()
{
int n = 328;
Console.WriteLine( "Sum of digits in numbers " +
"from 1 to " +n + " is " +
sumOfDigitsFrom1ToN(n));
}
}
|
PHP
<?php
function sumOfDigitsFrom1ToN( $n )
{
if ( $n < 10)
return ( $n * ( $n + 1) / 2);
$d = (int)(log10( $n ));
$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)));
$p = (int)( ceil (pow(10, $d )));
$msd = (int)( $n / $p );
return ( $msd * $a [ $d ] + ( $msd * (int)( $msd - 1) / 2) * $p +
$msd * (1 + $n % $p ) + sumOfDigitsFrom1ToN( $n % $p ));
}
$n = 328;
echo ( "Sum of digits in numbers " ),
"from 1 to " , $n , " is " ,
sumOfDigitsFrom1ToN( $n );
?>
|
Javascript
<script>
function sumOfDigitsFrom1ToN(n)
{
if (n < 10)
return (n * (n + 1) / 2);
let d = parseInt(Math.log(n) / Math.log(10), 10);
let a = new Array(d+1);
a[0] = 0; a[1] = 45;
for (let i = 2; i <= d; i++)
a[i] = a[i-1] * 10 + 45 *
parseInt(Math.ceil(Math.pow(10, i-1)), 10);
let p = parseInt(Math.ceil(Math.pow(10, d)), 10);
let msd = parseInt(n / p, 10);
return (msd * a[d] + (msd * (msd - 1) / 2) * p +
msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p));
}
let n = 328;
document.write( "Sum of digits in numbers from 1 to " + n +
" is " + sumOfDigitsFrom1ToN(n));
</script>
|
Output
Sum of digits in numbers from 1 to 328 is 3241
Time complexity: O((len(N))2)
Auxiliary Space: O(len(N))
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: The above implementation takes O(d2) time as each recursive call calculates dp[] array once again. The first call takes O(d), the second call takes O(d-1), the 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 a number of digits in the input number.
C++
#include<bits/stdc++.h>
using namespace std;
int sumOfDigitsFrom1ToNUtil( int n, int a[])
{
if (n < 10)
return (n * (n + 1) / 2);
int d = ( int )( log10 (n));
int p = ( int )( ceil ( pow (10, d)));
int msd = n / p;
return (msd * a[d] + (msd * (msd - 1) / 2) * p +
msd * (1 + n % p) +
sumOfDigitsFrom1ToNUtil(n % p, a));
}
int sumOfDigitsFrom1ToN( int n)
{
int d = ( int )( log10 (n));
int a[d + 1];
a[0] = 0; a[1] = 45;
for ( int i = 2; i <= d; i++)
a[i] = a[i - 1] * 10 + 45 *
( int )( ceil ( pow (10, i - 1)));
return sumOfDigitsFrom1ToNUtil(n, a);
}
int main()
{
int n = 328;
cout << "Sum of digits in numbers from 1 to "
<< n << " is " << sumOfDigitsFrom1ToN(n);
}
|
Java
import java.io.*;
import java.math.*;
class GFG{
static int sumOfDigitsFrom1ToN( int n)
{
int d = ( int )(Math.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 *
( int )(Math.ceil(Math.pow( 10 , i- 1 )));
return sumOfDigitsFrom1ToNUtil(n, a);
}
static int sumOfDigitsFrom1ToNUtil( int n, int a[])
{
if (n < 10 )
return (n * (n + 1 ) / 2 );
int d = ( int )(Math.log10(n));
int p = ( int )(Math.ceil(Math.pow( 10 , d)));
int msd = n / p;
return (msd * a[d] + (msd * (msd - 1 ) / 2 ) * p +
msd * ( 1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));
}
public static void main(String args[])
{
int n = 328 ;
System.out.println( "Sum of digits in numbers " +
"from 1 to " +n + " is " +
sumOfDigitsFrom1ToN(n));
}
}
|
Python3
import math
def sumOfDigitsFrom1ToN(n):
d = int (math.log(n, 10 ))
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( pow ( 10 , i - 1 )))
return sumOfDigitsFrom1ToNUtil(n, a)
def sumOfDigitsFrom1ToNUtil(n, a):
if (n < 10 ):
return (n * (n + 1 )) / / 2
d = int (math.log(n, 10 ))
p = int (math.ceil( pow ( 10 , d)))
msd = n / / p
return (msd * a[d] + (msd * (msd - 1 ) / / 2 ) * p +
msd * ( 1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a))
n = 328
print ( "Sum of digits in numbers from 1 to" ,n, "is" ,sumOfDigitsFrom1ToN(n))
|
C#
using System;
class GFG
{
static int sumOfDigitsFrom1ToN( int n)
{
int d = ( int )(Math.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 *
( int )(Math.Ceiling(Math.Pow(10, i-1)));
return sumOfDigitsFrom1ToNUtil(n, a);
}
static int sumOfDigitsFrom1ToNUtil( int n, int []a)
{
if (n < 10)
return (n * (n + 1) / 2);
int d = ( int )(Math.Log10(n));
int p = ( int )(Math.Ceiling(Math.Pow(10, d)));
int msd = n / p;
return (msd * a[d] + (msd * (msd - 1) / 2) * p +
msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));
}
public static void Main(String []args)
{
int n = 328;
Console.WriteLine( "Sum of digits in numbers " +
"from 1 to " +n + " is " +
sumOfDigitsFrom1ToN(n));
}
}
|
Javascript
<script>
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( "Sum of digits in numbers from 1 to "
+ n + " is " + sumOfDigitsFrom1ToN(n))
</script>
|
Output
Sum of digits in numbers from 1 to 328 is 3241
Time complexity: O(len(N))
Auxiliary Space: O(len(N))
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
27 Jun, 2022
Like Article
Save Article