Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Last active April 11, 2020 02:38
Show Gist options
  • Save voidnerd/4d0afe554d96976d61da0d6c35908ca5 to your computer and use it in GitHub Desktop.
Save voidnerd/4d0afe554d96976d61da0d6c35908ca5 to your computer and use it in GitHub Desktop.
A solution for Harvard / edX CS50 week 1 luhn algorithm credit card verification assignment
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void) {
long card_no;
do{
card_no = get_long("Card Number: ");
}while(card_no < 1);
long temp = card_no;
int firstDigit, secondDigit;
int sum = 0;
int current;
int counter = 0;
int product;
while(temp > 0) {
counter++;
current = temp % 10;
if(counter % 2 == 0) {
product = current * 2;
if(product > 9) {
sum += floor(product / 10) + (product % 10);
}else {
sum += product;
}
}else {
sum += current;
}
if(temp > 9) {
secondDigit = current;
}else if(temp <= 9) {
firstDigit = current;
}
temp = temp /10;
}
if(sum % 10 == 0) {
switch(firstDigit) {
case 3:
if( (counter == 15) && (secondDigit == 4 || secondDigit == 7 ))
{
printf("AMEX\n");
}else {
printf("INVALID\n");
}
break;
case 4:
if((counter == 13 || counter == 16))
{
printf("VISA\n");
}else {
printf("INVALID\n");
}
break;
case 5:
if(counter == 16 && (secondDigit == 1 || secondDigit == 2 || secondDigit == 3 || secondDigit == 4 || secondDigit == 5 ))
{
printf("MASTERCARD\n");
}else {
printf("INVALID\n");
}
break;
default:
printf("INVALID\n");
}
}else {
printf("INVALID\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment