1 min read

Luhn Algorithm

Luhn Algorithm

The Luhn algorithm is a checksum algorithm used to detect errors in identification numbers, such as credit card numbers and IMEI numbers. It is a modulo-10 algorithm, which means that the sum of the digits in the number is divided by 10, and the remainder is used to determine whether the number is valid.

Algorithm:

  1. Double every other digit: Starting from the rightmost digit, double every other digit in the number.
  2. Sum the digits: Add all the digits in the number, including the doubled digits.
  3. Modulo 10: Divide the sum by 10 and take the remainder.
  4. Check for equality: If the remainder is 0, the number is valid. Otherwise, it is not.

Example:

Given the credit card number 1234 5678 9012:

  1. Double every other digit: 1234 5678 9012 becomes 1234 1168 9012.
  2. Sum the digits: 1234 1168 9012 = 3644.
  3. Modulo 10: 3644 % 10 = 4.
  4. Check for equality: Since the remainder is not 0, the number is not valid.

Variations:

  • Luhn-2 algorithm: This algorithm doubles every other digit, but instead of adding the doubled digits, they are added as separate numbers.
  • Luhn-3 algorithm: This algorithm doubles every third digit, and the sum of the doubled digits is divided by 10.

Applications:

The Luhn algorithm is used in a variety of applications, including:

  • Credit card verification
  • IMEI number validation
  • Social Security number validation

Advantages:

  • Simple to implement
  • Effective at detecting errors
  • Relatively secure

Disadvantages:

  • Not foolproof: It is possible to create numbers that pass the Luhn algorithm but are not valid.
  • Can be cracked with enough effort: With enough time and resources, it is possible to crack the Luhn algorithm.

Disclaimer