Consider the swap gate that we implemented in problem A2.
Solution 1
First, let's consider 2 qubits swap.
Swapping the first and second qubits can be achieved using a controlled X gate, and the state transitions are as follows.
By repeating this operation n−1 times, the desired quantum state ∣xn−1x0x1⋯xn−2⟩ can be prepared with a depth of 2(n−1).
The circuit diagram for n=3 is as follows.
Solution 2
As mentioned in the editorial of A2, the XOR swap algorithm is a classical algorithm to swap 2 variables x and y in 3 steps.
When y=0, the third step of "replace y with x+y(mod2)" can be omitted, so XOR swap can be achieved in 2 steps by replacing "replace y with x+y(mod2)" and "replace x with x+y(mod2)".
By utilizing this, we can solve this problem.
First, replace y with x+y(mod2) using a controlled X gate for 1,2,…,n−1 bits.
for i in reversed(range(n - 1)): qc.cx(i, i + 1)
Next, replace x with x+y(mod2) using a controlled X gate for 1,2,…,n−1 bits.
for i in reversed(range(n - 1)): qc.cx(i + 1, i)
Consequently, the desired quantum state ∣xn−1x0x1⋯xn−2⟩ can be prepared with a depth of 2(n−1).
The circuit diagram for n=3 is as follows.
Sample Code
Below is a sample program:
Solution 1
from qiskit import QuantumCircuitdef solve(n: int) -> QuantumCircuit: qc = QuantumCircuit(n) for i in reversed(range(n - 1)): qc.cx(i, i + 1) qc.cx(i + 1, i) return qc
Solution 2
from qiskit import QuantumCircuitdef solve(n: int) -> QuantumCircuit: qc = QuantumCircuit(n) for i in reversed(range(n - 1)): qc.cx(i, i + 1) for i in reversed(range(n - 1)): qc.cx(i + 1, i) return qc