Luhn Algorithm

Luhn is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers. Below is how this algorithm works:

  • From the rightmost digit, which is the check digit, and moving left, double the value of every second digit. The check digit is not doubled, the first digit doubled is immediately to the left of the check digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the product (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same result can be found by subtracting 9 from the product (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).
  • Take the sum of all the digits.
  • If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

Write the Luhn checksum function.

For Example:
1322 4231 4332 2312

  • 1x2=2, 2x2=4, 3x2=6, 4x2=8, 3x2=6, 4x2=8, 2x2=4, 1x2=2
  • 2+2+3+4+2+6+3+8+1+6+2+8+2+4+3+2 = 58
  • 58 % 10 = 8, thus this CC is not valid!

Contributed by Mert Deniz Güngör