Skip to content

Instantly share code, notes, and snippets.

Created July 28, 2016 16:09
Show Gist options
  • Save anonymous/b92d10a31cec0c601384964060b9b06a to your computer and use it in GitHub Desktop.
Save anonymous/b92d10a31cec0c601384964060b9b06a to your computer and use it in GitHub Desktop.
credit_check.c
#include <stdio.h>
/*
* This program uses the Luhn algorithm to validate a card number and
* print its association (VISA, MASTERCARD or AMERICAN EXPRESS)
*/
int sum_1(long long num);
int sum_2(long long num);
long long get_num();
int main(void) {
int sum;
long long digits, num;
num = get_num();
sum = sum_1(num) + sum_2(num);
digits = num;
while (digits > 100) {
digits /10;
}
if (sum % 10 == 0)
if (digits / 10 == 4)
printf("VISA\n");
else
switch (digits) {
case 34: case 37:
printf("AMEX\n");
break;
case 51: case 52: case 53: case 54: case 55:
printf("MASTERCARD\n");
break;
default:
printf("INVALID\n");
}
}
long long get_num() {
/* Get a positive number form user*/
long long num;
printf("Number: ");
scanf("%lld\n", &num);
while (num < 1) {
printf("Retry: ");
scanf("%lld\n", &num);
}
return num;
}
int sum_1(long long num) {
/* Sum of a product of every second digit form the right multiplied by 2 */
int sum;
while (num > 0) {
num /= 10;
if (num % 10 * 2 >9) {
sum += (num % 10 * 2) % 10 + 1;
num /= 10;
}
else {
num += num % 10 * 2;
num /= 10;
}
}
return sum;
}
int sum_2(long long num) {
/* Sum of a digits that were not multiplied by 2 */
int sum;
while (num > 0) {
sum += num % 10;
num /= 100;
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment