Editorial
Consider multiplying each probability amplitude of the computational basis states by .
The operation of multiplying by can be achieved using the gate, which leaves the computational basis state unchanged, and transforms into .
So, how can you apply the gate to only a specific computational basis state within a superposition state?
This can be accomplished as follows:
- For , apply the gate at index where . This transforms into .
- Apply a multiple-control gate1, using bits as control bits and the remaining bit as the target bit. In this case, the gate acts only on the computational basis state within the superposition.
- Perform the inverse of step 1 to transform back to .
Therefore, by performing this operation for each computational basis state , you can solve this problem.
Sample Code
Below is a sample program:
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate
def solve(n: int, L: int) -> QuantumCircuit:
qc = QuantumCircuit(n)
for l in range(L):
for i in range(n):
# check if i-th bit of l is 0 or 1
if not ((l >> i) & 1):
qc.x(i)
if n == 1:
qc.z(0)
else:
# apply multiple controlled Z gate
qc.append(ZGate().control(n - 1), range(n))
for i in range(n):
if not ((l >> i) & 1):
qc.x(i)
return qc