1

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.

Karma0o7
  • 15
  • 5
  • 1
    Welcome to SO. What is your input and expected output? Different results with different compilers normally points towards undefined behaviour in your application. Uninitialized variables, overflow, etc. – Gerhardh Jan 15 '22 at 09:19
  • 2
    Your comment indicates that you are dealing with credit card numbers. These are not really numbers but more a sequence of digits. It is better to handle them as a string. Depending on your compiler it may easily happen that neither `int` nor `long int` can store values large enough for a credit card number. – Gerhardh Jan 15 '22 at 09:23
  • 1
    @Karma0o7 Use long long int instead pf long int. – Vlad from Moscow Jan 15 '22 at 09:24
  • inputs are stored in "num" variable which is long type and "sum" is at max 2 digit number so its should be fine with storing in int data type. – Karma0o7 Jan 15 '22 at 09:25
  • Please do not change your code to show the solution. That makes all comments and answers useless. It also makes the whole post useless for any future visitors if the problem is no longer present in the question. – Gerhardh Jan 15 '22 at 09:30

1 Answers1

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335