RightSignal
1 of 4

Your RightSignal

Concept of the day1 / 3

Luhn algorithm

The concept

How a checkout form spots a wrong card number before asking the bank

The last digit of a card number is a check digit, worked out from all the others. The Luhn algorithm is the rule for that digit. A form can rerun the rule on what you typed and spot most typos instantly.

The rule: start at the rightmost digit and double every second digit going left. If a doubled digit is over 9, subtract 9. Add up all the digits. The number is valid only if the total ends in 0.

Take Stripe's test card 4242 4242 4242 4242. The 4s land on the doubled positions and become 8s. The 2s stay as they are. The total is 80, which ends in 0, so the number passes.

What it’s forChecks whether a card or ID number is internally consistent.

(Σ dᵢ′) mod 10 = 0

dᵢ′
each digit, with every second one from the right doubled (minus 9 if the result is over 9)
Σ
add all of those values together
mod 10
the remainder after dividing by 10, i.e. the last digit of the total

What it givesA yes or no: does the number pass the check, or does it contain a typo?

  1. Eight 4s doubled: 8 × 8 = 64
  2. Eight 2s kept: 8 × 2 = 16
  3. 64 + 16 = 80, and 80 mod 10 = 0, so it's valid