// JavaScript for puzzle 3: Two logicians.

// Global variables.
var s = new Array(), p = new Array();

// Generate list of eligible sums.
function genSum(upperSum) {
	var upperX = Math.floor((upperSum-1)/2), c = 0, prod;
	// Populate p, number of eligible factorizations for each product.
	for (var i = 2; i <= upperX; i++)
		for (var j = i+1; i+j <= upperSum; j++)
			{if (p[prod=i*j]) p[prod]++; else p[prod] = 1;}
	// Populate s, list of sums that are never the sum of precisely two eligible factors.
	for (i = 2+3; i <= upperSum; i += 2) {
		var ok = true;
		for (j = 2; j < i-j; j++)
			if (p[j*(i-j)] == 1) {ok = false; break;}
		if (ok) s[c++] = i;
	}
	document.write('<p class="dc">', "Eligible sums:&nbsp; ", s.join(", "), ".</p>");
}

// Generate list of eligible products, with factors, in sum order.
function genProd() {
	var i, prod, sum, p2 = new Array(), si = new Array(), bg = ' style="background:#cfc"', newCell = "</td><td>", endRow = "</td></tr>";
	document.write('<div class="p">');
	document.write('<table summary="Eligible products and sums." border="2" cellspacing="0" cellpadding="3" class="dc"><caption id="db">Eligible products and sums</caption><thead align="right"><tr><th scope="col" width="30%">Product</th><th scope="col" width="20%">x</th><th scope="col" width="20%">y</th><th scope="col" width="30%">Sum</th></tr><tbody align="right">');
	// Populate p2, lower factor for each product such that precisely one sum of eligible factors is in list of eligible sums.
	for (var r = 0; r < s.length; i = s[r++])
		for (var j = 2; j < i-j; j++)
			if (p[prod=j*(i-j)] > 1) {if (p2[prod]) p2[prod] = 0; else p2[prod] = j;}
	// Build si, indexed by sum, from p2.
	for (r in p2)
		if (p2[r] > 0) {
			if (!si[sum=p2[r]+r/p2[r]]) si[sum] = new Array();
			si[sum][si[sum].length] = p2[r];
		}
	// Write table, in sum order, highlighting answer.
	for (r = 0; r < s.length; i = s[r++])
		if (si[i])
			for (j = 0; j < si[i].length; j++)
				document.write("<tr", si[i].length==1 ? bg : '', "><t", "d>", si[i][j]*(i-si[i][j]), newCell, si[i][j], newCell, i-si[i][j], newCell, i, endRow);
	document.write("</tbody></table></div>");
}
