Skip to content

Instantly share code, notes, and snippets.

@t81lal
Created December 24, 2018 22:51
Show Gist options
  • Save t81lal/267a71c4f8def6255fd123457fee991c to your computer and use it in GitHub Desktop.
Save t81lal/267a71c4f8def6255fd123457fee991c to your computer and use it in GitHub Desktop.
luhn.c
#include <stdio.h>
#include <ctype.h>
int checksum(char *str) {
int cs = 0;
int length = 0;
char *c;
/* get sequence length and validate chars in it */
for(c=str; *c; c++, length++) {
if(!isdigit(*c)) {
return -1;
}
}
/* go back one character to ignore the null terminator.
* c is now equal to the last digit in the sequence. */
c--;
for(int i=0; i < length; i++, c--) {
int v = *c - '0';
if((i % 2) == 0) {
cs += v;
} else {
v *= 2;
/* the sum of the digits of a number, n, between 10 and 19
* is the same as n-9 */
if(v > 10) {
v -= 9;
}
cs += v;
}
}
return cs;
}
int is_valid_checksum(int checksum) {
return (checksum % 10) == 0;
}
int main(int argc, char *argv[]) {
int cs = checksum("378282246310005");
int valid = is_valid_checksum(cs);
printf("cs=%d, valid=%s\n", cs, valid ? "true" : "false");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment