I've been trying to create a program that can check if a credit card number is valid or not based on [Hans Peter Luhn's algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm). However, I can only get it to work for some inputs.

```
// Loop through every digit in the card number
for ( int i = 0; i < intlen (num); ++i )
{
    nextDigit = getDigit (num, i);

    // If every other number...
    if ( i % 2 )
    {
        nextDigit *= 2;

        // ...times by two and add the individual digits to the total
        for ( int j = 0; j < intlen (nextDigit); ++j )
        {
            total += getDigit (nextDigit, j);
        }
    }
    else
    {
        total += nextDigit;
    }
}

```

When I use the `AMEX` card number `378282246310005` it works fine and tells the user it's valid. However, once I try the `VISA` card number `4012888888881881` it says it's invalid. I tried to do a sanity check and do it manually to see if my program was wrong but I deduced the same result. These card number were taken from the Paypal test credit card numbers [page](https://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm) so I know they are valid.

So what am I doing wrong?

---

To clarify the details by the program, if `total modulo 10 == 0` then the card number is valid.

Functions called:

```
// Function to return length (number of digits) of an int

int intlen (long long n)
{
    int len = 1;

    // While there is more than 1 digit...
    while ( abs (n) > 9 )
    {
       // ...discard leading digits and add 1 to len
       n /= 10;
       ++len;
    }

    return len;
}

// Function to return a digit in an integer at a specified index

short getDigit (long long num, int index)
{
    // Calculating position of digit in integer
    int pos = intlen (num) - index;

    // Discard numbers after selected digit
    while ( pos > 1 )
    {
        num /= 10;
        --pos;
    }

    // Return right-most digit i.e. selected digit
    return num % 10;
}

```