USACO OCT09 Problem 'evenodd' Analysis

by Fatih Gelgi

The simple trick in this problems is to check whether a number is even or odd by only checking the last digit; not the entire number with modulo 2 operation.

Thus, it is not necessary to read the input as a number (or convert it to a number) but just read it as characters (or string) then check if the last digit is even or odd. Below is Rob Kolstad's solution:

#include <stdio.h>
#include <stdlib.h>

main() {
    FILE *fin = fopen ("evenodd.in", "r");
    FILE *fout = fopen ("evenodd.out", "w");
    int i, n, parity;
    int c;
    fscanf (fin, "%d", &n);
    fgetc(fin);		/* gobble newline */
    for (i = 0; i < n; i++) {
	for (;;) {
	    c = fgetc(fin);
	    if (c == '\n') break;
	    parity = c % 2;
	}
	if (parity == 0) fprintf (fout, "even\n");
	else             fprintf (fout, "odd\n");
    }
    exit (0);
}