tags:

views:

396

answers:

2

Excluding the check digit, what is the minimum length number the luhn algorithm will work on?

My thoughts are that it would work on any number greater than 2 digits (again, excluding the check digit).

The reason I ask is this: if i iterates over all digits in the number from right to left. This causes i%2 == 0 (used to find alternate positions in the number) in my luhn validation to fail if the number is 3 digits or smaller (e.g. 125 -- which on paper seems to be a valid number)

Obviously I could change my condition from i%2== 0 to something else but if it's not the correct behavior for the algorithm it'd be nice to know.

+1  A: 

Luhn's algorithm would work on two digits. It will warn if a single digit is wrong and some (but not all) of the cases where digits are transposed. Heck, it would theoretically work with one digit, but that's not very useful. You can see for yourself by fixing one digit, then changing the other and verifying that each value of the other digit will give a unique "checksum". With just two digits, however, just adding digits mod 10 would give you the same property, but it wouldn't catch any transposition errors.

David Nehme
A: 

Wikipedia's entry on the Luhn algorithm has a C# implementation that uses a different method for determining alternating digits that does not rely on a mod operation.

bool CheckNumber(int[] digits)
 {
   int sum = 0;
   bool alt = false;
   for (int i = digits.Length - 1; i >= 0; --i) {
     int thedigit = digits[i];
     if (alt) {
       thedigit *= 2;
       if (thedigit > 9) {
         thedigit -= 9; 
       }
     }
     sum = (sum + thedigit) % 10;
     alt = !alt;
   }
   return (sum == 0);
 }
Timothy Lee Russell