Sum of digits is a common problem where given a number, you need to find the sum of digits of that number.
It seems to be a basic problem, but very useful in some contexts. This tutorial will help you to solve this problem, let's get started!
Table of Contents
Method 1: Using Modulo Operator and Division
The first method is to use the modulo operator (%) and division to extract each digit from the number and calculate their sum. Here's how it works:
- Initialize a variable
num
with the given number. - Initialize a variable
sum
with 0 to store the sum of digits. - Use a while loop to iterate until
num
becomes 0. - Inside the loop, calculate the remainder of
num
divided by 10 using the modulo operator and add it tosum
. - Update
num
by dividing it by 10 using integer division. - Repeat steps 4 and 5 until
num
becomes 0. - The final value of
sum
will be the sum of digits of the given number.
Let's see some examples:
Sum of Digits using Modulo Operator and Division in C++
#include <stdc++.h> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } cout << "Sum of digits: " << sum << '\n'; return 0; }
Sum of Digits using Modulo Operator and Division in Python
num = int(input('Enter a number: ')) sum = 0 while num != 0: sum += num % 10 num //= 10 print('Sum of digits:', sum)
Sum of Digits using Modulo Operator and Division in Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int num = input.nextInt(); int sum = 0; while (num != 0) { sum += num % 10; num /= 10; } System.out.println("Sum of digits: " + sum); } }
Sum of Digits using Modulo Operator and Division in JavaScript
const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout, }); readline.question("Enter a number: ", (num) => { let sum = 0; while (num != 0) { sum += num % 10; num = Math.floor(num / 10); } console.log("Sum of digits:", sum); readline.close(); });
Output:
Enter a number: 21032002 Sum of digits: 10
In this example, the given number is 21032002, so the sum of digits is 2 + 1 + 0 + 3 + 2 + 0 + 0 + 2 = 10
.
Method 2: Using Recursion
Similar to the previous method, we will use recursion to loop through the digits of the number. Here's how it works:
- Define a recursive function
sumOfDigits
that takes an integernum
as input. - Base case: If
num
is less than 10, returnnum
as the sum of digits. - Recursive case: Calculate the sum of digits of
num
by adding the last digit (obtained using the modulo operator) to the sum of digits of the remaining digits (obtained using integer division). - Return the sum of digits.
Sum of Digits using Recursion in C++
#include <stdc++.h> using namespace std; int sumOfDigits(int num) { if (num < 10) { return num; } return num % 10 + sumOfDigits(num / 10); } int main() { int num; cout << "Enter a number: "; cin >> num; cout << "Sum of digits: " << sumOfDigits(num) << '\n'; return 0; }
Sum of Digits using Recursion in Python
def sumOfDigits(num): if num < 10: return num return num % 10 + sumOfDigits(num // 10) num = int(input('Enter a number: ')) print('Sum of digits: ', sumOfDigits(num))
Another quick and efficient way:
num = int(input('Enter a number: ')) print('Sum of digits: ', sum(map(int, str(num))))
Sum of Digits using Recursion in Java
import java.util.Scanner; public class Main { public static int sumOfDigits(int num) { if (num < 10) { return num; } return num % 10 + sumOfDigits(num / 10); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int num = input.nextInt(); System.out.println("Sum of digits: " + sumOfDigits(num)); } }
Sum of Digits using Recursion in JavaScript
const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout, }); function sumOfDigits(num) { if (num < 10) { return num; } return (num % 10) + sumOfDigits(Math.floor(num / 10)); } readline.question("Enter a number: ", (num) => { console.log("Sum of digits:", sumOfDigits(num)); readline.close(); });
Output:
Enter a number: 9032000 Sum of digits: 14
In this example, we define a recursive function sumOfDigits
and given the number is 9032000, so the sum of digits is 9 + 0 + 3 + 2 + 0 + 0 + 0 = 14
.
Use Cases
Maybe you know or not, but such simple task like sum of digits is very useful in some contexts:
- Validating credit card numbers: The sum of digits of a credit card number can be used to check its validity.
- Checking divisibility: The sum of digits of a number can be used to determine if it is divisible by a certain number, for example, a number is divisible by 3 if the sum of its digits is divisible by 3.
- Cryptography: The sum of digits can be used in cryptographic algorithms to generate secure keys.
The Luhn Algorithm
The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the US, and Canadian Social Insurance Numbers. To learn more about the Luhn algorithm, you can read this article.
In the scope of this tutorial, we will learn how to use the Luhn algorithm to validate a simple 16-digit credit card number. Here's how it works:
- Multiply every digit in odd positions (1st, 3rd, 5th, ...) by 2.
- If the result of the multiplication is greater than 9, subtract 9 from it (or equivalently, add the two digits of the result).
- Add all the digits together.
- If the sum is divisible by 10, the number is valid.
See the following example:

Luhn Algorithm in C++
#include <stdc++.h> using namespace std; bool luhnAlgorithm(string cardNumber) { int sum = 0; for (int i = 0; i < cardNumber.length(); i++) { int digit = cardNumber[i] - '0'; if (i % 2 == 0) { digit *= 2; if (digit > 9) { digit -= 9; } } sum += digit; } return sum % 10 == 0; } int main() { string cardNumber; cout << "Enter a credit card number: "; cin >> cardNumber; if (luhnAlgorithm(cardNumber)) { cout << "Valid credit card number\n"; } else { cout << "Invalid credit card number\n"; } return 0; }
Luhn Algorithm in Python
def luhnAlgorithm(cardNumber): sum = 0 for i in range(len(cardNumber)): digit = int(cardNumber[i]) if i % 2 == 0: digit *= 2 if digit > 9: digit -= 9 sum += digit return sum % 10 == 0 cardNumber = input('Enter a credit card number: ') if luhnAlgorithm(cardNumber): print('Valid credit card number') else: print('Invalid credit card number')
Luhn Algorithm in Java
import java.util.Scanner; public class Main { public static boolean luhnAlgorithm(String cardNumber) { int sum = 0; for (int i = 0; i < cardNumber.length(); i++) { int digit = cardNumber.charAt(i) - '0'; if (i % 2 == 0) { digit *= 2; if (digit > 9) { digit -= 9; } } sum += digit; } return sum % 10 == 0; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a credit card number: "); String cardNumber = input.nextLine(); if (luhnAlgorithm(cardNumber)) { System.out.println("Valid credit card number"); } else { System.out.println("Invalid credit card number"); } } }
Luhn Algorithm in JavaScript
const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout, }); function luhnAlgorithm(cardNumber) { let sum = 0; for (let i = 0; i < cardNumber.length; i++) { let digit = parseInt(cardNumber[i]); if (i % 2 == 0) { digit *= 2; if (digit > 9) { digit -= 9; } } sum += digit; } return sum % 10 == 0; } readline.question("Enter a credit card number: ", (cardNumber) => { if (luhnAlgorithm(cardNumber)) { console.log("Valid credit card number"); } else { console.log("Invalid credit card number"); } readline.close(); });
Output:
Enter a credit card number: 4137894711755904 Valid credit card number
Hope you find this useful, see you in the next tutorial!