The Luhn algorithm is mainly used to calculate the legitimacy of credit card numbers. 1, starting from the last digit of the card number, the even digit is multiplied by 2, if the result multiplied by 2 is a double digit, the number of two digits is added to save. 2, add all the numbers, get the sum. 3. If the credit card number is legal, the sum can be divisible by 10
#include <stdio.h> #include <string.h> #include <stdlib.h>int main (int argc, const char * argv[]) { Char num[30]; while (gets (num)!=null) { int len= (int) strlen (num); int sum=0; int tmp; for (int i=len-1;i>=0;i--) { if ((len-i)%2==1) //odd digit sum+=num[i]-' 0 '; else //even digit { tmp= (num[i]-' 0 ') * *; sum+=tmp>=10?tmp-9:tmp; } } printf ("sum=%d\n", sum); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C Language Implementation Luhn check