CNOT gate tutorial with Code

Interested in learning how to program quantum computers? Then check out our Qiskit textbook Introduction to Quantum Computing with Qiskit.

Introduction

This tutorial will introduce the user to the CNOT gate and how to implement it on IBMs quantum devices.

The CNOT gate is a mulit-qubit gate that consists of two qubits. The first qubit is known as the control qubit and the second is known as the target qubit. If the control qubit is |1〉then it will flip the targets qubit state from |0〉to |1〉or vice versa.

The CNOT gates operation is described by the following matrix:

Using matrix multiplication let’s explore how the CNOT gate operates on the qubits state. Since this gate operates on two qubits the column vectors will have a row for each possible state:

For our first example let’s set the control qubit and target qubit to |0〉such that the combined state will be |00〉

This shows that the target qubits state has remained unchanged as the state is |00〉Now let’s instead set the control qubit to |1〉and the target qubit to |0〉such that the combined state will be |10〉:

Which has flipped the target qubit to |1〉such that the combined state is |11〉

Implementation

In Qiskit the CNOT gate can be implemented by initialising two qubits. The first qubits state is flipped to |1〉and the second remains |0〉. Next a CNOT gate is applied where the first qubit is the control and the second is the target qubit. Next both qubits are measured and the results will be sent back from the device.

The full Qiskit code is in the code section below.

Circuit diagram of the program

How to run the program

Copy and paste the code below in to a python file

  1. Enter your API token in the IBMQ.enable_account('Insert API token here') part

  2. Save and run

Code

from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor

IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator') # Specifying qasm simulator as the target device

q = QuantumRegister(2,'q')
c = ClassicalRegister(2,'c')

circuit = QuantumCircuit(q,c)
circuit.x(q[0]) # Pauli x gate applied to first qubit 
circuit.cx(q[0],q[1]) # CNOT applied to both qubits 
circuit.measure(q,c) # Qubits states are measured 

job = execute(circuit, backend, shots=1)
                                              
job_monitor(job)
counts = job.result().get_counts()

print('RESULT: ',counts)
print('')
print('Press any key to close')
input()

Any problems or questions associated with this program? Contact us