3 ms·
I've been waiting decades for anyone to be interested in a divisible-by-7 test that works right-to-left. Only 7 states required: #include <stdio.h> int x
by drfuchs 14y ago
I've been waiting decades for anyone to be interested in a divisible-by-7 test that works right-to-left. Only 7 states required:
#include <stdio.h>
int x[7][10] = {
/* 0 */ {0, 2, 4, 6, 1, 3, 5, 0, 2, 4},
/* 1 */ {5, 0, 2, 4, 6, 1, 3, 5, 0, 2},
/* 2 */ {3, 5, 0, 2, 4, 6, 1, 3, 5, 0},
/* 3 */ {1, 3, 5, 0, 2, 4, 6, 1, 3, 5},
/* 4 */ {6, 1, 3, 5, 0, 2, 4, 6, 1, 3},
/* 5 */ {4, 6, 1, 3, 5, 0, 2, 4, 6, 1},
/* 6 */ {2, 4, 6, 1, 3, 5, 0, 2, 4, 6}
};
int divisible_by_7(char *b)
{
char *p = b; while (*p) p++; // skip to NUL
int state = 0;
while (--p >= b)
state = x[state][*p-'0'];
return !state;
}
int main(int argc, char *argv[])
{
int i;
for (i = 1; i<argc; i++)
printf("%s is%s divisible by 7\n", argv[i], divisible_by_7(argv[i]) ? "" : "n't");
return 0;
}