Home > Mobile >  Trying to implement Luhn's algorithm in C, but not getting expected sum of every other digit
Trying to implement Luhn's algorithm in C, but not getting expected sum of every other digit

Time:10-24

I'm trying to implement Luhn's algorithm. For every other digit you have to take it, multiply it by 2, and add it to a running total. If the ith digit * 2 is greater than 10, you split it up, and just add it to the running total. I create a void function that does this and pass in 123456789 as a test value.

#include <stdio.h>
// #include <cs50.h> // 

void LuhnsAlgorithm(long); // needs to be changed to str return type when submitted
int main()
{


    int num = 123456789;
    LuhnsAlgorithm(num);
}

void LuhnsAlgorithm(long cc) // return type will be str when submitting
{
    int sum = 0;
    // case 1

    // case 2 (every other odd digit, multiplied by 2, and then added)
    long case2 = cc;
    while (case2 > 0)
    {
        if ((case2 / 10 % 10) * 2 >= 10) // checks if the every-other-digit's product when multiplied by 2 is bigger than 10 (aka, has 2 digits)
        {
            // creating this stupid temp variable 
            int digitBreakUp = case2 / 10 % 10 * 2;
            sum  = (digitBreakUp / 10)   (digitBreakUp % 10);
        }
        else // if the product is just 1 digit then add it to the sum
        {
            sum  = (case2 / 10 % 10) * 2;
        }
        case2 = case2 / 10;
    }

    printf("The sum of every last other digit in 123456789 is %i\n", sum);
}

The expected sum should be 22 (8 --> 1 6, 6 --> 1 2, 4 --> 8, 2 --> 4). But, I get 36. What's wrong? How do I get to 0 / get it to 'stop iterating' until it reaches the beginning of the number?

Thanks

CodePudding user response:

Since your test is for every other digit, the line of code:

case2 = case2 / 10;

Should be:

case2 = case2 / 100;

If you do that, your summation of every other digit does come out to 22.

Give that a try.

  • Related