# Demo

## Qubits & Quantum States, Circuits, Measurements

`import numpy as npfrom qiskit import QuantumCircuitfrom qiskit.quantum_info import Statevectorfrom qiskit.visualization import plot_state_qsphere`
`n =1qc= QuantumCircuit(n,n)statevec = Statevector.from_instruction(qc).dataprint(statevec)plot_state_qsphere(statevec)`
`n =6qc= QuantumCircuit(n,n)for i in range(n):    qc.h(i)    qc.rz(2*np.pi/n,i)statevec = Statevector.from_instruction(qc).dataplot_state_qsphere(statevec)`
`n=2qz= QuantumCircuit(4)qc.h(0)for i in range(n):    qc.cx(0,i+1)    qc.x(2)statevec = Statevector.from_instruction(qc).dataplot_state_qsphere(statevec)`

## Part 1

`import numpy as np# Importing standard Qiskit libraries and configuring accountfrom qiskit import IBMQ, BasicAerfrom qiskit.providers.ibmq import least_busyfrom qiskit import QuantumCircuit, executefrom qiskit.tools.jupyter import *#import basic plot tooldfrom qiskit.visualization import plot_histogram`
`IBMQ.save_account('<your TOKEN>')provider = IBMQ.load_account()`
`def dj_oracle(case,n):    # We need to make a QuantumCircuit object to return    # This circuit has n+1 qubits: the size of the input,    # plus one output qubit    oracle_qc = QuantumCircuit(n+1)        #First, let's deal with the case in which oracle is balanced    if case == "balanced":        #We apply controlled-NOT gates for each qubit, using the         #output qubit as the target:        for qubit in range(n):            oracle_qc.cx(qubit,n)            #Case in which oracle is constant    if case == "constant":        #First decide what the fixed output of the oracle will be        #(either always 0 or always 1)        output = np.random.randint(2)        if output == 1:            oracle_qc.x(n)        oracle_gate = oracle_qc.to_gate()    oracle_gate.name = "Oracle" # To show when we display the circuit    return oracle_gate`
`def dj_algorithm(n, case = 'random'):    dj_circuit = QuantumCircuit(n+1,n)    #set up the input register:    for qubit in range(n):        dj_circuit.h(qubit)    #And set up the output qubit:    dj_circuit.x(n)    dj_circuit.h(n)    #Let's append the oracle gate to our ciruit:    if case == 'random':        random = np.random.randint(2)        if random == 0:            case = 'constant'        else:            case = 'balanced'    oracle = dj_oracle(case, n)    dj_circuit.append(oracle, range(n+1))    # Finally,perfom the H-gates again and measure:    for i in range(n):        dj_circuit.h(i)        dj_circuit.measure(i,i)    return dj_circuit`
`n=4dj_circuit = dj_algorithm(n)dj_circuit.draw()`
`# use local simulatorbackend = BasicAer.get_backend('qasm_simulator')shots = 1024dj_circuit = dj_algorithm(n, 'constant')result = execute(dj_circuit, backend=backend, shots=shots).result()answer = result.get_counts()plot_histogram(answer)`
`backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True))print("least busy backend: ", backend)%qiskit_job_watcherdj_circuit= dj_algorithm(n)job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)`
`least busy backend:  ibmq_vigo`
`# Get the result of the computationresults = job.result()answer = results.get_counts()plot_histogram(answer)`
`## job I ran beforebackend = provider.get_backend('<your backend>')old_job = backend.retrieve_job('<your job id>')result = old_job.result()answer = results.get_counts()plot_histogram(answer)`

## Part 2

