Java Reference
In-Depth Information
The algorithm for adding the digits can be described as follows: Consider each
digit of the credit card number to have a zero-based index: The first is at index 0, and
the last is at index 15. Start from the rightmost digit and process each digit one at a
time. For each digit at an odd-numbered index (the 15th digit, 13th digit, etc.), simply
add that digit to the cumulative sum. For each digit at an even-numbered index (the
14th, 12th, etc.), double the digit's value. If that doubled value is less than 10, add it
to the sum; if the doubled value is 10 or greater, add each of its digits separately into
the sum.
The following pseudocode describes the Luhn algorithm to add the digits:
sum = 0.
for (each digit of credit card number, starting from right) {
if (digit's index is odd) {
add digit to sum.
} else {
double the digit's value.
if (doubled value < 10) {
add doubled value to sum.
} else {
split doubled value into its two digits.
add first digit to sum.
add second digit to sum.
}
}
}
4111111111111111 and 4408041274369853 are sample credit card numbers that
pass the Luhn algorithm. Figure 14.3 shows how the algorithm sums the latter num-
ber in detail. Notice how digits at even indexes are doubled and split into two digits if
their new values are 10 or higher. For example, the number 7 at index 8 is doubled to
14, which is then split to make 1 + 4.
CC # 4408 0412 7436 9853
44080412 7 436 9 8 5 3
Scale
× 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2
8 4 0 8 0 4 2 2 14 4 6 6 18 8 10 3
Sum = 8 + 4 + 0 + 8 + 0 + 4 + 2 + 2 + 1+4 + 4 + 6 + 6 + 1+8 + 8 + 1+0 + 3
= 70
70 is divisible by 10, therefore, this card number is valid.
Figure 14.3
Example checksum using the Luhn algorithm
Search WWH ::




Custom Search