The programm identifies this invalid cards as Visa (4111111111111113, 4222222222223). I really don't know how to solve this problem. The program pass all other checks expet these two and I don't know where it goes wrong. I think the problem in the loop but the program identifies "AMEX", "MASTERCARD", "VISA" and "INVALID" correctly excpet these two cards.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
string cardType = "VALID";
long card = get_long("Number: ");
int length = floor(log10(card)) + 1;
bool isValid = false;
long number = card;
long startNumber = card;
int productNumber;
int sum = 0;
while (startNumber > 100)
{
startNumber /= 10;
}
for (int i = 0; number < 0; i ++)
{
sum += number % 10;
if ( i % 2 == 0)
{
productNumber = (number % 10) * 2 ;
if (productNumber > 9)
{
productNumber = (productNumber % 10) + (productNumber / 10);
}
sum += productNumber;
}
number /= 10;
}
if (sum % 10 == 0)
{
isValid = true;
}
if (length == 15 && isValid && (startNumber == 34 || startNumber == 37))
{
cardType = "AMEX";
}
else if (length == 16 && isValid && (startNumber == 51 || startNumber == 52 || startNumber == 53 || startNumber == 54 || startNumber == 55))
{
cardType = "MASTERCARD";
}
else if ((length == 13 || length == 16) && isValid && (startNumber >= 40 && startNumber < 50 ))
{
cardType = "VISA";
}
else {
cardType = "INVALID";
}
printf("%s\n", cardType);
}
Your checksum loop has at least two faults.
a) It isn't looping at all so the checksum test always passes. Change
to
b) The Luhn algorithm is incorrect because for even-placed digits you sum the digit as well as the sum of the digits of twice its value. The whole loop should be this:
c) However the checksum test is still failing for reasons I haven't yet found.