Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <math.h>
- long get_ccn();
- int main(void)
- {
- //Get card number, copy to temp value so it can be manipulated and reset
- long ccn = get_ccn();
- long temp_ccn = ccn;
- //Reject if card number is not 13, 15, or 16 digits
- int length = (log10(ccn) + 1);
- if (length != 13 && length != 15 && length != 16)
- {
- printf("INVALID\n");
- return (0);
- }
- //Iterate through every other digit starting from the right
- temp_ccn = ccn;
- int sum = 0;
- for (int i = 1; i <= length; i++)
- {
- int digit = temp_ccn % 10L;
- if (i % 2 == 0)
- {
- //Multiply every other digit by two
- digit *= 2;
- //Subtract 9 to turn 2 digit product into a single int, because math
- if (digit > 9)
- {
- digit -= 9;
- }
- }
- //Add digit or digit*2 to running total, divide by 10 to get to next number
- sum += digit;
- temp_ccn /= 10L;
- }
- //Check if last digit of sum is 0
- if (sum % 10 != 0)
- {
- printf("INVALID\n");
- return (0);
- }
- //Determine issuer based on first two digits
- temp_ccn = ccn;
- while (temp_ccn > 100L)
- {
- temp_ccn = temp_ccn / 10L;
- }
- if ((temp_ccn / 10 == 4) && (length == 13 || length == 16))
- {
- printf("VISA\n");
- }
- else if ((temp_ccn == 34 || temp_ccn == 37) && length == 15)
- {
- printf("AMEX\n");
- }
- else if ((temp_ccn > 50 && temp_ccn < 56) && length == 16)
- {
- printf("MASTERCARD\n");
- }
- else
- {
- printf("INVALID\n");
- }
- }
- //FUNCTIONS
- //Get Card Number
- long get_ccn()
- {
- long i = 0L;
- while (i < 1L || i > 9999999999999999L)
- {
- i = get_long("Enter card number:\n");
- }
- return i;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement