-
-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
48 changes: 48 additions & 0 deletions
48
quantum_integration/quantum_algorithms/grovers_algorithm.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
from qiskit import QuantumCircuit, Aer, execute | ||
from qiskit.visualization import plot_histogram | ||
import numpy as np | ||
|
||
def grovers_algorithm(n, target): | ||
# Create a quantum circuit with n qubits | ||
qc = QuantumCircuit(n, n) | ||
|
||
# Initialize the target state | ||
qc.h(range(n)) # Apply Hadamard to all qubits | ||
qc.x(target) # Flip the target qubit | ||
qc.h(target) # Apply Hadamard to the target qubit | ||
|
||
# Oracle for the target state | ||
qc = oracle(qc, n, target) | ||
|
||
# Grover's diffusion operator | ||
qc.h(range(n)) | ||
qc.x(range(n)) | ||
qc.h(target) | ||
qc.x(target) | ||
qc.h(range(n)) | ||
|
||
# Measure the qubits | ||
qc.measure(range(n), range(n)) | ||
|
||
# Execute the circuit | ||
backend = Aer.get_backend('qasm_simulator') | ||
result = execute(qc, backend, shots=1024).result() | ||
counts = result.get_counts() | ||
|
||
# Plot the results | ||
plot_histogram(counts).show() | ||
|
||
return counts | ||
|
||
def oracle(qc, n, target): | ||
# Implement the oracle for the target state | ||
for qubit in range(n): | ||
if qubit != target: | ||
qc.x(qubit) # Flip all qubits except the target | ||
qc.h(target) | ||
qc.mct(list(range(n)), target) # Multi-controlled Toffoli gate | ||
qc.h(target) | ||
for qubit in range(n): | ||
if qubit != target: | ||
qc.x(qubit) # Flip back the qubits | ||
return qc |