Skip to content

Instantly share code, notes, and snippets.

@sdwvit sdwvit/сс.c
Created May 3, 2019

Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
string INVALID = "INVALID";
string AMEX = "AMEX";
string MASTERCARD = "MASTERCARD";
string VISA = "VISA";
typedef struct {
unsigned int d[16];
unsigned int len;
} CC;
CC getDigits(long cc) {
CC digits;
int i = 0;
while (cc > 0) {
digits.d[i] = cc % 10;
cc /= 10;
i++;
}
digits.len = i;
return digits;
}
bool checkLength(CC cc) {
if (cc.len < 13 || cc.len > 16 || cc.len == 14) {
return false;
}
return true;
}
bool isMC(CC cc) {
int last = cc.len - 1;
return cc.d[last] == 5 && cc.d[last - 1] > 0 && cc.d[last - 1] < 6;
}
bool isVisa(CC cc) {
int last = cc.len - 1;
return cc.d[last] == 4;
}
bool isAmex(CC cc) {
int last = cc.len - 1;
return cc.d[last] == 3 && (cc.d[last - 1] == 4 || cc.d[last - 1] == 7);
}
bool checkStartsWith(CC cc) {
if (isVisa(cc)) {
return cc.len == 13 || cc.len == 16;
}
if (isMC(cc)) {
return cc.len == 16;
}
if (isAmex(cc)) {
return cc.len == 15;
}
return false;
}
bool checkSum(CC cc) {
int sum = 0;
for (int i = cc.len - 1; i >= 0; i--) {
int toadd = cc.d[i] * (i%2 ? 2 : 1);
if (toadd >= 10) {
sum += toadd % 10 + toadd / 10;
} else {
sum += toadd;
}
}
return sum % 10 == 0;
}
int main(void) {
CC cc = getDigits(get_long("Gimme credit card: "));
if (
checkLength(cc) &&
checkStartsWith(cc) &&
checkSum(cc)
) {
if (isAmex(cc)) {
printf("%s\n", AMEX);
} else if (isVisa(cc)) {
printf("%s\n", VISA);
} else if (isMC(cc)) {
printf("%s\n", MASTERCARD);
}
} else {
printf("%s\n", INVALID);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.