General Algorithm for sum of digits in a given number:
Get the number
Declare a variable to store the sum and set it to 0
Repeat the next two steps till the number is not 0
Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.
Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
Print or return the sum
Below are the solutions to get sum of the digits. 1. Iterative:
C++
// C program to compute sum of digits in
// number.
#include <iostream>
usingnamespacestd;
/* Function to get sum of digits */
classgfg {
public:
intgetSum(intn)
{
intsum = 0;
while(n != 0) {
sum = sum + n % 10;
n = n / 10;
}
returnsum;
}
};
// Driver code
intmain()
{
gfg g;
intn = 687;
cout << g.getSum(n);
return0;
}
// This code is contributed by Soumik
C
// C program to compute sum of digits in
// number.
#include <stdio.h>
/* Function to get sum of digits */
intgetSum(intn)
{
intsum = 0;
while(n != 0) {
sum = sum + n % 10;
n = n / 10;
}
returnsum;
}
// Driver code
intmain()
{
intn = 687;
printf(" %d ", getSum(n));
return0;
}
Java
// Java program to compute
// sum of digits in number.
importjava.io.*;
classGFG {
/* Function to get sum of digits */
staticintgetSum(intn)
{
intsum = 0;
while(n != 0) {
sum = sum + n % 10;
n = n / 10;
}
returnsum;
}
// Driver code
publicstaticvoidmain(String[] args)
{
intn = 687;
System.out.println(getSum(n));
}
}
// This code is contributed by Gitanjali
Python3
# Python 3 program to
# compute sum of digits in
# number.
# Function to get sum of digits
defgetSum(n):
sum=0
while(n !=0):
sum=sum+int(n %10)
n =int(n/10)
returnsum
# Driver code
n =687
print(getSum(n))
C#
// C# program to compute
// sum of digits in number.
usingSystem;
classGFG {
/* Function to get sum of digits */
staticintgetSum(intn)
{
intsum = 0;
while(n != 0) {
sum = sum + n % 10;
n = n / 10;
}
returnsum;
}
// Driver code
publicstaticvoidMain()
{
intn = 687;
Console.Write(getSum(n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP Code to compute sum
// of digits in number.
// Function to get
// $sum of digits
functiongetsum($n)
{
$sum= 0;
while($n!= 0)
{
$sum= $sum+ $n% 10;
$n= $n/10;
}
return$sum;
}
// Driver Code
$n= 687;
$res= getsum($n);
echo("$res");
// This code is contributed by
// Smitha Dinesh Semwal.
?>
Javascript
<script>
// Javascript program to compute sum of digits in
// number.
/* Function to get sum of digits */
functiongetSum(n)
{
varsum = 0;
while(n != 0) {
sum = sum + n % 10;
n = parseInt(n / 10);
}
returnsum;
}
// Driver code
varn = 687;
document.write(getSum(n));
</script>
Output
21
Time Complexity : O(logn)
Auxiliary Space: O(1)
How to compute in asingle line? The below function has three lines instead of one line, but it calculates the sum in line. It can be made one-line function if we pass the pointer to sum.
C++
#include <iostream>
usingnamespacestd;
/* Function to get sum of digits */
classgfg {
public:
intgetSum(intn)
{
intsum;
/* Single line that calculates sum */
for(sum = 0; n > 0; sum += n % 10, n /= 10)
;
returnsum;
}
};
// Driver code
intmain()
{
gfg g;
intn = 687;
cout << g.getSum(n);
return0;
}
// This code is contributed by Soumik
C
#include <stdio.h>
/* Function to get sum of digits */
intgetSum(intn)
{
intsum;
/* Single line that calculates sum */
for(sum = 0; n > 0; sum += n % 10, n /= 10)
;
returnsum;
}
// Driver code
intmain()
{
intn = 687;
printf(" %d ", getSum(n));
return0;
}
Java
// Java program to compute
// sum of digits in number.
importjava.io.*;
classGFG {
/* Function to get sum of digits */
staticintgetSum(intn)
{
intsum;
/* Single line that calculates sum */
for(sum = 0; n > 0; sum += n % 10, n /= 10)
;
returnsum;
}
// Driver code
publicstaticvoidmain(String[] args)
{
intn = 687;
System.out.println(getSum(n));
}
}
// This code is contributed by Gitanjali
Python3
# Function to get sum of digits
defgetSum(n):
sum=0
# Single line that calculates sum
while(n > 0):
sum+=int(n %10)
n =int(n/10)
returnsum
# Driver code
n =687
print(getSum(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to compute
// sum of digits in number.
usingSystem;
classGFG {
staticintgetSum(intn)
{
intsum;
/* Single line that calculates sum */
for(sum = 0; n > 0; sum += n % 10, n /= 10)
;
returnsum;
}
// Driver code
publicstaticvoidMain()
{
intn = 687;
Console.Write(getSum(n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP Code for Sum the
// digits of a given number
// Function to get sum of digits
functiongetsum($n)
{
// Single line that calculates $sum
for($sum= 0; $n> 0; $sum+= $n% 10,
$n/= 10);
return$sum;
}
// Driver Code
$n= 687;
echo(getsum($n));
// This code is contributed by
// Smitha Dinesh Semwal.
?>
Javascript
<script>
// Javascript program to compute
// sum of digits in number.
// Function to get sum of digits
functiongetSum(n)
{
let sum;
// Single line that calculates sum
for(sum = 0; n > 0;
sum += n % 10,
n = parseInt(n / 10))
;
returnsum;
}
// Driver code
let n = 687;
document.write(getSum(n));
// This code is contributed by subhammahato348
</script>
Output
21
Time Complexity : O(logn)
Auxiliary Space: O(1)
2. Recursive Thanks to Ayesha for providing the below recursive solution.
Algorithm :
1) Get the number
2) Get the remainder and pass the next remaining digits
3) Get the rightmost digit of the number with help of the remainder '%' operator by dividing it by 10 and add it to sum.
Divide the number by 10 with help of '/' operator to remove the rightmost digit.
4) Check the base case with n = 0
5) Print or return the sum
When the number of digits of that number exceeds 1019 , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)
Below is the implementation of the above approach
C++14
// C++ implementation of the above approach
#include <iostream>
usingnamespacestd;
intgetSum(string str)
{
intsum = 0;
// Traversing through the string
for(inti = 0; i < str.length(); i++) {
// Since ascii value of
// numbers starts from 48
// so we subtract it from sum
sum = sum + str[i] - 48;
}
returnsum;
}
// Driver Code
intmain()
{
string st = "123456789123456789123422";
cout << getSum(st);
return0;
}
Java
// Java implementation of the above approach
importjava.io.*;
classGFG {
staticintgetSum(String str)
{
intsum = 0;
// Traversing through the string
for(inti = 0; i < str.length(); i++) {
// Since ascii value of
// numbers starts from 48
// so we subtract it from sum
sum = sum + str.charAt(i) - 48;
}
returnsum;
}
// Driver Code
publicstaticvoidmain(String[] args)
{
String st = "123456789123456789123422";
System.out.print(getSum(st));
}
}
// This code is contributed by Dharanendra L V.
Python3
# Python implementation of the above approach
defgetSum(n):
# Initializing sum to 0
sum=0
# Traversing through string
fori inn:
# Converting char to int
sum=sum+int(i)
returnsum
n ="123456789123456789123422"
print(getSum(n))
C#
// C# implementation of the above approach
usingSystem;
publicclassGFG {
staticintgetSum(String str)
{
intsum = 0;
// Traversing through the string
for(inti = 0; i < str.Length; i++) {
// Since ascii value of
// numbers starts from 48
// so we subtract it from sum
sum = sum + str[i] - 48;
}
returnsum;
}
// Driver Code
staticpublicvoidMain()
{
String st = "123456789123456789123422";
Console.Write(getSum(st));
}
}
// This code is contributed by Dharanendra L V.
Javascript
<script>
// Javascript implementation of the above approach
functiongetSum(str)
{
let sum = 0;
// Traversing through the string
for(let i = 0; i < str.length; i++)
{
// Since ascii value of
// numbers starts from 48
// so we subtract it from sum
sum = sum + parseInt(str[i]);
}
returnsum;
}
// Driver Code
let st = "123456789123456789123422";
document.write(getSum(st));
// This code is contributed by subhammahato348.
</script>
PHP
<?php
// PHP implementation of the above approach
// PHP Code for Sum the
// digits of a given number
// Function to get sum of digits
functiongetsum($str)
{
$sum= 0;
// Traversing through the string
for($i= 0; $i<strlen($str); $i++) {
//Converting char to int
$sum= $sum+ (int)$str[$i];
}
return$sum;
}
// Driver Code
$str= "123456789123456789123422";
echo(getsum($str));
// This code is contributed by aadityapburujwale
?>
Output
104
Time Complexity : O(logn)
Auxiliary Space: O(1)
4. Using Tail Recursion
This problem can also be solved using Tail Recursion. Here is an approach to solving it.
1. Add another variable “Val” to the function and initialize it to ( val = 0 )
2. On every call to the function add the mod value (n%10) to the variable as “(n%10)+val” which is the last digit in n. Along with pass the variable n as n/10.
3. So on the First call it will have the last digit. As we are passing n/10 as n, It follows until n is reduced to a single digit.
4. n<10 is the base case so When n < 10, then add the n to the variable as it is the last digit and return the val which will have the sum of digits
C++
// C++ program for the above approach
#include <iostream>
usingnamespacestd;
// Function to check sum of digit using tail recursion
intsum_of_digit(intn, intval)
{
if(n < 10) {
val = val + n;
returnval;
}
returnsum_of_digit(n / 10, (n % 10) + val);
}
// Driver code
intmain()
{
intnum = 12345;
intresult = sum_of_digit(num, 0);
cout << "Sum of digits is "<< result;
return0;
}
// This code is contributed by subhammahato348
C
// C program for the above approach
#include <stdio.h>
// Function to check sum of digit using tail recursion
intsum_of_digit(intn, intval)
{
if(n < 10) {
val = val + n;
returnval;
}
returnsum_of_digit(n / 10, (n % 10) + val);
}
// Driver code
intmain()
{
intnum = 12345;
intresult = sum_of_digit(num, 0);
printf("Sum of digits is %d", result);
return0;
}
// This code is contributed by Sania Kumari Gupta
Java
// Java program for the above approach
importjava.io.*;
importjava.lang.*;
importjava.util.*;
classsum_of_digits {
// Function to check sum
// of digit using tail recursion
staticintsum_of_digit(intn, intval)
{
if(n < 10) {
val = val + n;
returnval;
}
returnsum_of_digit(n / 10, (n % 10) + val);
}
// Driven Program to check above
publicstaticvoidmain(String args[])
{
intnum = 12345;
intresult = sum_of_digit(num, 0);
System.out.println("Sum of digits is "+ result);
}
}
Python3
# Python3 program for the above approach
# Function to check sum
# of digit using tail recursion
defsum_of_digit(n, val):
if(n < 10):
val =val +n
returnval
returnsum_of_digit(n //10, (n %10) +val)
# Driver code
num =12345
result =sum_of_digit(num, 0)
print("Sum of digits is", result)
# This code is contributed by subhammahato348
C#
// C# program for the above approach
usingSystem;
classGFG{
// Function to check sum
// of digit using tail recursion
staticintsum_of_digit(intn, intval)
{
if(n < 10)
{
val = val + n;
returnval;
}
returnsum_of_digit(n / 10, (n % 10) + val);
}
// Driver code
publicstaticvoidMain()
{
intnum = 12345;
intresult = sum_of_digit(num, 0);
Console.Write("Sum of digits is "+ result);
}
}
// This code is contributed by subhammahato348
Javascript
<script>
// Javascript program for the above approach
// Function to check sum
// of digit using tail recursion
functionsum_of_digit(n, val)
{
if(n < 10)
{
val = val + n;
returnval;
}
returnsum_of_digit(parseInt(n / 10),
(n % 10) + val);
}
// Driver code
let num = 12345;
let result = sum_of_digit(num, 0);
document.write("Sum of digits is "+ result);
// This code is contributed by subhammahato348
</script>
Output
Sum of digits is 15
Time Complexity : O(logn)
Auxiliary Space: O(logn)
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy