Advertisement
ValentinV

CS50 Credit

Apr 21st, 2023
2,121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | Software | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <math.h>
  4.  
  5. int main(void)
  6. {
  7.     long number = get_long("Number: ");
  8.  
  9.     long card_number = number; // create a copy of number to use for card type validation
  10.  
  11.     int digit_count = 0;
  12.     int sum_of_products = 0;
  13.     int sum_of_digits = 0;
  14.  
  15.     while (number != 0)
  16.     {
  17.         int digit = number % 10;
  18.         digit_count++;
  19.  
  20.         // multiply every other digit by 2, starting with second-to-last
  21.         if (digit_count % 2 == 0)
  22.         {
  23.             int product = digit * 2;
  24.             sum_of_products += product / 10 + product % 10;
  25.         }
  26.         else
  27.         {
  28.             sum_of_digits += digit;
  29.         }
  30.  
  31.         number /= 10;
  32.     }
  33.  
  34.     // add the two sums together
  35.     int total_sum = sum_of_products + sum_of_digits;
  36.  
  37.     // validate card type using card_number variable
  38.     if (total_sum % 10 == 0)
  39.     {
  40.         if (digit_count == 15 && (card_number / (long)pow(10, 13) == 34 || card_number / (long)pow(10, 13) == 37))
  41.         {
  42.             printf("AMEX\n");
  43.         }
  44.         else if (digit_count == 16 && (card_number / (long)pow(10, 14) >= 51 && card_number / (long)pow(10, 14) <= 55))
  45.         {
  46.             printf("MASTERCARD\n");
  47.         }
  48.         else if ((digit_count == 13 || digit_count == 16) && (card_number / (long)pow(10, digit_count - 1) == 4))
  49.         {
  50.             printf("VISA\n");
  51.         }
  52.         else
  53.         {
  54.             printf("INVALID\n");
  55.         }
  56.     }
  57.     else
  58.     {
  59.         printf("INVALID\n");
  60.     }
  61.  
  62.     return 0;
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement