This is a Luhn algorithm code and it works fine in an online complier but when I use it in my local vscode it is only giving 63 as output.
I dont know if its a memory issue as it late long variable.
i.e credit card number as input.
#include <stdio.h>
// Finds its Luhn algorithm to see if its a valid credit card number.
void checksum(long num)
{
int sum = 0;
for (int i = 0; num != 0; num /= 10, i++)
{
if (i % 2 == 0)
{
sum = sum + num % 10;
}
else
{
int digit = 2 * (num % 10);
sum = sum + (digit / 10) + (digit % 10);
}
}
printf("%d", sum);
}
int main()
{
long int num;
// Takes credit Card number as input.
do
{
printf("Number: ");
scanf("%li", &num);
} while (num < 0);
checksum(num);
return 0;
}
My inputs are like 374245455400126
,378282246310005
.
And output is always 63
.
The result depends on the size of the type long int
that can be equal either to the size of the type int
or to the size of the type long long int
.
So use the type long long int
instead of the type long int
.
Also as the program expects an unsigned value then instead of the signed type long long int
it is even better to use the type unsigned long long int
.