QCEXP@9
QCEXP@9
Experiment 9
Aim: To write a program to implement Deutsch-Jozsa’s algorithm
LO Mapped: LO3
LO Description: To understand quantum entanglement, quantum algorithms
Theory:
The Deutsch-Jozsa algorithm is a quantum algorithm that distinguishes between constant and
balanced functions in one query, regardless of the number of input bits. It was the first real
demonstration of a quantum speedup over classical algorithms.
Problem statement
n
You are given a black-box function f : { 0 ,1 } →{0 , 1} which is guaranteed to be either:
Classical approach
In the worst case, you would have to evaluate f (x) on 2n−1 +1 inputs to be sure.
Quantum approach
It requires only 1 query, regardless of the number of inputs.
Steps
Assume we have n input qubits and 1 output qubit:
1) Initial state
● Input qubits: ¿ 0 ⟩⊗n
● Output qubit: ¿ 1 ⟩
● So, the state is:
⊗n
¿ 0 ⟩ ⊗∨1 ⟩
2) Apply Hadamard gates
● Apply Hadamard gates to all qubits to create a superposition
● Input qubits become:
1
√❑
● Output qubits become:
1
√❑
Mitesh Singh B22 2101111 AI&DS
U f ∨x ⟩∨ y ⟩=¿ x ⟩∨ y ⊕ f (x)⟩
● Due to the superposition and the way the output qubit was prepared, this encodes f (x) as a
phase:
¿x⟩ ( ¿ 0 ⊕ f ( x) ⟩−¿1
√❑
⨁ f (x)⟩
)
● So, the system becomes:
1
√❑
● The output qubit is now separable — we focus only on the input qubits
4) Apply Hadamard gates to the input qubits
● Now apply Hadamard gates to all n input qubits
● This causes interference based on the values of f (x)
5) Measure the input qubits
● If the result is all zeroes, then f is constant
● If the result is anything else, then f is balanced
Significance
● It only uses 1 query v/s exponential queries in classical computing
● It exploits quantum parallelism and interference
● While it has limited practical application, it demonstrates the principle of quantum speedup
● It also serves as a foundation for more practical algorithms such as Grover’s and Shor’s
algorithm
Code / Output:
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Output results
print("Measurement outcomes:", counts)
print("Quantum Circuit:")
print(qc.draw(output='text'))
return counts
# Example oracles
def constant_oracle(n):
"""Returns a constant oracle (f(x) = 0 for all x)."""
oracle = QuantumCircuit(n + 1)
# Does nothing to the circuit (f(x) = 0)
return oracle.to_instruction()
def balanced_oracle(n):
"""Returns a balanced oracle (f(x) = x_0 XOR x_1 XOR ... XOR
x_n)."""
oracle = QuantumCircuit(n + 1)
for i in range(n):
oracle.cx(i, n)
return oracle.to_instruction()
if __name__ == "__main__":
n = 3 # Number of input qubits