The controlled phase gate CP(\lambda) on two qubits c and t of an n-qubit register multiplies the amplitude of every basis state in which qubit c and qubit t both read 1 by e^{i\lambda}, and leaves every other amplitude unchanged. On two qubits its matrix is \mathrm{diag}(1, 1, 1, e^{i\lambda}). It is usually drawn with c as the "control" and t as the "target" (apply the phase gate P(\lambda)=\mathrm{diag}(1,e^{i\lambda}) to t when c reads 1), but the rule "both read 1" shows that the two qubits play the same role: CP(\lambda) on (c, t) is the same gate as on (t, c).
Bit order: basis state |b_0 b_1 \dots b_{n-1}\rangle has index int("b0b1...", 2), so qubit 0 is the leftmost bit, the most significant. In 3 qubits, |011\rangle is index 3, where qubits 1 and 2 read 1.
Write cphase(state, c, t, lam) that returns the state after CP(\lambda) on qubits c and t (c != t), as a list or numpy array of 2^n amplitudes. lam is an angle in radians. Any global phase is accepted: [1j, 0] is the same state as [1, 0]. The larger tests use the helper peek(state), which returns 8 amplitudes, [state[(j * 40503) % len(state)] for j in range(1, 9)].
Examples
Input: state = [0.5, 0.5, 0.5, 0.5], c = 0, t = 1, lam = math.pi / 2
Output: [0.5, 0.5, 0.5, 0.5j]
Explanation: only |11> (index 3) has both qubits reading 1; it is multiplied by e^{i pi/2} = i.
Input: state = [0.5, 0.5, 0.5, 0.5], c = 1, t = 0, lam = math.pi / 2
Output: [0.5, 0.5, 0.5, 0.5j]
Explanation: the same gate: the two qubits play the same role.
Input: state = [0.3535533905932738] * 8, c = 0, t = 1, lam = math.pi
Output: [0.3535533905932738, 0.3535533905932738, 0.3535533905932738, 0.3535533905932738,
0.3535533905932738, 0.3535533905932738, -0.3535533905932738, -0.3535533905932738]
Explanation: qubits 0 and 1 both read 1 in |110> and |111> (indices 6 and 7); e^{i pi} = -1.
Constraints
- amplitudes are compared with a tolerance of
1e-6
Goals
- Apply a controlled phase gate to two qubits of a register
- Find the basis states where two given qubits both read 1, with qubit 0 as the leftmost bit
- See that the controlled phase gate treats its two qubits the same way