简体   繁体   中英

I couldn't understand why my function does not work

So this should do Luhn's algorithms needs from Harward cs50 pset1. But it has some flow in it which ı could not find. Normally the while loop's condition is not coun it 8 times but while testing it ı thought: first ı should solve the flow in functions work. Luhn's Algorithm work as the following for the ones who can't recall:

Multiply every other digit by 2, starting with the number's second-to-last digit, and then add those products' digits together.

Add the sum to the sum of the digits that weren't multiplied by 2.

If the total's last digit is 0 (or, put more formally, if the total modulo 10 is congruent to 0), the number is valid!

And that's the sample input:

That's kind of confusing, so let's try an example with David's Visa: 4003600000000014.

For the sake of discussion,

let's first underline every other digit,

starting with the number's second-to-last digit:

4003600000000014

Okay, let's multiply each of the underlined digits by 2:

1•2 + 0•2 + 0•2 + 0•2 + 0•2 + 6•2 + 0•2 + 4•2

That gives us:2 + 0 + 0 + 0 + 0 + 12 + 0 + 8

Now let's add those products' digits (ie, not the products themselves) together:

2 + 0 + 0 + 0 + 0 + 1 + 2 + 0 + 8 = 13

Now let's add that sum (13) to the sum of the digits that weren't multiplied by 2 (starting from the end):13 + 4 + 0 + 0 + 0 + 0 + 0 + 3 + 0 = 20

Yup, the last digit in that sum (20) is a 0, so David's card is legit!

And this is my function.

bool checkdigits(long long x)
{   int power();
    int checklength();
    long counter,sum,summ2,multp2,index;
    sum=0;
    summ2=0;
    index=1;
    counter=0;
while(!(counter == 8))
    {
    sum+=x/power(10,index)%10;
    multp2=(x/power(10,index))%10*2;
    if(multp2 >= 10)
    {summ2 += (multp2 % 10)+1;}
    else if(multp2 < 10)
    {summ2 += multp2 % 10;}
    index = index+2;
    counter++;
    }


if((sum + summ2)%10 == 0)
{return true;}
else
{return false;}
}

As Weather Vane pointed out, it's easier to use a string instead:

bool checkdigits(const char* number)
{
    long long sum1 = 0, sum2 = 0;

    for (int i = strlen(number) - 1; i >= 0; i -= 2) // single add every second
        sum1 += number[i] - '0';
    for (int i = strlen(number) - 2; i >= 0; i -= 2) // double add every other second
        sum2 += 2 * (number[i] - '0') - ((number[i] - '0') > 4 ? 9 : 0);
                                       // number > 4 => 2 * number > 10
                                       // therefore subtract 9

    return (sum1 + sum2) % 10 == 0;
}

I don't know cs50 but that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM