Checkdigit algorithm Luhn mod N vs simple sum

4.4k views Asked by At

Do you know why the Luhn mod N algoritm in order to create the check digit performs a sum by doubling the value of each even placed char instead of perfoming a simple sum of all chars?

In pseudo-code words:

given:

var s = "some string i want to create check digit";

do you know why Luhn mod N does basically this:

for(i from s.length-1 to 0)
   if(i is even)
      checkdigit += chr2int(s[i]) * 2;
   else
      checkdigit += chr2int(s[i]);

instead of simply doing a sum

for(i from s.length-1 to 0)
   checkdigit += chr2int(s[i]);

they can still both terminate with a mod operation to make the checkdigit fit into one char

return int2chr( chr2int('a') + (checkdigit mod 25) );

As a side note to this question, to whom it may be interested in a graphic representation of the Luhn algorithm that makes it even more simple to understand:

enter image description here

Actually this one is the original Luhn algorithm that does not even needs to use MOD function.

1

There are 1 answers

8
SWeko On BEST ANSWER

Checkdigit characters are designed to prevent accidental mangling of an input, for example when a clerk enters the number via keyboard.

If just a sum is used both strings "ABCD" and "ABDC" would yield the same checksum ("A" + "B" + "C" + "D"), so simple swap errors could happen unnoticed.

However, taking parity into consideration, "ABCD" and "ABDC" will become (2"A" + "B" + 2"C" + "D") and (2"A" + "B" + 2"D" + "C") respectively, which are (likely) different numbers, so in this way we could detect if two characters were inadvertently swapped.