Skip to content

Instantly share code, notes, and snippets.

@FrancoB411
Last active March 25, 2022 17:08
Show Gist options
  • Save FrancoB411/91a372951621be7ad64567dca1cb6c2f to your computer and use it in GitHub Desktop.
Save FrancoB411/91a372951621be7ad64567dca1cb6c2f to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
int last_digit(long num);
bool ends_with_zero(int num);
bool is_even(int num);
bool luhn_validate(long num);
int first_n_digits(long num, int len, int n);
int num_len(long num);
bool isAmex(long num);
bool isVisa(long num);
bool isMc(long num);
int main(void)
{
long num = get_long("Number: ");
if (luhn_validate(num) == false)
{
printf("INVALID\n");
return 0;
}
if (isAmex(num))
printf("AMEX\n");
else if (isVisa(num))
printf("VISA\n");
else if (isMc(num))
printf("MASTERCARD\n");
else
printf("INVALID\n");
}
int last_digit(long num)
{
return num % 10;
}
bool ends_with_zero(int num)
{
return last_digit(num) == 0;
}
bool is_even(int num)
{
return num % 2 == 0;
}
bool luhn_validate(long num)
{
int current;
int sum_of_evens = 0;
int sum_of_odds = 0;
int i = 1;
while(num)
{
current = last_digit(num);
if(is_even(i))
{
current = current * 2;
if(current > 9)
{
sum_of_evens += last_digit(current);
current /= 10;
}
sum_of_evens += current;
}
else
{
sum_of_odds += current;
}
num /= 10;
i += 1;
}
return ends_with_zero(sum_of_evens + sum_of_odds);
}
int first_n_digits(long num, int len, int n)
{
return num / pow(10, len - n);
}
int num_len(long num)
{
return log10(num) + 1;
}
bool isAmex(long num)
{
const int AMEX_LEN = 15;
const int AMEX_HEAD_LARGE = 37;
const int AMEX_HEAD_SMALL = 34;
int len = num_len(num);
if (len == AMEX_LEN)
{
int first_2 = first_n_digits(num, len, 2);
if (first_2 == AMEX_HEAD_SMALL || first_2 == AMEX_HEAD_LARGE)
return true;
}
return false;
}
bool isVisa(long num)
{
const int VISA_SHORT_LEN = 13;
const int VISA_LONG_LEN = 16;
const int VISA_FIRST_DIGIT = 4;
int len = num_len(num);
if ((len == VISA_SHORT_LEN) || (len == VISA_LONG_LEN))
{
int first = first_n_digits(num, len, 1);
if (first == VISA_FIRST_DIGIT)
{
return true;
}
}
return false;
}
bool isMc(long num)
{
const int MC_LEN = 16;
const int MC_MAX = 55;
const int MC_MIN = 51;
int len = num_len(num);
if (len == MC_LEN)
{
int first_2 = first_n_digits(num, len, 2);
if ((first_2 >= MC_MIN) && (first_2 <= MC_MAX))
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment