Sunday, April 10, 2011

验证CC算法

http://en.wikipedia.org/wiki/Luhn_algorithm

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 number4992739871x
Double every other418947691672x
Sum digits4 + (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.

No comments: