Lably
Skip to content

Luhn algorithm

Simple checksum formula

  • 4 min read
  • 5 chapters

Related on Lably

Through Modular arithmetic, Algorithm and Modulo

The algorithm is in the public domain and is in wide use today. It is specified in ISO/IEC 7812-1. It is not intended to be a cryptographically secure hash function; it was designed to protect against accidental errors, not malicious attacks. Most credit card numbers and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers.

Description

The check digit is computed as follows:

  1. Drop the check digit from the number (if it's already present). This leaves the payload.
  2. Start with the payload digits and double every second digit (a digit in an odd position in reversed order) when numbered from the left.
  3. Process the payload from right-to-left. If a doubled digit exceeds 9, subtract 9 from the digit.
  4. Sum all the resulting digits (including the ones that were not doubled).
  5. The check digit is calculated by (10−(smod10))mod10, where s is the sum from step 4. This is the smallest number (possibly zero) that must be added to s to make a multiple of 10.
  6. Other valid formulas giving the same value are 9−((s+9)mod10), (10−s)mod10, and 10⌈s/10⌉−s. Note that the formula (10−s)mod10 will not work in all environments due to differences in how negative numbers are handled by the modulo operation.

Example for computing check digit

Assume an example of an account number 1789372997 (just the "payload", check digit not yet included):

The sum of the resulting digits is 56.

The check digit is equal to (10−(56mod10))mod10=4.

This makes the full account number read 17893729974.

Example for validating check digit

  1. Drop the check digit (last digit) of the number to validate. (e.g. 17893729974 → 1789372997)
  2. Calculate the check digit (see above)
  3. Compare your result with the original check digit. If both numbers match, the result is valid. (e.g. (givenCheckDigit = calculatedCheckDigit) ⇔ (isValidCheckDigit)).

Sign in to keep reading

4 more chapters are free with a Lably account.

More in From Lably lessons