Not that you would ever need to do it, but it would be cool to look at a credit card number and be like, “Yup, it’s valid” or, “Meh, this wont work.” I’ve heard people show this one off as a magic trick in parties as well (although, make sure the party airs on the side of being a bit nerdy or you may soon find yourself boring people). The magic behind this whole credit-card validation thing, regardless of whether you do it in your mind, or some shopping outlet, is Luhn algorithm.
As code, the algorithm looks like this:
return [int(d) for d in str(n)]
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = 0
checksum += sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d*2))
return checksum % 10
return luhn_checksum(card_number) == 0
Before we attempt to understand what this algorithm does, let’s take a look at what the numbers of a credit card actually mean.
The first digit is always the Industry Identifier. It determines the category of the organization that issued the card.
1 and 2 are Airlines
3 is Travel and Entertainment
4 and 5 are Banking and Financial
6 is Merchandising and Banking
7 is Petroleum
8 is Telecommunications
9 is a National assignment
The first 6 digits combined are the Issuer Identification Number. This combination will identify the exact institution that issued the card. For instance,
Amex: 34xxxx, 37xxxx
Discover: 6011xx, 644xxx, 65xxxx
Mastercard: 51xxxx – 55xxxx
To put this in perspective, 375863 is a British Airways American Express Platinum Card.
The 7th digit up until the last (excluding the last digit) are the cardholder’s account number. And the final digit is the checksum. This is what the Luhn algorithm uses to validate a card.
Alright, now let’s see how we can do this in our head. Let’s take the above credit card number.
5412 3456 7890 1234
Now let us pick out every every other digit from the right, and then double them.
5, 1 3, 5 7, 9 1, 3 => 10, 2 6, 10 14, 18 2, 6
Now take the remaining numbers, the ones that were not doubled, and add them to the doubled ones.
4, 2 4, 6 8, 0 2, 4 => 4+2+5+(1+ 0)+2 4+6+6+(1+0) 8+0+(1+4)+(1+8) 2+4+2+6
Notice on the right hand side, how I’ve added each digit of the double digit numbers as well? So finally, the sum is:
If this final sum is divisible by 10, then the card is valid, else it is invalid. So in our case, since, 67 is not divisible by 10, this card is invalid.
Well that is about it… Happy validation!