Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 1. Takes card number
- 2. Gets number of digits in card number. Invalid if not 13, 15 or 16.
- 3. Gets first two digits of card number to check later.
- 4. Uses Luhn's algorithm on card number to get "sum"
- 5. Checks if last digit of sum is 0. Invalid if not.
- 6. If it is, checks first digit(s) to match to correct card. Invalid if no match.
- */
- #include <cs50.h>
- #include <stdio.h>
- int get_digit_length(long long num);
- int main(void)
- {
- printf("Card number: ");
- long long num = GetLongLong();
- // count digits in num
- int digit_length = get_digit_length(num);
- if (digit_length != 13 && digit_length != 15 && digit_length != 16 )
- {
- printf("INVALID\n");
- return 0;
- }
- // get first two digits of num to check amex/mastercard/visa
- long long first_two = num;
- while (first_two >= 100)
- first_two /= 10;
- // implement Luhn's algorithm
- int sum = 0;
- while (num)
- {
- // get last/second-last digits of num
- int last_digit = num % 10;
- int second_last_digit = (num / 10) % 10;
- // multiply by 2 and separate digits if product > 9
- int product = second_last_digit * 2;
- if (product > 9)
- product = 1 + (product - 10);
- sum += (product + last_digit);
- // divide to move to next pair of digits
- num /= 100;
- }
- // check that sum ends in zero and match to correct card if so.
- if (sum % 10 != 0)
- printf("INVALID\n");
- else if (first_two == 34 || first_two == 37)
- printf("AMEX\n");
- else if (first_two >= 51 && first_two <= 55)
- printf("MASTERCARD\n");
- else if (first_two / 10 == 4)
- printf("VISA\n");
- else
- printf("INVALID\n"); // in case Luhn's checks out, but not amex/mc/visa
- }
- // counts digits in num
- int get_digit_length(long long num)
- {
- int count = 0;
- while (num)
- {
- num = num / 10;
- count++;
- }
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement