Luhn algorithm: Difference between revisions

Content deleted Content added
Tag: section blanking
Line 104:
 
The algorithm appeared in a US Patent<ref>[http://www.google.com/patents/US2950048 US Patent 2,950,048 - ''Computer for Verifying Numbers'', Hans P Luhn, August 23, 1960]</ref> 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.
 
==Implementation of standard Mod 10==
The implementations below are in [[Python (programming language)|Python]].
===Verification of the check digit===
 
<!--
Do not add more code to this article. See the talk page before editing. The manual of style discourages multiple code samples, as they are rarely of encyclopedic value.
-->
<source lang="python">
def digits_of(number):
return list(map(int, str(number)))
 
def luhn_checksum(card_number):
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
total = sum(odd_digits)
for digit in even_digits:
total += sum(digits_of(2 * digit))
return total % 10
 
def is_luhn_valid(card_number):
return luhn_checksum(card_number) == 0
</source>
 
===Calculation of the check digit===
The algorithm above checks the validity of an input with a check digit. Calculating the check digit requires only a slight adaptation of the algorithm—namely:
 
<!--
Do not add more code to this article. See the talk page before editing. The manual of style discourages multiple code samples, as they are rarely of encyclopedic value.
-->
<source lang="python" style="margin-top: 1em">
def calculate_luhn(partial_card_number):
check_digit = luhn_checksum(int(partial_card_number) * 10) # Append a zero check digit to the partial number and calculate checksum
return check_digit if check_digit == 0 else 10 - check_digit # If the (sum mod 10) == 0, then the check digit is 0
# Else, the check digit = 10 - (sum mod 10)
 
</source>
 
==See also==