I was reminded today of the “Luhn algorithm” or Mod 10 as it’s sometimes known.
Wikipedia has a pretty solid explanation of it that you can check out below.
https://en.wikipedia.org/wiki/Luhn_algorithm
On that same page is some pseudo code to check if the number being evaluated conforms to mod 10.
function checkLuhn(string purportedCC) {
int nDigits := length(purportedCC)
int sum := 0;
int parity := (nDigits-2)modulus 2
for i from 0 to nDigits - 1 {
int digit := integer(purportedCC[i])
if i modulus 2 = parity
digit := digit × 2
if digit > 9
digit := digit - 9
sum := sum + digit
}
return (sum modulus 10) = 0
}
I had to use this function in a previous life to validate credit card numbers on a major Australian Banks website! Previous to doing that, I had no idea I could execute on, or even comprehend such a thing, the word “algorithm” sounds scary. But it’s really not that difficult to understand, and is more simple than I prevously imagined a credit card number to be.
This is how you validate a Credit Card Number
Example credit card number
4 0 1 2 8 8 8 8 8 8 8 8 1 8 8 1
Step 1 – Starting at the second last number, at every second number, double the number
4 | 0 | 1 | 2 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 1 | 8 | 8 | 1 |
x2 | x2 | x2 | x2 | x2 | x2 | x2 | x2 | ||||||||
8 | 2 | 16 | 16 | 16 | 16 | 2 | 16 |
Step 2 – When you double the number, if the result is a two digit number, like 16 in the previous step, then take the two digits of that number, and add them together ie:- take 16, add 1 to 6 ie:- 1+6 = 7
4 | 0 | 1 | 2 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 1 | 8 | 8 | 1 |
x2 | x2 | x2 | x2 | x2 | x2 | x2 | x2 | ||||||||
8 | 2 | 16 | 16 | 16 | 16 | 2 | 16 | ||||||||
1+6 | 1+6 | 1+6 | 1+6 | 1+6 | |||||||||||
8 | 2 | 7 | 7 | 7 | 7 | 2 | 7 |
Step 3 – Take every other number from the top row, and insert them next to the numbers in the previous step.
4 | 0 | 1 | 2 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 8 | 1 | 8 | 8 | 1 |
x2 | x2 | x2 | x2 | x2 | x2 | x2 | x2 | ||||||||
8 | 2 | 16 | 16 | 16 | 16 | 2 | 16 | ||||||||
– | – | 1+6 | 1+6 | 1+6 | 1+6 | – | 1+6 | ||||||||
8 | 2 | 7 | 7 | 7 | 7 | 2 | 7 | ||||||||
8 | 0 | 2 | 2 | 7 | 8 | 7 | 8 | 7 | 8 | 7 | 8 | 2 | 8 | 7 | 1 |
Step 4 – Add all the digits in the sequence, if the final sum can be evenly divided by 10, then it is a valid credit card number!
8+0+2+2+7+8+7+8+7+8+7+8+2+8+7+1 = 90