Search code examples
ccs50credit-card

CS50 Problem set 1 Credit - can't find the logic error


When I enter a credit card number that should work it outputs "INVALID" when it should output the credit card brand. I believe something is going wrong in the validity function but i can't seem to figure out what. I've spent a couple hours trying to fix the problem but nothing has worked. It would be great if I could get some help, thanks so much!

This is my code:

#include <stdio.h>
#include <cs50.h>

bool validity(long long creditNum);
int find_length(long long n);
bool checksum(long long ccn);
void credit_card_num(long long ccn);

int main(void)
{
    long long creditNum;
    do
    {
    creditNum = get_long_long("Enter Card Number: ");
    }
    while(creditNum < 0);

    if (validity(creditNum) == true)
        credit_card_num(creditNum);
    else
        printf("INVALID\n");
}

bool validity(long long creditNum)
{
    int length = find_length(creditNum);
    if ((length == 13 || length == 15 || length == 16) && checksum(creditNum))
       return true;
    else
       return false;  
}

int find_length(long long n)
{
    int length;
    for (length = 0; n != 0; n/= 10)
    length++;
    return length;
}

bool checksum(long long ccn)
{
    int sum = 0;
    int digit;
    for (int i = 0; ccn != 0; i++, ccn /= 10)
    {
        if (i % 2 == 0)
           sum += ccn % 10;
        else
        digit = 2 * (ccn % 10);
        sum += digit / 10 + digit % 10;
    }
    if ((sum % 10) == 0)
       return true;
    else
       return false;
}

void credit_card_num(long long ccn)
{
    if ((ccn >= 34e13 && ccn < 35e13) || (ccn >= 37e13 && ccn < 38e13))
        printf("AMEX\n");
    else if (ccn >= 51e14 && ccn < 56e14)
        printf("MASTERCARD\n");
    else if ((ccn >= 4e12 && ccn < 5e12) || (ccn >= 4e15 && ccn < 5e15))
        printf("VISA\n");
    else
        printf("INVALID\n");
}

Solution

  • It looks like your error is in your checksum function; specifically, the for loop.

    for (int i = 0; ccn != 0; i++, ccn /= 10)
    {
        if (i % 2 == 0)
           sum += ccn % 10;
        else
        digit = 2 * (ccn % 10);
        sum += digit / 10 + digit % 10;
    }
    

    should be

    for (int i = 0; ccn != 0; i++, ccn /= 10)
    {
        if (i % 2 == 0){
           sum += ccn % 10;
        } else {
           digit = 2 * (ccn % 10);
           sum += digit / 10 + digit % 10;
        }
    }
    

    There was incorrect nesting around your if-else statement. I tested with a couple numbers and they printed the correct output.