Credit Card Validation Using Luhn Algorithm

Hassan Shulli
3 min readJun 26, 2019

--

Luhn algorithm is a checksum formula used to validate credit card numbers. It was invented by Peter luhn, a German IBM reseacher, in 1954 to protect against mistypes or reversed figures when typing credit card numbers.

How does it work?

Step 1)

Starting with the second number from the right (underlined below in blue), double every other digit as shown below.

Double Every Other Digit

Step 2)

Calculate the sum of all the numbers that were left behind(not underlined above) in the previous step and add them to the numbers that were doubled (numbers underlined above).

Result Of The Summation

Step 3)

Calculate modulo 10 (divide by 10 and take the remainder) of the result that was computed in the previous step. If the result of the modulo operation is zero, the credit card number is valid. If the result of the modulo is anything other than zero then the number is an invalid credit card number. In our case the result is as follows:

Modulo 10 shows the number is valid

Lets look at a slightly more complex example that covers a rule that we haven’t mentioned yet.

Double Every Other Digit

In this example, doubling 9 and 7 produces two digit number (18 and 14) as shown above. We need to follow an extra step when this happens and that is to convert the two digit numbers in to a one digit number by summing up the two digits. Therefore 18 becomes 1 + 8 = 9 and 14 becomes 1 + 4 = 5.

Summation
Modulo 10

The summation of the doubled up digits with the digits left behind produces 70. Calculating modulo 10 of 70 shows that the card number is valid.

Now that you understand how this algorithm works you can add it to your application to give the user instant feedback if they mistype their credit card number.

Thank you for taking the time to read this article.

--

--

Hassan Shulli

A software engineer with a passion for developing great products. I also enjoy working on open source projects and writing software engineering articles.