#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
long long cardNumber;
char cardNumberStr[16];
char cardNumberArray[16];
int i, numberOfDigits;
int sum = 0;
do
{
printf("Enter your card number.\n");
cardNumber = get_long_long();
}while(cardNumber < 0); //Check if card number is out of range, less than 0
//Calculates the number of digits in the cardNumber
numberOfDigits = log10(cardNumber) + 1;
//If the number of digits is not equal to 13 or 15 or 16 (VISA, MASTERCARD, AMEX) then it's an invalid card number
if(numberOfDigits != 13 && numberOfDigits != 15 && numberOfDigits != 16)
{
printf("INVALID\n");
return 0;
}
//Convert the number to a string to be able to deal with each digit easily
sprintf(cardNumberStr, "%lld", cardNumber);
//Convert each char in the string to an integer number and store it in an array for easier calculations
for(i = 0; i < numberOfDigits; i++)
{
cardNumberArray[i] = cardNumberStr[i] - '0';
}
for(i = 0; i < numberOfDigits; i++)
{
if(i % 2 == 0) //If the order of the number is even AKA not supposed to be multiplied by 2 then we should just add it to the sum
{
sum += cardNumberArray[i];
}
else //If the order of the number is odd then this number is supposed to be multiplied by 2
{
/*If the number times 2 is greater than or equal 10 then it consists of 2 parts which should be divided then summed*/
if((cardNumberArray[i] * 2) >= 10)
/*The 2nd digit should be summed hence the moduluo and since the number would never exceed (2 * 9 = 18) then a 1 is added*/
sum += ((cardNumberArray[i] * 2) % 10) + 1;
}
else
{
/*If the number is less than 10 then it should be multiplied by 2 and added to the sum immediatly*/
sum += (cardNumberArray[i] * 2);
}
}
}
//If the last digit of the sum is 0 then the credit card number is valid
if(sum % 10 == 0)
{
if(cardNumberArray[0] == 3) // Since all AMEX credit cards start with 3
{
printf("AMEX\n");
}
else if(cardNumberArray[0] == 5) // Since all MASTERCARD credit cards start with 5
{
printf("MASTERCARD\n");
}
else if(cardNumberArray[0] == 4) // Since all VISA credit cards start with 4
{
printf("VISA\n");
}
}
else
{
printf("INVALID\n");
}
}
Here is the checks50 results https://cs50.me/checks/713f559f14249bcf264dda1df6e9c24ea6c7b13e