↑

Main Page

# Luhn algorithm

The Luhn algorithm has four steps. The first step is to start at the last digit in the card number and go

backwards digit by digit, adding together all the digits in odd positions (1, 3, and so on). To keep track of

whether the digit is in an even position, it’s easiest to use a Boolean flag (which is called

bIsOdd

). The

flag starts out

true

, because the last position is number 15.

It’s helpful to define the Luhn algorithm in a separate function so other functions access it easily:

function luhnCheckSum(sCardNum) {

var iOddSum = 0;

var bIsOdd = true;

for (var i=sCardNum.length-1; i >= 0; i--) {

var iNum = parseInt(sCardNum.charAt(i));

if (bIsOdd) {

iOddSum += iNum;

}

bIsOdd = !bIsOdd;

}

}

The next step is to add the digits in even positions; but there’s a twist: You must first multiply the digit

by two and then, if the result has two digits, you must add them together before adding to the overall

sum. That’s a bit wordy, so consider the credit card number 5432-1234-5678-9012. You have already

added together the digits in the odd positions, which is equal to 4 + 2 + 2 + 4 + 6 + 8 + 0 + 2 = 28. In this

step, you start by multiplying digits by two, which means that 5, 3, 1, 3, 5, 7, 9, and 1 will all be multi-

plied by two, leaving you with 10, 6, 2, 6, 10, 14, 16, and 2. Because 10, 10, 14, and 16 each have two dig-

its, these digits must be added, so you are now left with 1, 6, 2, 6, 1, 5, and 7. It is these numbers that you

add and store, which equals 28.

Putting this algorithm into code, you get this:

function luhnCheckSum(sCardNum) {

var iOddSum = 0;

var iEvenSum = 0;

var bIsOdd = true;

for (var i=sCardNum.length-1; i >= 0; i--) {

var iNum = parseInt(sCardNum.charAt(i));

if (bIsOdd) {

iOddSum += iNum;

} else {

iNum = iNum * 2;

if (iNum > 9) {

iNum = eval(iNum.toString().split(“”).join(“+”));

}

iEvenSum += iNum;

219

Regular Expressions

10_579088 ch07.qxd 3/28/05 11:38 AM Page 219

Free JavaScript Editor
Ajax Editor

©

↓