Advertisement
voodoo_curse

credit.c

Jul 1st, 2020
3,069
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <math.h>
  4.  
  5. long get_ccn();
  6.  
  7. int main(void)
  8. {
  9.     //Get card number, copy to temp value so it can be manipulated and reset
  10.     long ccn = get_ccn();
  11.     long temp_ccn = ccn;
  12.  
  13.     //Reject if card number is not 13, 15, or 16 digits
  14.     int length = (log10(ccn) + 1);
  15.     if (length != 13 && length != 15 && length != 16)
  16.     {
  17.         printf("INVALID\n");
  18.         return (0);
  19.     }
  20.  
  21.     //Iterate through every other digit starting from the right
  22.     temp_ccn = ccn;
  23.     int sum = 0;
  24.  
  25.     for (int i = 1; i <= length; i++)
  26.     {
  27.         int digit = temp_ccn % 10L;
  28.  
  29.         if (i % 2 == 0)
  30.         {
  31.             //Multiply every other digit by two
  32.             digit *= 2;
  33.             //Subtract 9 to turn 2 digit product into a single int, because math
  34.             if (digit > 9)
  35.             {
  36.                 digit -= 9;
  37.             }
  38.         }
  39.         //Add digit or digit*2 to running total, divide by 10 to get to next number
  40.         sum += digit;
  41.         temp_ccn /= 10L;
  42.     }
  43.  
  44.     //Check if last digit of sum is 0
  45.     if (sum % 10 != 0)
  46.     {
  47.         printf("INVALID\n");
  48.         return (0);
  49.     }
  50.  
  51.     //Determine issuer based on first two digits
  52.     temp_ccn = ccn;
  53.     while (temp_ccn > 100L)
  54.     {
  55.         temp_ccn = temp_ccn / 10L;
  56.     }
  57.  
  58.     if ((temp_ccn / 10 == 4) && (length == 13 || length == 16))
  59.     {
  60.         printf("VISA\n");
  61.     }
  62.     else if ((temp_ccn == 34 || temp_ccn == 37) && length == 15)
  63.     {
  64.         printf("AMEX\n");
  65.     }
  66.     else if ((temp_ccn > 50 && temp_ccn < 56) && length == 16)
  67.     {
  68.         printf("MASTERCARD\n");
  69.     }
  70.     else
  71.     {
  72.         printf("INVALID\n");
  73.     }
  74. }
  75.  
  76. //FUNCTIONS
  77.  
  78. //Get Card Number
  79. long get_ccn()
  80. {
  81.     long i = 0L;
  82.     while (i < 1L || i > 9999999999999999L)
  83.     {
  84.         i = get_long("Enter card number:\n");
  85.     }
  86.     return i;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement