Home//

Sum of Digits of a Number and the Luhn Algorithm

# Sum of Digits of a Number and the Luhn Algorithm 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!

## 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:

1. Initialize a variable `num` with the given number.
2. Initialize a variable `sum` with 0 to store the sum of digits.
3. Use a while loop to iterate until `num` becomes 0.
4. Inside the loop, calculate the remainder of `num` divided by 10 using the modulo operator and add it to `sum`.
5. Update `num` by dividing it by 10 using integer division.
6. Repeat steps 4 and 5 until `num` becomes 0.
7. 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++

sum-of-digits.cpp
``````#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

sum-of-digits.py
``````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

SumOfDigits.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

sum-of-digits.js
``````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);
});
``````

Output:

shell
``````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:

1. Define a recursive function `sumOfDigits` that takes an integer `num` as input.
2. Base case: If `num` is less than 10, return `num` as the sum of digits.
3. 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).
4. Return the sum of digits.

### Sum of Digits using Recursion in C++

sum-of-digits.cpp
``````#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

sum-of-digits.py
``````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));
});
``````

Output:

shell
``````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:

1. Multiply every digit in odd positions (1st, 3rd, 5th, ...) by 2.
2. If the result of the multiplication is greater than 9, subtract 9 from it (or equivalently, add the two digits of the result).
3. Add all the digits together.
4. 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");
}

});
``````

Output:

shell
``````Enter a credit card number: 4137894711755904
Valid credit card number
``````

Hope you find this useful, see you in the next tutorial! Minh Vu

Software Engineer

Hi guys, I'm the author of WiseCode Blog. I mainly work with the Elastic Stack and build AI & Python projects. I also love writing technical articles, hope you guys have good experience reading my blog! Minh Vu

Software Engineer

Do not find what you need?

Send us a message.