Skip to content

Commit

Permalink
Create grovers_algorithm.py
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Dec 3, 2024
1 parent 1bde288 commit c1fc59d
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions quantum_integration/quantum_algorithms/grovers_algorithm.py
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

0 comments on commit c1fc59d

Please sign in to comment.