You can either use the approach given or modular arithmetic. Both methods are of the same computational complexity, however, they differ in coding difficulty. A third solution is using big arithmetic which I won’t consider.
The operation explained in the statement modifies at most 4 digits of the integer. 1 digit for by removing the last digit (d) and –at most– 3 digits for the subtraction of (5 * d).
This suggest that: we perform the operation on the first 4 rightmost digits (which reduces them to 2 or 3 digits) then concatenate the next rightmost digit and repeat until the string is processed.
A little bit hard to code, but it works! Coded in C++, rank 451:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; char num[128], *numPtr; int n, i; int main() { while (scanf("%s", num) && !((numPtr = num + strlen(num) - 1) == num && *num == '0')) { for (n = 0, i = 1; numPtr >= num && i < 10000; i *= 10) n += (*(numPtr--) - '0') * i; while (numPtr >= num) { n = (n / 10) - (n % 10) * 5; if (n > 9999) n += (*(numPtr--) - '0') * 10000; else n += (*(numPtr--) - '0') * 1000; } printf("%d\n", (n % 17) == 0); } return 0; }
You parse the input like you would normally do for an integer, but you take modulo 17 as you compute. This utilizes addition and multiplication properties in modular arithmetic. C++ implementation with rank 456:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; char num[128], *numPtr; int n; int main() { while (scanf("%s", num) && !(strlen(numPtr = num) == 1 && *num == '0')) { n = 0; do n = (n * 10 + (*numPtr - '0')) % 17; while (*++numPtr != '\0'); printf("%d\n", (n % 17) == 0); } return 0; }