### Luhn Algorithm

Posted on: April 25, 2016 11:52:19 PM

I recently came across some programming challenges online that I decided to try out. They are heavily math based and took me quite a bit of research. This particular challenge was to both calculate a check digit on a credit card and validate a credit card number. The algorithm I found that does this best is called Luhn Algorithm.

Luhn Algorithm is described as the following (via Wikipedia):

1. From the right most digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9).
2. Take the sum of all the digits.
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.

Based on this description, I came up with the following code:

```    public static class LuhnAlgorithm
{
private static readonly int[] DoubleDigitCalculation = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };

public static int GetLuhnsCheckDigit(this string account)
{
int checkValue = LuhnsCalculation(account.Select(c => c - '0').ToArray(), false);

return checkValue == 0 ? 0 : 10 - checkValue;
}

public static bool LuhnsPass(this string account)
{
return LuhnsCalculation(account.Select(c => c - '0').ToArray(), true) == 0;
}

private static int LuhnsCalculation(int[] digits, bool includesCheckDigit)
{
int index = 0;
int modIndex = includesCheckDigit ? digits.Length % 2 : digits.Length % 2 == 1 ? 0 : 1;

return digits.Sum(d => index++ % 2 == modIndex ? DoubleDigitCalculation[d] : d) % 10;
}
}
```

This bit of code passed all the tests and is very fast. Although it doesn't have a ton of use, it was fun to come up with.

No comments yet, be the first to leave one.

Recent Blog Activity
Blog Archive