Every time you swipe, dip, or tap your card card the card reader pulls the card information off of your card. But what happens if you swipe, dip, or tap too quickly? Enter the Luhn Algorithm...
In our previous post we broke down how a credit card number is really just a set of other numbers mashed together. The last digit is a special digit used to make sure that the card reader pulled in the rest of the information correctly. Card readers do this by running an algorithm known as the Luhn Algorithm.
The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, with credit cards being the most popular.
Steps of the Luhn Algorithm
- Starting from the rightmost digit (the check digit), and moving left, double the value of every second digit. If doubling a number results in a number greater than 9, subtract 9 from the product.
- Add all the digits together. This includes the undoubled digits and the doubled digits (after adjusting for values greater than 9 as necessary).
- Check if the total modulo 10 is equal to 0. If the total modulo 10 is zero, then the number is valid according to the Luhn formula; otherwise, it is not valid.
Example
To demonstrate the Luhn Algorithm, consider the this credit card number:
4012-8888-8888-1881
Remember from our previous post that the last digit is the Luhn score is the last digit (in this case it's "1"). So we want to run the Luhn Algorithm against the other numbers and see if we end up with "1"
Moving the other numbers each into their own column we have
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4 | 0 | 1 | 2 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 1 | 8 | 8 |
Next starting from the right and moving left we double every other number.
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8 | 0 | 2 | 2 | 16 | 8 | 16 | 8 | 16 | 8 | 16 | 8 | 2 | 8 | 16 |
Next for any columns that are 10 subtract 9:
(i.e. if we have "16" as a number we would add 16 - 9 to get 7)
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8 | 0 | 2 | 2 | 7 | 8 | 7 | 8 | 7 | 8 | 7 | 8 | 2 | 8 | 7 |
(We're almost here...)
Next we add all the values
8 + 0 + 2 + 2 + 7 + 8 + 7 + 8 + 7 + 8 + 7 + 8 + 2 + 8 + 7 = 89
Then we add our original Luhn Number (the last digit). In this case "1"
89 + 1 = 90
If the number is divisible by 10 then it is a valid card number. In this case we can see that the number (90) is divisible by 10 so we know it's a valid number. 🎉