/
ch10_04_unsatisfiable_3sat.qs
54 lines (44 loc) · 2.05 KB
/
ch10_04_unsatisfiable_3sat.qs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
namespace QSharp.Chapter10
{
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
// Example 10-4: Unsatisfiable 3-SAT problem
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Measurement;
operation SolveUnsatisfiableSAT () : Unit {
// Allocate the qubits
use (inputs, clauses) = (Qubit[3], Qubit[4]);
// Prepare the inputs in a superposition of all states
ApplyToEach(H, inputs);
within {
// Clause 1: a OR b = inputs[0] OR inputs[1]
ComputeOrClause(inputs[0..1], [false, false], clauses[0]);
// Clause 2: NOT a OR c = NOT inputs[0] OR inputs[2]
ComputeOrClause(inputs[0..2..2], [true, false], clauses[1]);
// Clause 3: NOT b OR NOT c = NOT inputs[1] OR NOT inputs[2]
ComputeOrClause(inputs[1..2], [true, true], clauses[2]);
// Clause 4: a OR c = inputs[0] OR inputs[2]
ComputeOrClause(inputs[0..2..2], [false, false], clauses[3]);
// New clause 5 is b itself, so doesn't need an extra input to be computed
} apply {
// Compute the (phase-encoded) result
Controlled Z(clauses, inputs[1]);
}
// Dump the state of inputs (the clauses are not entangled with them any longer).
// At this point the answer is phase-encoded.
Message("Computation result encoded in phases");
DumpRegister((), inputs);
// Convert the phase encoding into magnitudes encoding
MirrorRegister(inputs);
// Dump the state of qubits "boxes" again.
// At this point the answer is magnitudes-encoded.
Message("Computation result encoded in amplitudes");
DumpRegister((), inputs);
// Perform measurements to extract the result
let solution = ResultArrayAsBoolArray(MultiM(inputs));
Message($"Variables [a, b, c] = {solution}");
ResetAll(inputs);
}
}