Luhn’s algorithm to validate credit / debit card Numbers

Akshay Mohite
2 min readOct 7, 2018

--

Did you ever come across an error shown while paying digitally on a payment gateway page, saying the Credit Card number is not valid?

Usually this happens if you enter an incorrect credit / debit card number in the field. Ever wondered, how do they validate if the credit card number is valid?

Here is the answer to that question. It’s Luhn’s Algorithm.

What is Luhn’s Algorithm?

The Luhn algorithm or Luhn formula, also known as the “modulus 10” or “mod 10” algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers

Source: Wikipedia

Let’s consider number: 3141 4352 72

The formula is simple:

  1. Start from the right side. Double every other number.
    3141 4352 72 → 6181 83102 142
  2. Sum the resulting number if it is a double digit.
    6181 83102 142 → 6181 8312 52
  3. Sum the digits from resulting number from step 2.
    6+1+8+1+8+3+1+2+5+2 = 37
  4. Find out Modulus 10 of the resulting number.
    37%10 = 7
  5. If the modulus 10 is equal to 0. The number is a valid card number.

Luhn’s Algorithm implementation in Ruby:

The program below implements an algorithm discussed above.

Various (C / Python) implementations of the algorithm can be found on the Luhn_algorithm wiki page.

--

--