CS50x Credit

Photo by Ryan Born on Unsplash
~/ $ cd pset1
~/pset1/ $ mkdir credit
~/pset1/ $ cd credit
~/pset1/credit/ $ touch credit.c
~/pset1/credit/ $ open credit.c
$ ./credit
Number: 4003-6000-0000-0014
Number: foo
Number: 4003600000000014
VISA
$ ./credit
Number: 6176292929
INVALID
// Prompt user for a card number to validate. Store it.
// Validate the card through Luhn's Algorithm.
// Check for card lenght and starting digits.
// Print provider or invalid.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
bool luhnCheck(long cardNumber);
int getCardLen(long cardNumber);
void getCardProv(long cardNumber);
int main(void)
{
long cardNumber = get_long_long("Card Number to Validate: ");
if (luhnCheck(cardNumber) == true)
{
getCardProv(cardNumber);
}
else
{
printf("INVALID\n");
}
}

Luhn’s Algorithm

bool luhnCheck(long cardNumber)
{
int checkSum = 0;
long tmp = cardNumber;

for (int pos = 0; tmp > 0; pos++)
{
if (pos % 2 == 0)
{
checkSum += tmp % 10;
tmp /= 10;
}
else
{
int odd = (tmp % 10) * 2;
checkSum += (odd / 10 + odd% 10);
tmp /= 10;
}
}
return (checkSum % 10) == 0;
}
odd = 12
(12/10)+(12%10)
1 + 2 = 3
odd = 4
(4/10) + (4%10)
0 4 = 4
printf("VALID\n");
int getCardLen(long cardNumber)
{
return false;
}
void getCardProv(long cardNumber)
{
}
~/pset1/credit/ $ ./credit
Card Number to Validate: 4003600000000014
VALID
~/pset1/credit/ $ ./credit
Card Number to Validate: 378282246310005
VALID
~/pset1/credit/ $ ./credit
Card Number to Validate: 6011111111111117
INVALID
~/pset1/credit/ $ ./credit
Card Number to Validate: 6176292929
INVALID
int getCardLen(long cardNumber)
{
int len = log10(cardNumber);
return len + 1;
}
int len = getCardLen(cardNumber);
int prov;
if (len == 16)   
{
prov = (cardNumber / 1e14);
if (prov >= 51 && prov <= 55)
{
printf("MASTERCARD\n");
}
else if (prov >= 40 && prov <= 49)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
if (len == 13)
{
prov = (cardNumber / 1e12);
if (prov == 4)
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}

if (len == 15)
{
prov = (cardNumber / 1e13);
if (prov == 34 || prov == 37)
{
printf("AMEX\n");
}
else
{
printf("INVALID\n");
}
}
else if (len <= 12 || len >= 17 || len == 14)
{
printf("INVALID\n");
}
Results generated by style50 v2.7.4
Looks good!
Results for cs50/problems/2020/x/credit generated by check50 v3.1.2
:) credit.c exists
:) credit.c compiles
:) identifies 378282246310005 as AMEX
:) identifies 371449635398431 as AMEX
:) identifies 5555555555554444 as MASTERCARD
:) identifies 5105105105105100 as MASTERCARD
:) identifies 4111111111111111 as VISA
:) identifies 4012888888881881 as VISA
:) identifies 4222222222222 as VISA
:) identifies 1234567890 as INVALID
:) identifies 369421438430814 as INVALID
:) identifies 4062901840 as INVALID
:) identifies 5673598276138003 as INVALID
:) identifies 4111111111111113 as INVALID
:) identifies 4222222222223 as INVALID