Jump to content

Luhn algorithm: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Remove JavaScript code, and replace it with link. This code have author.
Adding Groovy Implementation - I think it's a helpful balance between Python and Java
Line 84: Line 84:
num = [int(x) for x in str(cc)]
num = [int(x) for x in str(cc)]
return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
</source>

In [[Groovy (programming language)|Groovy]]:
<source lang="groovy">
def isLuhnValid = { String num ->
def divmod = { n, div -> [(int)(n/div),n%div] }
def digits = num.getChars().collect { Character.digit(it,10) }
boolean flip = true;
digits[-1..0].sum { (flip^=true) ? divmod(it*2,10).sum() : it } % 10 == 0
}
</source>
</source>


Line 121: Line 132:
Add more code samples only if you think it's necessary.
Add more code samples only if you think it's necessary.
-->
-->

==Other implementations==
==Other implementations==
*[https://sites.google.com/site/abapexamples/javascript/luhn-validation Luhn implementations in Javascript]
*[https://sites.google.com/site/abapexamples/javascript/luhn-validation Luhn implementations in Javascript]

Revision as of 19:45, 24 January 2011

The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn and described in U.S. Patent No. 2,950,048, filed on January 6, 1954, and granted on August 23, 1960.

The algorithm is in the public domain and is in wide use today. It is specified in ISO/IEC 7812-1[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 cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from collections of random digits.

Strengths and weaknesses

The Luhn algorithm will detect almost any single-digit error, as well as almost all transpositions of adjacent digits. It will not, however, detect transposition of the two-digit sequence 09 to 90 (or vice versa). It will detect 7 of the 10 possible twin errors (it will not detect 2255, 3366 or 4477).

Other, more complex check-digit algorithms (such as the Verhoeff algorithm) can detect more transcription errors. The Luhn mod N algorithm is an extension that supports non-numerical strings.

Because the algorithm operates on the digits in a right-to-left manner and zero digits affect the result only if they cause shift in position, zero-padding the beginning of a string of numbers does not affect the calculation. Therefore, systems that pad to a specific number of digits by converting 1234 to 0001234 (for instance) can perform Luhn validation before or after the padding and achieve the same result.

The algorithm appeared in a US Patent for a hand-held, mechanical device for computing the checksum. It was therefore required to be rather simple. The device took the mod 10 sum by mechanical means. The substitution digits, that is, the results of the double and reduce procedure, were not produced mechanically. Rather, the digits were marked in their permuted order on the body of the machine.

Informal explanation

The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This account number must pass the following test:

  1. Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
  2. Sum the digits of the products (eg, 10 => 1, 14 => 5) together with the undoubled digits from the original number.
  3. 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.

Assume an example of an account number "4992739871" that will have a check digit added, making it of the form 4992739871x:

Account number 4 9 9 2 7 3 9 8 7 1 x
Double every other 4 18 9 4 7 6 9 16 7 2 x
Sum digits 4 + (1 + 8) + 9 + (4) + 7 + (6) + 9 + (1 + 6) + 7 + (2) = 64 + x

To make the sum divisible by 10, we set the check digit to 6, making the full account number 49927398716.

The account number 49927398716 can be validated as follows:

  1. Double every second digit, from the rightmost: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18
  2. Sum all the individual digits (digits in parentheses are the products from Step 1): 6 + (2) + 7 + (1+6) + 9 + (6) + 7 + (4) + 9 + (1+8) + 4 = 70
  3. Take the sum modulo 10: 70 mod 10 = 0; the account number is probably valid.

Mod 10+5 Variant

Some credit cards use the "Mod 10 plus 5" variant to extend the space of valid card numbers.[citation needed] In this variant, if the sum ends in 0 or 5, the number is considered valid.

Implementation of standard Mod 10

In Python:

def is_luhn_valid(cc):
    num = [int(x) for x in str(cc)]
    return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0

In Groovy:

def isLuhnValid = { String num ->
    def divmod = { n, div -> [(int)(n/div),n%div] }
    def digits = num.getChars().collect { Character.digit(it,10) }
    boolean flip = true;
    
    digits[-1..0].sum { (flip^=true) ? divmod(it*2,10).sum() : it } % 10 == 0
}

In Java:

  public static boolean isValidCC(String num) {

    final int[][] sumTable = {{0,1,2,3,4,5,6,7,8,9},{0,2,4,6,8,1,3,5,7,9}};
    int sum = 0, flip = 0;
    
    for (int i = num.length() - 1; i >= 0; i--)
      sum += sumTable[flip++ & 0x1][Character.digit(num.charAt(i), 10)];
    return sum % 10 == 0;
  }

In C#:

public static bool LuhnCheck(string input)
{
    int sum = 0;
    int imax = input.Length - 1;
    for (int i = imax; i >= 0; i--)
    {
        int digit = input[i] - '0';
        if (i % 2 == imax % 2)
            sum += digit;
        else if (digit <= 4)
            sum += digit * 2;
        else
            sum += digit * 2 - 9;
    }
    return sum % 10 == 0;
}

Other implementations

References