Monday, October 6, 2008

How does the Luhn Test work?

The code to find credit cards in a block of text is available on GitHub: Credit Card

The Luhn Test or Luhn Algorithm is a test of a series of numbers to determine if they could be a valid credit card. The algorithm is fairly simple and I'll demonstrate it with 4 digits.

The number to test: 4 - 5 - 6 - 7

Step 1: Starting from the right, double every second digit:

8 - 5 - 12 - 7

Step 2: If the result of the doubling ends up with a 2 digit number then add those 2 digits together.

8 - 5 - 3 - 7

Step 3: Add all the digits together.

8 + 5 + 3 + 7 = 23

Step 4: Mod the number against 10.

23 % 10 = 3

Step 5: Is the number exactly divisible by 10?

i.e. does 3 equal 0?

If it is (exactly divisible by 10) then it passes the Luhn Test and could be a credit card number.

1 comment: