How to take two's complement of a number using a quantum circuit
Two's complement is an arithmetic operation that converts a number
The general algorithm for computing the two's complement of a signed binary number is as follows:
Flip all the bits of the number, that is, 0s become 1s and 1s become 0s. This is called the one's complement of a number.
Add
to the one's complement of the number.
For example, the two's complement of
Quantum circuit
In quantum circuits, the algorithm to compute the two's complement of a number is the same. However, the algorithm to implement it is modified to minimize the number of extra
Code example
Let's look at the following code to evaluate the two's complement of a number:
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, executefrom qiskit.circuit.library import XGateqc_complement = QuantumCircuit(3, 3, name = '2s_cmp')reg = QuantumRegister(3, 'q')qc_complement.barrier()# Encode a numberprint('The encoded number is', bin(5)[2::])index = [0, 2][qc_complement.x(i) for i in index]qc_complement.barrier()# Take the complement## Flip the qubits[qc_complement.x(i) for i in range(3)]## Add onefor i in range(2, -1, -1):if i > 0:cnx_gate = XGate().control(i)qc_complement.append(cnx_gate, reg[0:i] + [reg[i]])qc_complement.x(0)qc_complement.barrier()# Measure the qubitsqc_complement.measure(range(3), range(3))print(qc_complement)# Simulate the circuitbackend = Aer.get_backend('qasm_simulator')counts = execute(qc_complement, backend, shots = 100).result().get_counts()print(counts)dec_num = int(list(counts.keys())[0], 2)print('Twos complement of the encoded number is', dec_num)
Here's an explanation of the code:
Line 4: We create a quantum circuit,
qc_complement, with three qubits and three classical bits.Line 5: We declare a quantum register with three qubits.
Lines 9–11: We encode a number to the qubits. Since the qubits are initialized to
by default, applying a to them will flip the state to 1. Here, the CNOT gate is applied to indexesCNOT gate In quantum computing, a controlled-NOT (CNOT) gate is a two-qubit gate wherein the state of the target qubit flips only when the control qubit is in state 1. and . So, the encoded number is . Lines 13–22: We compute the two's complement of the encoded number.
Line 15: The qubit states are flipped. So, the encoded number is transformed into its one's complement.
Lines 17–21: A ripple carry is used to flip the state of a qubit if all the previous qubit states are
.
Line 25: We apply the measurement gates to the qubits.
Line 26: We display the
qc_complement.Lines 29–30: We simulate
qc_complementusing the QASM backend provided by Qiskit and the dictionary of the simulation results is stored incounts.Line 32: We convert the computed two's complement in the binary form to an integer.
Free Resources