DEV Community

Cover image for Understanding the Luhn Algorithm
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Understanding the Luhn Algorithm

The Luhn Algorithm is a mathematical checksum formula used to validate identification numbers, especially credit and debit card numbers. It helps detect common typing mistakes when entering numerical information.

It was developed by Hans Peter Luhn, an IBM researcher, and is widely used in payment systems.

What Is the Luhn Algorithm?

It works by:

Starting from the rightmost digit.

Doubling every second digit.

Subtracting 9 from doubled values greater than 9.

Adding all the resulting digits.

Checking whether the final sum is divisible by 10.

If the final sum is divisible by 10, the number passes the Luhn validation.

How Does the Luhn Algorithm Work?

Let's understand the algorithm with an example.

Consider this sample number:

79927398713

Follow these steps:

Step 1: Start from the right side

Start reading the digits from right to left.

Step 2: Double every second digit

Leave the rightmost digit unchanged and double every second digit moving towards the left.

Step 3: Subtract 9

If a doubled digit becomes greater than 9, subtract 9 from it.

For example:

7 × 2 = 14

14 − 9 = 5

Step 4: Calculate the total

Add all the resulting digits.

Step 5: Check the remainder

If the total is divisible by 10, the number passes the Luhn check.

For our example:

Total = 70

70 % 10 = 0

Therefore, the number passes the Luhn validation.

Advantages of the Luhn Algorithm

Easy to understand and implement.

Requires very little computation.

Detects many common single-digit typing errors.

Helps identify many accidental digit transpositions.

Can be implemented in programming languages such as Java, Python, C, and JavaScript.

Limitations of the Luhn Algorithm

Although the Luhn Algorithm is useful, it has some limitations:

It does not verify whether a credit card actually exists.

It does not check whether a card is active.

It does not verify the available balance.

It does not prevent credit card fraud.

Some combinations of digit changes can still pass the checksum.

Top comments (0)