`import numpy as np# Importing standard Qiskit libraries and configuring accountfrom qiskit import IBMQ, QuantumCircuit, Aer, executefrom qiskit.quantum_info import Operatorfrom qiskit.providers.ibmq import least_busyfrom qiskit.visualization import plot_histogramfrom qiskit.tools.jupyter import *`
`IBMQ.save_account('<your TOKEN>')provider = IBMQ.load_account()`
`def phase_oracle(n, indices_to_mark, name = 'Oracle'):    qc= QuantumCircuit(n, name=name)    oracle_matrix = np.identity(2**n)    for index_to_mark in indices_to_mark:        oracle_matrix[index_to_mark, index_to_mark] = -1    qc.unitary(Operator(oracle_matrix), range(n))    return qcdef diffuser(n):    qc = QuantumCircuit(n, name = 'Diff - "V"')    qc.h(range(n))    qc.append(phase_oracle(n,[0]),range(n))    qc.h(range(n))    return qcdef Grover(n, marked):    qc = QuantumCircuit(n,n)    r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2))    print(f'{n} qubits, bases state {marked} marked, {r} rounds')    qc.h(range(n))    for _ in range(r):        qc.append(phase_oracle(n,marked),range(n))        qc.append(diffuser(n), range(n))    qc.measure(range(n),range(n))    return qc`
`n = 5x = np.random.randint(2**n)marked = [x]qc = Grover(n, marked)qc.draw()`
`backend = Aer.get_backend('qasm_simulator')result = execute(qc, backend, shots=10000).result()counts = result.get_counts(qc)print(counts)print(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2)plot_histogram(counts)`
`n = 3x = np.random.randint(2**n)y = np.random.randint(2**n)while y==x:    y = np.random.randint(2**n)marked = [x,y]qc = Grover(n, marked)backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator and x.status().operational==True))#print("least busy backend: ", backend)backend = provider.get_backend('ibmq_vigo')%qiskit_job_watchershots = 1024job = execute(qc, backend=backend, shots=shots, optimization_level = 3)`
`3 qubits, bases state [7, 4] marked, 1 rounds`
`results = job.result()answer= results.get_counts()plot_histogram(answer)`
`backend = provider.get_backend('<your backend>')old_job = backend.retrieve_job('<your job id>')result = old_job.result()answer = results.get_counts()plot_histogram(answer)`
`import numpy as npfrom numpy import pi# importing Qiskitfrom qiskit.circuit.library import QFTfrom qiskit.quantum_info import Statevectorfrom qiskit import QuantumCircuitfrom qiskit.visualization import plot_bloch_multivectorimport warningswarnings.filterwarnings('ignore')`
`pi = np.pidef myQFT(nqubits):        myQFT_circuit = QuantumCircuit(nqubits)        for qubit in range(nqubits):        myQFT_circuit.h(qubit)        for otherqubit in range(qubit+1, nqubits):            myQFT_circuit.cu1( pi / (2** (otherqubit-qubit)), otherqubit, qubit)                return myQFT_circuitdef QFT(nqubits):        QFT_circuit = QuantumCircuit(nqubits)        for qubit in range(nqubits):        QFT_circuit.h(qubit)        for otherqubit in range(qubit+1, nqubits):            QFT_circuit.cu1( pi / (2** (otherqubit-qubit)), otherqubit, qubit)                return QFT_circuitdisplay(myQFT(4).draw)display(QFT(4).draw)`
`<bound method QuantumCircuit.draw of <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x0000024922ADB788>><bound method QuantumCircuit.draw of <qiskit.circuit.quantumcircuit.QuantumCircuit object at 0x0000024922ADB7C8>>`
`state = '00'sv = Statevector.from_label(state)print(sv)mycircuit = QuantumCircuit(len(state))mycircuit.initialize(sv.data, mycircuit.qubits[::-1])print("Computaional basis")display(plot_bloch_multivector(sv.data))sv = sv.evolve(myQFT(len(state)))print("Fourier basis")mycircuit.append(myQFT(len(state)), mycircuit.qubits)display(plot_bloch_multivector(sv.data))`
`state = '000'sv = Statevector.from_label(state)print(sv)mycircuit = QuantumCircuit(len(state))mycircuit.initialize(sv.data, mycircuit.qubits[::-1])print(f'Computaional basis | {state}>')display(plot_bloch_multivector(sv.data))sv = sv.evolve(QFT(len(state)))print(f'Fourier basis | {state}>')mycircuit.append(QFT(len(state)), mycircuit.qubits)display(plot_bloch_multivector(sv.data))`
`n_qubits = 3states = [format(x, f'0{n_qubits}b') for x in range(2**n_qubits)]states.append(state[0])for ii, state in enumerate(states):    mycircuit = QuantumCircuit(len(state))    sv = Statevector.from_label(state)    print(sv)    mycircuit.initialize(sv.data, mycircuit.qubits[::1])    print('====================================')    print("Computaional basis")    display(plot_bloch_multivector(sv.data))    sv = sv.evolve(myQFT(len(state)))    print("Fourier basis")    mycircuit.append(myQFT(len(state)), mycircuit.qubits)    display(plot_bloch_multivector(sv.data))    print('====================================')`
`state = '001'sv = Statevector.from_label(state)print(sv)mycircuit = QuantumCircuit(len(state))mycircuit.initialize(sv.data, mycircuit.qubits[::-1])print(f'Computaional basis | {state}>')display(plot_bloch_multivector(sv.data))sv = sv.evolve(QFT(len(state)))print(f'Fourier basis | {state}>')mycircuit.append(QFT(len(state)), mycircuit.qubits)display(plot_bloch_multivector(sv.data))`

## Part 1

`import mathN = 5*3a = 13math.gcd(a, N)`
`1`
`import matplotlib.pyplot as plotterz = list(range(N))y = [a**z0 % N for z0 in z]plotter.plot(z,y)plotter.xlabel('z')plotter.ylabel(f'{a}^z (mod {N})')plotter.show()`
`r = z[y[1:].index(1)+1]print(f'r = {r}')`
`r = 4`
`if r %2 == 0:    x = (a**(r/2)) % N    print(f'x = {x}')    if ((x+1) % N) != 0:        print(math.gcd((int(x)+1), N), math.gcd(int(x), N))    else:        print("x +1 is 0 (mod N)")else:    print(f'r = {r} is odd')`
`x = 4.05 1`
`import mathN = 11*7a = 18math.gcd(a, N)`
`1`
`import matplotlib.pyplot as plotterz = list(range(N))y = [a**z0 % N for z0 in z]plotter.plot(z,y)plotter.xlabel('z')plotter.ylabel(f'{a}^z (mod {N})')plotter.show()`
`r = z[y[1:].index(1)+1]print(f'r = {r}')`
`r = 30`
`if r %2 == 0:    x = (a**(r/2)) % N    print(f'x = {x}')    if ((x+1) % N) != 0:        print(math.gcd((int(x)+1), N), math.gcd(int(x), N))    else:        print("x +1 is 0 (mod N)")else:    print(f'r = {r} is odd')`
`x = 43.011 1`

## Part 2

`import numpy as nppi = np.pifor y in range(15):    coeff = np.exp(-1j*3*pi/8 * y) + \            np.exp(-1j*7*pi/8 * y) + \            np.exp(-1j*11*pi/8 * y) + \            np.exp(-1j*15*pi/8 * y)    if abs(coeff) < 1e-10: coeff = 0    print(y, coeff)`
`0 (4+0j)1 02 03 04 (-5.757077917265737e-15+4j)5 06 07 08 (-4-1.1514155834531474e-14j)9 010 011 012 (2.2600304269997962e-14-4j)13 0`

--

--

## More from cahyati sangaji (cahya)

Love podcasts or audiobooks? Learn on the go with our new app.