My code:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
long long i = 0;
do
{
// read user input from stdin
i = get_long_long("Enter credit card number: ");
}
while(i <= 0); //make sure number entered is positive int
long long cc = i;
int valueA = 0;
int valueB = 0;
//get every second number of credit card multiply it by two and add the values
while(cc > 0)
{
cc /= 10;
if(cc % 10 * 2 > 9)
{
valueA += (((cc % 10) * 2) - 10) + 1;
}
else
{
valueA += (cc % 10) * 2;
}
cc /= 10;
}
//add together the other numbers from the credit card
cc = i;
while(cc > 0)
{
valueB += cc % 10;
cc /= 100;
}
cc = i;
//get the leading 2 digits of the credit card
while(cc > 99)
{
cc /= 10;
}
//determine if valid checksum, and if so, identify issuer
if((valueA + valueB) % 10 == 0)
{
//credit card identification
if(cc == 34 || cc == 37)
{
printf("AMEX\n");
}
else if(cc > 50 && cc < 56)
{
printf("MASTERCARD\n");
}
else if(cc > 39 && cc < 50)
{
printf("VISA\n");
}
}
else //reject card
{
printf("INVALID\n");
}
return 0;
}
check50
output don't match. Is that really the same code? Maybe you forgot to save before runningcheck50
, or are in a different file/directory? Also, what if credit card number has correct checksum but is not a credit card? Take for example42
(VISA?), or1000000000000008
(no output)10
is in none of the ranges. The if-elseif chain needs a final else. Even though there are no checks, the specifications limit the valid digit counts for the different types, any card with a different length should be rejected, for example usingif (cc / 10 == 4 && (digits == 13 || digits == 16)) { printf("VISA\n"); } else ...
(obviously requires having the digit count first).