Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. /*
  2. 1. Takes card number
  3. 2. Gets number of digits in card number. Invalid if not 13, 15 or 16.
  4. 3. Gets first two digits of card number to check later.
  5. 4. Uses Luhn's algorithm on card number to get "sum"
  6. 5. Checks if last digit of sum is 0. Invalid if not.
  7. 6. If it is, checks first digit(s) to match to correct card. Invalid if no match.
  8. */
  9. #include <cs50.h>
  10. #include <stdio.h>
  11.  
  12. int get_digit_length(long long num);
  13.  
  14. int main(void)
  15. {
  16. printf("Card number: ");
  17. long long num = GetLongLong();
  18.  
  19. // count digits in num
  20. int digit_length = get_digit_length(num);
  21. if (digit_length != 13 && digit_length != 15 && digit_length != 16 )
  22. {
  23. printf("INVALID\n");
  24. return 0;
  25. }
  26.  
  27. // get first two digits of num to check amex/mastercard/visa
  28. long long first_two = num;
  29. while (first_two >= 100)
  30. first_two /= 10;
  31.  
  32. // implement Luhn's algorithm
  33. int sum = 0;
  34. while (num)
  35. {
  36. // get last/second-last digits of num
  37. int last_digit = num % 10;
  38. int second_last_digit = (num / 10) % 10;
  39.  
  40. // multiply by 2 and separate digits if product > 9
  41. int product = second_last_digit * 2;
  42.  
  43. if (product > 9)
  44. product = 1 + (product - 10);
  45.  
  46. sum += (product + last_digit);
  47.  
  48. // divide to move to next pair of digits
  49. num /= 100;
  50. }
  51.  
  52. // check that sum ends in zero and match to correct card if so.
  53. if (sum % 10 != 0)
  54. printf("INVALID\n");
  55. else if (first_two == 34 || first_two == 37)
  56. printf("AMEX\n");
  57. else if (first_two >= 51 && first_two <= 55)
  58. printf("MASTERCARD\n");
  59. else if (first_two / 10 == 4)
  60. printf("VISA\n");
  61. else
  62. printf("INVALID\n"); // in case Luhn's checks out, but not amex/mc/visa
  63. }
  64.  
  65. // counts digits in num
  66. int get_digit_length(long long num)
  67. {
  68. int count = 0;
  69. while (num)
  70. {
  71. num = num / 10;
  72. count++;
  73. }
  74. return count;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement