/* 2020/2021 North America Championship International Collegiate Programming Contest Problem ? You be the Judge M. K. Furon. 2021-04-08. */ #include #include #include #include #include int addend1, addend2, i, iocount, j, sum; char isprime[65536], inputbuffer[102400]; void abend (char *message) { (void) fputs (message, stderr); (void) fputc ('\n', stderr); exit (4); } int printresult (char answer) { /* Print the answer and exit. */ (void) putchar (answer); (void) putchar ('\n'); exit (0); } int isaprime (int valuein) { int stophere; /* Do trial division of every prime up to the square root of the input value. Any multiple of a prime ends the test. */ if (valuein == 2) /* If value is 2 */ return (1); else if (!(valuein & 1)) /* If value is even */ return (0); stophere = 1 + (int) sqrt ((double) valuein); for (i = 3; i <= stophere; i += 2) { if (isprime[i]) if (!(valuein % i)) /* If value is multiple of prime */ return (0); } return (1); } int nextint (char *bufferpos) { int result; char *extratoken, *token; /* Get the next value from the input, verifying that it is an integer and there is no extra non-integer text following. */ token = strtok (bufferpos, " \t\n"); if (token == NULL) /* If no token exists */ printresult ('0'); else if ((isdigit (*token)) && (*token != '0')) { /* Token begins with a non-zero digit. Check to see if the token is a valid integer without extra trailing characters. */ result = (int) strtol (token, &extratoken, 10); if ((extratoken != NULL) && (*extratoken != ((char) 0))) printresult ('0'); else return (result); } else printresult ('0'); } int main (int argc, char *argv[], char *envp[]) { /* Ingest the input into a single buffer. */ iocount = fread (((void *) inputbuffer), ((size_t) 1), ((size_t) 101001), stdin); if (!feof (stdin)) abend ("Input too large."); /* Parse the three input values. Verify no additional token follows. */ sum = nextint (inputbuffer); addend1 = nextint (NULL); addend2 = nextint (NULL); if (strtok (NULL, " \t\n") != NULL) /* If more input is present */ printresult ('0'); /* Check the other input constraints--the first value is even and does not exceed 10^9, and the other two values add to the third. */ if ((sum < 4) || (sum > 1000000000) || (sum & 1)) printresult ('0'); if ((addend1 < 2) || (addend2 < 2) || (sum != addend1 + addend2)) printresult ('0'); /* At this point the only remaining check is for primality of the addends. Run the Sieve of Eratosthenes to find all primes that fit in sixteen bits. */ isprime[0] = isprime[1] = (char) 0; for (i = 2; i < 65536; i++) isprime[i] = (char) 1; for (i = 2; i < 256; i++) if (isprime[i]) for (j = i * i; j < 65536; j += i) isprime[j] = (char) 0; /* Check each addend for primality. */ if ((isaprime (addend1)) && (isaprime (addend2))) printresult ('1'); else printresult ('0'); /* Execution will never reach here. */ }