Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// valid cc numbers for testing
// Amex - 378282246310005
// MC - 5404000000000001
// Visa - 4242424242424242
long long user_input, cc_num_test_1, cc_num_test_2;
// prompt for user input
do
{
printf("Please enter your credit card number: ");
user_input = get_long_long();
}
while (user_input < 0);
int n1, n2, sum_of_n1, sum_of_n2_products;
sum_of_n1 = 0;
sum_of_n2_products = 0;
cc_num_test_1 = user_input;
cc_num_test_2 = user_input;
// validate checksum
while (cc_num_test_1 > 0)
{
n1 = cc_num_test_1 % 10;
sum_of_n1 += n1;
cc_num_test_1 -= n1;
cc_num_test_1 /= 10;
n2 = cc_num_test_1 % 10;
if ( (n2 * 2) > 9)
{
int n2_t2 = n2 * 2;
sum_of_n2_products += n2_t2 % 10;
sum_of_n2_products += (n2_t2 - (n2_t2 % 10)) / 10;
}
else{
sum_of_n2_products += (n2 * 2);
}
cc_num_test_1 -= n2;
cc_num_test_1 /= 10;
}
// validate company's identifier
// validate number's length
if ( (sum_of_n1 + sum_of_n2_products) % 10 == 0)
{
bool amex, mc, visa;
amex =
(cc_num_test_2 >= 340000000000000 && cc_num_test_2 < 350000000000000) ||
(cc_num_test_2 >= 370000000000000 && cc_num_test_2 < 380000000000000);
mc =
(cc_num_test_2 >= 5100000000000000 && cc_num_test_2 < 5600000000000000);
visa =
(cc_num_test_2 >= 4000000000000 && cc_num_test_2 < 5000000000000) ||
(cc_num_test_2 >= 4000000000000000 && cc_num_test_2 < 5000000000000000);
if (amex)
printf("Success! Valid American Express!\n");
else if (mc)
printf("Success! Valid MasterCard\n");
else if (visa)
printf("Success! Valid Visa\n");
else
printf("ERROR: checksum passed, however card type not found!\n");
}
else
{
printf("ERROR: checksum did not pass!\n");
}
}
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.