-1

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

Shah
  • 3
  • 4
  • Luhn's algorithm returns 1 digit so how can the expected result be 22? – Allan Wind Oct 24 '22 at 00:26
  • You misunderstand what I'm doing. I'm only working on half the logic. I'm kind of a noob programmer so I'm doing it one piece at a time. – Shah Oct 24 '22 at 00:42
  • Do you think it might be confusing when you say "I'm trying to implement Luhn's algorithm.", when in fact you are doing something else? – Allan Wind Oct 24 '22 at 00:55
  • yeah, but you could have ignored it if it was so confusing? i followed all the guidelines of posting a question here. – Shah Oct 24 '22 at 00:57
  • I deleted my answer as I lost all interest in helping you. – Allan Wind Oct 24 '22 at 01:04

1 Answers1

1

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.

NoDakker
  • 3,390
  • 1
  • 10
  • 11
  • Works perfectly, thanks. But I'm a little confused - to get to the second-to-last digit `8` in `123456789`... you just divide it by 10 once. Modding it will give you `8`. So why is it that you need to divide by `10` the first but need to divide by `100` everytime after? I can't figure that out and it hurts my brain a little. – Shah Oct 24 '22 at 00:40