# Untitled

unknown
csharp
2 years ago
2.7 kB
2
Indexable
Never
```#include <cs50.h>
#include <stdio.h>

// function to get digits count
int digits(long dig);

// function to get value of specific digit
int pos(long p, long card);

//function to check Luhn’s Algorithm
long check(long card);

// functions to get card type
bool visa(long card);
bool amex(long card);
bool mc(long card);

int main(void)
{
long card = get_long("Number: ");

//checking if card type and checksum are both correct
if (visa(card) == true && check(card) == 0)
{
printf("VISA\n");
}
else if (amex(card) == true && check(card) == 0)
{
printf("AMEX\n");
}
else if (mc(card) == true && check(card) == 0)
{
printf("MASTERCARD\n");
}
else
{
printf("INVALID\n");
}
}

// checking how long is the input number
int digits(long dig)
{
int d = 0;
do
{
d++;
dig = dig / 10;
}
while (dig != 0);
return d;
}

// checking digit at specific position inside the number
int pos(long p, long card)
{
int digit;
long div = 10;
for (int i = p; i > 1; i--)
{
div = div * 10;
}
digit = (card / (div / 10)) - ((card / div) * 10);
return digit;
}

// checking first digits for the card type
bool visa(long card)
{
if (digits(card) == 13 || digits(card) == 16)
{
if (pos(digits(card), card) == 4)
{
return true;
}

}
return false;
}

// checking first digits for the card type
bool amex(long card)
{
if (digits(card) == 15 && pos(15, card) == 3)
{
if (pos(14, card) == 4 || pos(14, card) == 7)
{
return true;
}
}
return false;
}

// checking first digits for the card type
bool mc(long card)
{
if (digits(card) == 16 && pos(16, card) == 5)
{
if (pos(15, card) > 0 && pos(15, card) < 6)
{
return true;
}
}
return false;
}

//function to check Luhn’s Algorithm
long check(long card)
{
long sd = 0;
long se = 0;
long check;
// doubling every other digit
for (int j = 2; j <= digits(card); j = j + 2)
{
// checking if result is two digit number and adding them up if
if ((2 * pos(j, card)) > 9)
{
sd = sd + (2 * pos(j, card)) - 9;
}
else
{
sd = sd + (2 * pos(j, card));
}
}
// adding the rest of the digits
for (int k = 1; k <= digits(card); k = k + 2)
{
se = se + pos(k, card);
}

check = pos(1, sd + se);
return check;
}```