# SPDX-License-Identifier: Apache-2.0 AND CC-BY-NC-4.0## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
These are solutions to exercises from the grovers.ipynb notebook.
In [ ]:
# EXERCISE 1 SOLUTION# Define U_9 so that U_9|1001> = -|1001> but fixes # all other computational basis states |x># Set the number of qubits for the computational basis statesnum_qubits=4@cudaq.kerneldefU9(qubits:cudaq.qvector,aux_qubit:cudaq.qubit):x(qubits[1])x(qubits[2])z.ctrl(qubits,aux_qubit)x(qubits[1])x(qubits[2])# Create a kernel to test our defintion of U9@cudaq.kerneldefflip_phase_of_9_only(num_qubits:int):qubits=cudaq.qvector(num_qubits)aux_qubit=cudaq.qubit()# Place the aux_qubit in the minus statex(aux_qubit)h(aux_qubit)# Initialize the the qubits in a state of equal superpositionequal_superposition(qubits)# Apply the U9 kernelU9(qubits,aux_qubit)# Get the state of the flip_phase_of95_only kernelresult_with_aux_qubit=cudaq.get_state(flip_phase_of_9_only,num_qubits)print('The phases of the computational basis states after an application of U9 are',check_phase(result_with_aux_qubit))
In [ ]:
# EXERCISE 2 SOLUTION# Define a phase oracle that flips the phase of both 1111 and 1001, fixing all other computational basis states# assuming that the aux_qubit is initialized in the minus state@cudaq.kerneldefphase_oracle(qubits:cudaq.qvector,aux_qubit:cudaq.qubit):U9(qubits,aux_qubit)U15(qubits,aux_qubit)
EXERCISE 3 SOLUTION
f(000)=f(110)=1,f(x)=0 otherwise.
Applying Grover's algorithm, we note that the total number of states is N=23=8 and the number of solutions is t=2. The superposition of solutions is given by ∣G⟩=21(∣000⟩+∣110⟩),while the equal superposition of the remaining states is ∣B⟩=8−21(∣001⟩+∣010⟩+∣100⟩+∣011⟩+∣101⟩+∣111⟩).
As we have N=23=8, the angle θ satisfies:θ=arcsin(Nt)=arcsin(82)=arcsin(21)=6π.We solve for m:(2m+1)θ=2π⇒(2m+1)6π=2π⇒2m+1=3⇒m=1.Thus, a single iteration of the Grover diffusion operator maps ∣ξ⟩ exactly to ∣G⟩, ensuring that the subsequent measurement yields a valid solution with 100% probability!
Try writing the code for this. In particular, you will need to create new code for the phase oracle.