0

enter image description here

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

int main(void)
{

    long long cc;

    //get user input for cc
    do
    {
        cc = get_long_long("Number: ");

    } while (cc <= 0);

    //check if cc length is 13, 15, 16

    long long num = cc;
    int digits = 1;

    do
    {
        num /= 10;
        digits++;
    } while (num >= 10);

     if (digits != 13 && digits != 15 && digits != 16)
    {
        printf("Invaild number\n");
        return 1;
    }

    //check if cc is legit according to Luhn's Algorithm

    int number[digits], even[digits];
    int i, sum = 0;

    for (i = 0; i < digits; i++)
    {
        number[i] = cc % 10;
        cc /= 10;

        if (i % 2 == 1)
        {
            even[i] = number[i];
            even[i] *= 2;
        }
        if (even[i] >= 10)
        {
            even[i+1] = even[i] / 10;
            even[i] = even[i] % 10;
        }

        sum += even[i];

        if (i % 2 == 0)
        {
            sum += number[i];
        }

    }

    if (sum % 10 != 0)
    {
        printf("INVALID\n");
    }

    else
    {
        //check if cc is 15 digits starting with 34, 37
        if (digits == 15 && number[14] == 3 && (number[13] == 4 || number[13] == 7))
        {
            printf("AMEX\n");
        }

        //check if cc is 16 digits starting with 51, 52, 53, 54, 55
        if (digits == 16 && number[15] == 5 && (number[14] == 1 || number[14] == 2 || number[14] == 3 || number[14] == 4 || number[14] == 5))
        {
            printf("MASTERCARD\n");
        }

        //check if cc is 13 or 16 digits starting with 4
        if ((digits == 13 && number[12] == 4) || (digits == 16 && number[15] == 4))
        {
            printf("VISA\n");
        }
    }

    return 0;

}

Hi I can't figure out the problem of my code because debug50 runs fine... It says INVALID and then when I debug it says AMEX. same for VISA. what would be the problem?? Thanks in advance!

0

I think it's because of your conditions because of the your code above the digits of your number change(the numbers you multiply by 2) (digits == 15 && number[14] == 3 && (number[13] == 4 || number[13] == 7)) Your conditions here are based on the original number, but you've already multiplied every other number by 2, which makes the 4 and 7 here will no longer be correct. Since your algorithm multiplies 7 * 2 then if it is > 9, we separate the digits then add them together.. so for 7 * 2 = 14 -> 1 + 4 = 5 that should now be your expected digit in the index 13, and for 4 * 2 = 8 since 8 is less than 10 we don't need to do anything else with it, so in the index 13 we expect either an 8 or a 5...

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .