Why does Check50 work for certain credit numbers and not others? I ran debug and found that for some credit numbers and not others it may randomly be always one away from a multiple of 10 preventing checksum and a valid card numbers checksum is not passed.
2 Answers
First, it's typically easier for people to help you if you copy/paste your code (or just the relevant parts of your code), so they can try running your code.
But go through what happens if i = 7
, and multiplied_digits = 0
on line 27. i * 2 = 14
, so you should end up with multiplied_digits = 5
.
if((i * 2) > 9) // this is true, because (i * 2) is 14
{
multiplied_digits += ((i * 2) % 10); // ((i * 2) % 10) is 4, so multiplied_digits = 4
i = i- ((i * 2) % 10); // i = 7- ((7 * 2) % 10) = 7- (14 % 10) = 7- 4 = 3
i / 10; // i = 3 before this, so now i = 0 because the remainder is thrown away
multiplied_digits += i; // i = 0, so multiplied digits = 4 still
}
The fourth line of the snippet above is where you're going wrong, and why the Luhn sums you're getting are sometimes 1 off.
Also, it looks like you're not taking advantage of integer division. In C , 5 / 2 == 2
, because the remainder gets thrown away. (If you want the remainder, you need to cast one as a float.) You don't need to subtract the last digit before dividing by 10, because that will be thrown away anyway.
-
Thanks, I realised I made the mistake of not multiplying it by 2 so instead of line 2 being i = i- ((i * 2) % 10); I made it i = (i*2) - ((i * 2) % 10); It works amazing now!– AnonCommented Jul 24, 2020 at 23:21
in amex condition, number of zero's in the first condition is wrong. that is changing output of visa to amex..
-
I tried that and it did help for some numbers but I also ran debug and found that for some credit numbers and not others it may randomly be always one away from a multiple of 10 preventing checksum and a valid card numbers checksum is not passed.– AnonCommented Jul 24, 2020 at 21:27