/*
 * Copyright (c) 2004 Kamo Hiroyasu
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * A solution of "Golsbach's Conjecture"
 *  Author: Kamo Hiroyasu <wd@ics.nara-wu.ac.jp>
 */

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

#define INPUT_FILE	"goldbach.txt"
#define MAX_INPUT	0x8000
unsigned int	count_goldbach_pairs(unsigned int);

/*
 *  Test an odd number greater than or equal to 3 for any prime number.
 *  This function may return a false result if the input is 1 or an
 *  even number.
 */
static int
isprime_quick(unsigned int x)
{
	unsigned int	i;

	for (i = 3; i * i <= x; i += 2) {
		if (x % i == 0) {
			return 0;
		}
	}
	return 1;
}

unsigned int
count_goldbach_pairs(unsigned int x)
{
	unsigned int	s;
	unsigned int	i, j;

	switch (x) {
	case 0:
	case 1:
	case 2:
	case 3:
		return 0;
	case 4:
	case 5:
		return 1;
	}
	if (x % 2 == 0) {
		return 0;
	}
	s = 0;
	for (i = 3, j = x - 3; i <= j; i += 2, j -= 2) {
		if (isprime_quick(i) && isprime_quick(j)) {
			s ++;
		}
	}
	return s;
}

main(int argc, char *argv[])
{
	char		*path;
	FILE		*fp;
	unsigned int	n;

	switch (argc) {
	case 1:
		path = INPUT_FILE;
		break;
	case 2:
		path = argv[1];
		break;
	default:
		fprintf(stderr, "%s: too many arguments\n", argv[0]);
		return 1;
	}
	fp = fopen(path, "r");
	if (fp == NULL) {
		perror(path);
		exit(1);
	}
	while (fscanf(fp, "%u", &n) == 1 &&
	       n >= 4 && n % 2 == 0 && n <= MAX_INPUT) {
		printf("%u\n", count_goldbach_pairs(n));
	}
	return 0;
}
