Luhn Algorithm


The Luhn algorithm (also known as modulo-10) is used to check that a credit card number looks valid. In other words, if the number passes the Luhn check then it is possibly a valid credit card - numbers that fail the check can never be valid.

Luhn.java - Luhn algorithm and test harness in Java

    public boolean isValidNumber(final String number) {
        int sum = 0;

        boolean alternate = false;
        for (int i = number.length() - 1; i >= 0; i--) {
            int n = Integer.parseInt(number.substring(i, i + 1));
            if (alternate) {
                n *= 2;
                if (n > 9) {
                    n = (n % 10) + 1;
                }
            }
            sum += n;
            alternate = !alternate;
        }

        return (sum % 10 == 0);
    }

luhn.c - Luhn algorithm and test harness in C

int
isValidNumber(const char *number)
{
    int n, i, alternate, sum;

    if (!number)
        return 0;

    n = strlen(number);

    if (n < 13 || n > 19)
        return 0;

    for (alternate = 0, sum = 0, i = n - 1; i > -1; --i) {
        if (!isdigit(number[i]))
            return 0;

        n = number[i] - '0';

        if (alternate) {
            n *= 2;
            if (n > 9)
                n = (n % 10) + 1;
        }
        alternate = !alternate;

        sum += n;
    }

    return (sum % 10 == 0);
}

Last updated: 27th January 2005