TL;DR: My Luhn's algorithm function works flawlessly in JavaScript but not in C. In C, it ends up with the wrong total when multiplying every other digit. Could this be a data type conversion problem (int vs. float vs. long long)?

Detailed explanation:

I am working my way through the "credit" challenge one piece at a time. My current code, although incomplete for the full challenge, ought to be functional for what it is: it is supposed to take every other digit of the number entered, starting with the second-to-last one and moving in the direction of the first one; multiply each one of those digits by two; and add the result of each of these multiplications to a variable called "total".

My code is here: https://repl.it/JT3S/2 (Unfortunately you can't run it in repl.it due to the absence of the cs50.h library, but at least you can see it, and I tried to use sensible variable names and comment it clearly to help orient the reader.)

I split the whole thing up into separate functions for clarity. The problem appears to be in the function "addmultbytwo", specifically on line 62, I believe.

Note: I have some prior experience with JavaScript, so I translated all the code I have so far into JS, and in that language it works flawlessly. This is why I suspect that the problem may lie in my lack of understanding of the various data types in C and how to convert them into each other.

Here is a screenshot of my terminal when I run the current code (I added a bunch of "printf" lines for line-by-line debugging, which results in all the text you see): terminal screenshot

Note that right after I give it my input, the "currentcc" (user-inputted number, in this case 12341234123412) is displayed correctly. The next line is also correct: it "pops off" the last digit, 2. In the line after that, however – the one that starts "getlastdigitofthis is currently" – the number has suddenly changed completely! So clearly that's where the error lies... but what IS the error?

Any advice is greatly appreciated!


int chopoffend(long long n)

int in C is 4 bytes max, that is 2^32 -> 10 digits max

  • Thank you, obesman! Indeed, that fixed my problem. I need to learn more about the maximum byte size of the various data types. – Jinx Montague Jul 9 '17 at 15:11

You must log in to answer this question.

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