In [1]:
from qiskit import *
from qiskit.visualization import plot_histogram
%matplotlib inline
In [2]:
secretNumber = '1000101'
In [3]:
circuit = QuantumCircuit(8,7) # n+1 qubits and n classical bits. n=7 in this case, because there are 7 digits
In [4]:
# Bernstein-Vazirani: Put H on all qubits, put CNOT on the ones that are 1
circuit.h([0,1,2,3,4,5,6]) # apply H to 7 qubits
circuit.x(7) # Before applying H to the helper qubit, first apply a NOT gate
circuit.h(7) # If you don't apply NOT and H gates to this qubit, you would get the result right half of the time (50%)
# You would get 0000000 from the results by applying these gates
circuit.barrier()
circuit.draw(output='mpl')
# Now we'll do it manually to show the algorithm works
# In our secret code, q0=1 (the last digit)
# I'll apply NOT or CNOT gate between q0-q7 and I'll continue as long as I see 1s
circuit.cx(0,7)
circuit.cx(2,7) # 3rd qubit also has a value of 1
circuit.cx(6,7) # 7th qubit is also 1
circuit.barrier()
circuit.h([0,1,2,3,4,5,6]) # We will not measure the helper qubit so don't apply H to it
circuit.measure([0,1,2,3,4,5,6],[0,1,2,3,4,5,6])
circuit.draw(output='mpl')
Out[4]:
In [5]:
# Up to now, we flip the bits by hand. It doesn't make sense
# We'll do things more automatically later
from qiskit_aer import Aer
simulator = Aer.get_backend("qasm_simulator")
result = simulator.run(circuit, shots=1024).result()
counts = result.get_counts()
print(counts)
{'1000101': 1024}