Build a bit-counting comparator using NAND logic gates A bit-counting comparator (BCC) is a logic circuit that takes some number of counting inputs A1, A2, A3, ..., An as well as inputs B1, B2, B4, B8, ... representing a number. It then returns 1 if the total number of A inputs that are on is greater than the number represented in binary by the B inputs (e.g. B1, B2, and B8 would make the number 11), and 0 otherwise.

For example, for a bit-counting comparator that takes 5 inputs, of which A2, A4, A5, and B2 are set to 1, will return 1 because there are 3 A inputs that are on, which is greater than 2 (the number represented by only B2 being on).

Your task is to create a bit-counting comparator that takes a total of 16 A inputs and 4 B inputs (representing bits from 1 to 8), using only two-input NAND gates, and using as few NAND gates as possible. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:


NOT: 1
AND: 2
OR: 3
XOR: 4


Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.

The logic circuit that uses the fewest NAND gates to produce a correct construction wins.
169 nands

Adds up the A's to get A{1,2,4,8,16}.  Then does a binary comparison with the Bs.

I use a few more building blocks:


FA = full adder, 9 nands (from here)
HA = half adder, 7 nands (same ref)
EQ = equality, 5 gates (a.k.a. xnor)


The half and full adders have 2 outputs - they are distinguished with an r for result and c for carry.

The A{1,2,4,8,16} are the outputs from the half adders.