N-Qubit CNOT gate in Qiskit with Code

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

Introduction

In this tutorial we will explore how to implement a CNOT gate consisting of N qubits in Qiskit for use on IBM’s quantum devices.

Implementation

A normal CNOT gate consists of two qubits. The first is known as the control qubit and the second is known as the target qubit. If the control qubit is 1 then the target qubits state will be flipped from 1 to 0 or vice versa.

However what if we want to flip a qubits state based on more than 1 control qubit? Well we can use the circuit below!

4CNOT.png

This consists of 4 control qubits (q0 to q3), 3 auxilary qubits (q4 to q6) and 1 target qubit (q7).

When q0 to q3 are 1 the auxilary qubits will be flipped using toffoli gates which in turn will flip the state of the target qubit.

After the target qubit is flipped the auxiliary qubits have to be returned back to 0 by again applying Toffoli gates.

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
from qiskit import 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')


q = QuantumRegister(8, 'q')
c = ClassicalRegister(1, 'c')

circuit = QuantumCircuit(q, c)

circuit.x(q[0])
circuit.x(q[1])
circuit.x(q[2])
circuit.x(q[3])

circuit.ccx(q[0], q[1], q[4])
circuit.ccx(q[2], q[4], q[5])
circuit.ccx(q[3], q[5], q[6])

circuit.cx(q[6], q[7]) 

circuit.ccx(q[3], q[5], q[6])
circuit.ccx(q[2], q[4], q[5])
circuit.ccx(q[0], q[1], q[4])

circuit.measure(q[7], c[0])

job = execute(circuit, backend, shots=100)
job_monitor(job)

counts = job.result().get_counts()

print(circuit)
print(counts)

Output

Output showing the circuit and q7 flipped to 1

Output showing the circuit and q7 flipped to 1