0

I just started CS50 this week with no background in CS. I don't understand what is wrong with my solution to credit, in pset1. I keep trying the example card number '378282246310005', but it returns invalid. It is very weird because when I check the length, sum, or id arguments alone, the output is in fact "AMEX"... i.e. by themselves each of the arguments work, just not together. Again, I am new to CS and I love it so far! I feel like I might be implementing operators wrong? Any help would be greatly appreciated. Side note: first post here and I'm sorry if something like this has been asked but I was unable to find a problem like mine. I think it is something minor?

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

long long card;
int checksum(long long h);
int checklength(long long k);
int checkid (long long q);

int main (void)
{
    printf("Credit Card Number Please: \n");
card= get_long_long();
int x= checksum(card)%10;
int y= checklength(card);
int z= checkid(card);
    if((y==16) && (z>=51 && z<=55) && (x==0) )
{
    printf("MASTERCARD\n");
}
else if((y==15) && (z==34 || z==37) && (x==0))
{
    printf("AMEX\n");
}
else if((y==13||y==16) && (z%10==4) && (x==0))
{
    printf("VISA\n");
}
else printf("INVALID\n");

}

int checksum(long long h)
{
h= card;
int total=0;
    for (int i=0; i<10;i++)
    {
        while (card)
        {
            int j= card%10;
            int k= (card/10)%10;
            if (2 * k< 10) 
                {
                    total= total + k* 2;
                }
            else
                {
                    total = total + 1 + (2 * k - 10);
                }
            total= total+ j;
            card/=100;
        }
    }
return total;
}

int checklength(long long k)
{
int counter=0;
while (k != 0)
{
    k/=10;
    counter++;
}
return counter;
}

int checkid (long long q)
{
while(q>100)
{
    q/=10;
}
return q;
}

2 Answers 2

1

Three things:

  1. VISA requires z/10==4, not z%10==4
  2. I'd use q >= 100 in checkid, so it's always the first two digits (not that there are any valid numbers starting with "100")
  3. Most important: Use h, not card in checksum!
  4. (BONUS: For-loop in checksum has no function)
1
  • Worked Beautifully! Thank you very much!!!
    – Justin
    Feb 28, 2017 at 20:01
0

I think I got my algorithm wrong. suppose card : 5105105105105100 (suppose to be MC)

1) Multiply every other digit by 2

2 10 0 2 10 0 2 0

2) and then add those products' digits together

2 + (1+0) + 0 + 2 + (1+0) + 0 + 2 sum= 8

3) Add the sum to the sum of the digits that weren’t multiplied by 2

5 + 0 + 1 + 5 + 0 + 1 + 5 + 0 sum1 = 17

4) total = add + add1 = 25

5) if (total last digit is 0) then "card valid"

Here total last digit is "5" so shouldn't card be invalid. My shows correctly but apparently this is suppose to be a MC.

Help me out here

You must log in to answer this question.

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