 # The solution to cs50 psets 1 credit problem (2022)

In this problem cs50 psets 1 credit, we have to implement a program called “credit.c” that prompts the user for a credit card number. Then prints out whether it is a valid American Express, Mastercard, or Visa card number by checking in the digits of the input number.

So, to solve this problem we should use Luhn’s algorithm. If you are looking at this post, I’m guessing that you already know what this formula is and how we should implement the algorithm and build the program.

I’ll give you my solution for this cs50 psets 1 credit problem.

``````#include <cs50.h>
#include <stdio.h>

//AMERX 15 STRT 34 OR 37
//MC 16 STRT 51, 52, 53, 54, 55
//VZA 13 OR 16 STRT 4

int main(void)
{
long creditNumber;

do
{
creditNumber = get_long("Number: ");
}
while (creditNumber <= 0);

long creditCard = creditNumber;
int sum = 0;
int count =0;
long divider = 10;

while (creditCard > 0)
{
int lastDigit = creditCard % 10;
sum = sum + lastDigit;
creditCard = creditCard / 100;
}

creditCard = creditNumber / 10;
while (creditCard > 0)
{
int lastDigit = creditCard % 10;
int byTwo = lastDigit * 2;
sum = sum + (byTwo % 10) + (byTwo / 10);
creditCard = creditCard / 100;
}

creditCard = creditNumber;
while (creditCard != 0)
{
creditCard = creditCard / 10;
count++;
}

for (int i = 0; i < count - 2; i++)
{
divider = divider * 10;
}

int firstDigit = creditNumber / divider;
int firstTwoDigits = creditNumber / (divider / 10);

if ((sum % 10) == 0)
{
if (firstDigit == 4 && (count == 13 || count == 16))
{
printf("VISA\n");
}
else if ((firstTwoDigits == 34 || firstTwoDigits == 37) && count == 15)
{
printf("AMEX\n");
}
else if ((firstTwoDigits > 50 && firstTwoDigits < 56) && count == 16)
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
}
else {
printf("INVALID\n");
}
}
``````

If you found this post useful, give it a share!

you may also like to read: The solution to CS50 psets 1 cash problem (2022)

(Visited 44 times, 1 visits today)