Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <math.h>
- int main(void)
- {
- long number = get_long("Number: ");
- long card_number = number; // create a copy of number to use for card type validation
- int digit_count = 0;
- int sum_of_products = 0;
- int sum_of_digits = 0;
- while (number != 0)
- {
- int digit = number % 10;
- digit_count++;
- // multiply every other digit by 2, starting with second-to-last
- if (digit_count % 2 == 0)
- {
- int product = digit * 2;
- sum_of_products += product / 10 + product % 10;
- }
- else
- {
- sum_of_digits += digit;
- }
- number /= 10;
- }
- // add the two sums together
- int total_sum = sum_of_products + sum_of_digits;
- // validate card type using card_number variable
- if (total_sum % 10 == 0)
- {
- if (digit_count == 15 && (card_number / (long)pow(10, 13) == 34 || card_number / (long)pow(10, 13) == 37))
- {
- printf("AMEX\n");
- }
- else if (digit_count == 16 && (card_number / (long)pow(10, 14) >= 51 && card_number / (long)pow(10, 14) <= 55))
- {
- printf("MASTERCARD\n");
- }
- else if ((digit_count == 13 || digit_count == 16) && (card_number / (long)pow(10, digit_count - 1) == 4))
- {
- printf("VISA\n");
- }
- else
- {
- printf("INVALID\n");
- }
- }
- else
- {
- printf("INVALID\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement