#include <cs50.h>
#include <stdio.h>
int main(void)
{
long num = get_long("What's your card number: " );
long countNum = num;
int count = 0;
while (countNum != 0)
{
countNum /= 10;
count++;
}
printf("%i", count);
int sum = 0;
long tempNum = num;
if (count == 13)
{
for (int i = 0; i < 7; i ++)
{
int n = i;
while (n != 0)
{
tempNum /= 100;
n--;
}
if (2 * (tempNum % 10) > 10) //should not matter if correct or incorrect in this case
{
sum = sum + ((2 * (tempNum % 10)) / 10) + ((2 * (tempNum % 10)) % 10);
}
else
{
sum += 2 * (tempNum % 10);
}
tempNum = num;
}
printf("%i", sum);
}
}
I am just making this part of the algorithm for 13 digit numbers and when i test: 4222222222222
(which supposedly should work) I get a value back of 1332
. Can anyone tell me where I am going wrong in my code? - I suspect something is probably wrong in the loop at the bottom.
Seeing as this issue is still open, I thought I would go ahead and highlight the main issue with the code in that it is not including all of the digits in the hash total check. With that following is a refactored version of your program that includes the addition of the other digits to the hash total.
The key bits to note are as follows:
Additional print statements were added just for debugging and illustration purposes. With that following is a test of the refactored code.
As an additional bit of information, you might want to refer to the following Wikipedia link about the Luhn algorithm:
"https://en.wikipedia.org/wiki/Luhn_algorithm"
That might be helpful in making the card testing more generic as credit card numbers can be lengths other than thirteen digits.