PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] When i use my code in local vscode its giving only 63 as answer but when i use a different online complier it works fine

 July 20, 2022     c, function-definition, integer, long-integer, luhn     No comments   

Issue

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.


Solution

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.



Answered By - Vlad from Moscow
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing