What is Luhn’s Algorithm ? How to use it to validate credit card number ?

0 / 976 What is Luhn’s Algorithm?

Luhn Algorithm is also known as modulo 10 algorithm or modulus 10 formula. It’s a checksum which is used to validate credit card, IMEI and various national identification numbers from across the globe. It’s named after an IBM scientist Hans Peter Luhn.

Overview

Luhn test is used by various merchants and credit card numbers to check if the provided credit card number is valid or not. The algorithm has 5 simple steps as listed below

• Reverse the digits in the given credit card number string.
• Take first, third and every odd digit from the string and sum them up to get partial sum s1.
• Take second, fourth and every other even digit and list them together.
• Multiply each of the digits listed in step 3 by 2 and sum the digits if the result is greater than 9. Then add the final digits together to get second half of the partial sum s2.
• Sum s1 and s2 and take the modulo of the sum by 10. If the result is zero, given number passes the Luhn test, if not, it fails and is an invalid number.

Let’s try to understand the above steps using an example. Consider a number, 5521760712355716.

Reverse the above number to get 6175532170671255

s1 = sum of odd digits = 6+7+5+2+7+6+1+5 = 39————————-(1)

List of even digits = 1,5,3,1,0,7,2,5

Multiply each of the above digits by 2 to get 2,10,6,2,0,14,4,10.

In the above digit set, sum the digits together for all the numbers > 9 to get 2, 1 (1+0), 6, 2, 0, 5 (1+4), 4, 1 (1+0) i.e 2,1,6,2,0,5,4,1.

Sum all the numbers thus obtained, together to get s2 = 2+1+6+2+0+5+4+1 = 21———-(2)

Summing equations 1 & 2, we get Sum = 39+21 = 60 which ends in zero and hence is modulo 10 is zero , so it passes the Luhn test.

/* Luhn Algorithm implementation using Javascript */

function reverseString(str) {
return str.split("").reverse().join("");
}

function check() {
var number = document.getElementById('number').value,
oddIndex = 0,
evenIndex = 1,
s1 = s2 = 0;
number = reverseString(number);
while (oddIndex < number.length) {
console.log('odd ', number[oddIndex]);
s1 += parseInt(number[oddIndex]);
oddIndex += 2;
}
while (evenIndex < number.length) {
s2 += calculateSumOfDigits(number[evenIndex] * 2);
console.log('even ', number[evenIndex]);
evenIndex += 2;
}
if ((s1 + s2) % 10 === 0) {
document.getElementById('result').innerHTML = 'Number is valid as it passed the Luhn Test';
} else {
document.getElementById('result').innerHTML = 'Invalid number as it failed the Luhn Test';
}
console.log('Result ', s1 + s2)
}

function calculateSumOfDigits(n) {
var digit = 0,
sum = 0;
while (n != 0) {
digit = n % 10;
sum += digit;
n = parseInt(n / 10);
}
return sum;
}

Below is a demo:

Disclaimer: None of the data entered on this site or blog is stored by us. It’s for demonstration purpose only.