How to validate a Credit Card Number – The Luhn algorithm (mod 10)

Uncategorized | Tagged

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

4012888888881881
x2x2x2x2x2x2x2x2
8216161616216
For example: as you can see above, 8×2 = 16 etc.

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

4012888888881881
x2x2x2x2x2x2x2x2
8216161616216
1+61+61+61+61+6
82777727
For example: take 16, add 1 to 6 ie: 16 becomes 1+6 = 7

Step 3 – Take every other number from the top row, and insert them next to the numbers in the previous step.

4012888888881881
x2x2x2x2x2x2x2x2
8216161616216
1+61+61+61+61+6
82777727
8022787878782871
Form example: column two is 0, column four is 2

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