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 (i.e., 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;}
}