So, this is probably not a good solution of the problem, but I hoped it would at least work, after struggling with it for quite some time. It made me happy to see it worked for the first number I tested (AMEX), however, when I ran the cs50 test, it turned out it works only for certain cases, and I cannot figure out where the problem is.
Also, when I run the program and enter the credit card number, in certain cases it accepts it and displays result as either invalid or the card name, but in other cases it just keeps prompting me for new entry, and I don't see the reason.
I would really appreciate any help...
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
//Prompt the user for credit card number
long long ccnumber = get_long_long ("Number: ");
long long sum1=0;
long long sum2=0;
long long di=0;
long long dj=0;
long long d1=ccnumber%10;
long long d2=0;
// Sum the digits that won't be multiplied by 2 (every other digit starting from the last one)
long long number1=ccnumber;
while (number1>0)
{
number1=number1/100;
di=number1%10;
sum1+=di;
}
// Sum every other digit multiplied by 2, starting with the number’s second-to-last digit
long long number2=ccnumber/10;
long long d2temp=(number2%10);
if(d2temp*2>9)
{
d2=d2temp%10 + (d2temp/10)%10;
}
else
{
d2=d2temp;
}
while(number2>0)
{
number2=number2/100;
di=number2%10;
if(di*2>9)
{
dj=(di*2)%10 + (di*2/10)%10;
}
else
{
dj=di*2;
}
sum2+=dj;
}
long long totalsum=sum1+sum2+d1+d2;
// Check if the card is valid and what type it is if so
if (totalsum%10==0)
{
if( (ccnumber>=4000000000000 && ccnumber<5000000000000) || (ccnumber>=4000000000000000 && ccnumber<5000000000000000))
{
printf("VISA\n");
}
else if( (ccnumber>=340000000000000 && ccnumber<350000000000000) || (ccnumber>=370000000000000 && ccnumber<380000000000000))
{
printf("AMEX\n");
}
else if(ccnumber>=5100000000000000 && ccnumber<5600000000000000)
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}
}