Product of maxterms

A function can be written as a sum of minterms (the rows that are 1) or as a product of maxterms (the rows that are 0). The second way is called the product of sums, or POS.

What to build

Print the maxterm list and the product-of-sums form of a function.

Requirements

  • The variables are A, B, C, D with A as the leftmost bit. The truth table's output column is one string of 0 and 1.
  • Line 1 is M( followed by the row numbers of the 0s separated by commas, then ).
  • Line 2 is the product of sums: every maxterm in brackets, with a complemented variable written with '. If the function is never 0, print 1.

Input

A line with n (1 to 4), then a line with the 2ⁿ output bits as one string.

Output

Two lines, as described.

Constraints

1 ≤ n ≤ 4.

Example

Input:

3
00010111

Output:

M(0,1,2,4)
(A + B + C)(A + B + C')(A + B' + C)(A' + B + C)

Why it works

A product is 0 as soon as one of its factors is 0, and each maxterm is 0 on exactly one row. So the product of the maxterms of the 0-rows is 0 on those rows, and 1 on every other row, which is the function. For 00010111 the 0-rows are 0, 1, 2 and 4, and the product is (A + B + C)(A + B + C')(A + B' + C)(A' + B + C).

Examples

Example 1 · Input
3
00010111
Expected output
M(0,1,2,4)
(A + B + C)(A + B + C')(A + B' + C)(A' + B + C)
Example 2 · Input
2
0110
Expected output
M(0,3)
(A + B)(A' + B')

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The maxterms of a function are the rows where the output is 0: row r is a maxterm when the output string has '0' at position r.

Hint 2

For each such row, write one OR term: a 0 bit gives the plain variable, a 1 bit gives the variable with a prime.

Hint 3

Put each OR term in brackets and write them next to each other with no sign between them.

Solution

Show one correct solution (try it yourself first)
n = int(input())
outputs = input().strip()
names = "ABCD"
zeros = [r for r in range(2 ** n) if outputs[r] == "0"]
print("M(" + ",".join(map(str, zeros)) + ")")
factors = []
for r in zeros:
    bits = format(r, "0" + str(n) + "b")
    factors.append("(" + " + ".join(names[i] + "'" if b == "1" else names[i] for i, b in enumerate(bits)) + ")")
print("".join(factors) if factors else "1")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Minterms, maxterms and canonical forms →