I tried to attempt the credit.c problem. My code is as follows:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
int main(void)
{
printf("Please enter your credit card number: ");
long long credit = GetLongLong();
char str[20];
sprintf(str, "%lld", credit);
int length = strlen(str);
int sum1 = 0;
int sum2 = 0;
for (int i = length - 1; i >= 2; i = i - 2)
{
sum1 += (2 * (credit % 10^i));
}
for (int i = length; i >= 2; i = i - 2)
{
sum2 += (credit % 10^i);
}
int sum = sum1 + sum2;
int fstwo = ((credit % (10^length)) + (credit % (10^(length - 1))));
if (length == 15 && (fstwo == 34 || fstwo == 37) && sum % 10 == 0)
{
printf("AMEX\n");
}
else if (length == 16 && (fstwo >= 51 && fstwo <= 55) && sum % 10 == 0)
{
printf("MASTERCARD\n");
}
else if ((length == 13 || length == 16) && (credit % (10^length)) == 4 && sum % 10 == 0)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
My logic is to convert a long long into a string via sprintf()
, then use strlen()
and for loops to detect every other digit in the long long. The first for
loop starts from the second last digit and sums twice of each digit. The second one starts from the last digit and sums them as per normal. I used the modulo function to determine each digit in the long long. Finally, I implemented the various conditions in the if
and else
statements. However, all my tries so far have given me invalid results. Could someone please tell me what's wrong? I have absolutely no clue, thank you!