I'm new to programming, C and I'm trying to solve CS50's pset1 problem, Luhn's Algorithm to check if a credit card is valid. The example I'm using to test is this card Visa: 4003600000000014.
As referred in the problem, first underline every other digit, starting with the number’s second-to-last digit:
[4] 0 [0] 3 [6] 0 [0] 0 [0] 0 [0] 0 [0] 0 [1] 4
Multiply the underlined digits by 2:
1•2 + 0•2 + 0•2 + 0•2 + 0•2 + 6•2 + 0•2 + 4•2
That gives:
2 + 0 + 0 + 0 + 0 + 12 + 0 + 8
Add those products’ digits (i.e., not the products themselves) together:
2 + 0 + 0 + 0 + 0 + 1 + 2 + 0 + 8 = 13
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
// Variable assignment
long card;
int case1, case2, mod, mod2;
// Get input from user
do
{
card = get_long("Card: ");
}
while (card <= 0);
// Case 1
for (long checksum = card; checksum > 0; checksum = checksum / 10)
{
mod = remainder(checksum, 10) * 2;
if (mod >= 10)
{
mod2 = remainder (mod, 10);
case1 = case1 + mod2;
mod = mod / 10;
case1 = case1 + mod;
}
else
{
case1 = case1 + mod;
}
checksum = checksum / 10;
printf("\n%d", case1);
}
}
My output:
~/pset1/credit/ $ ./credit
Card: 4003600000000014
8
8
8
8
8
8
14
14
The number printed should be 13, for some reason the number my output is printing is 14. I've tried to make changes to the code, although i get outputs of 2 and -6. Tried CS50 debug tool too, without success. What is my code missing in order to have an output of 13?