Writing a quantum algorithm to generate integers of a specified parity

For an N-qubit system, the maximum number of basis-states is \(2^N\). This unique property allows us to represent basis-states using bitstrings, i.e., a state of \(|0101⟩\) can be written as '0b0101'

Given that the qubit \(\psi\) is initialized to a basis-state of \(|0⟩\) or \(|1⟩\), applying the Hadamard gate creates an balanced superposition of both states. $$H|ψ⟩ =\frac{1}{\sqrt{2}} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} \begin{bmatrix} 1 \\ 0 \end{bmatrix} = \begin{bmatrix} \frac{1}{\sqrt{2}} \\ \frac{1}{\sqrt{2}} \end{bmatrix}$$

Thus, there's an equal probability of collapsing to either \(|1⟩\) or \(|0⟩\). In a system of 2 qubits, the possible basis-states are \(|00⟩\), \(|01⟩\), \(|10⟩\), and \(|11⟩\).

Applying the Hadamard gate to the first qubit in a 2-qubit system gives us \(|00⟩\) and \(|01⟩\) as the basis-states. Likewise, applying the Hadamard gate to the second qubit gives us \(|00⟩\) and \(|10⟩\). Knowing that we can manipulate the \(n^{th}\) bit[1] in the basis-state bitstring by operating on the \(n^{th}\) qubit, we can craft a circuit to generate only even or odd numbers.

Finding the parity of a binary number is ridiculously easy[2]. If the least significant bit (LSB) is set to 0, it's even. Therefore, the definition of an even bitstring is \(\{0, 1\}^{N-1}0\). Let's move on to circuit construction to test this out.

Environment setup

Let's start by creating a virtual environment[3] and installing the qsiml package for circuit simulation.
$ pip install virtualenv
$ mkdir qc_even
$ cd qc_even
$ python -m venv env
$ source env/bin/activate
$ pip install qsiml

Open a new file in your text editor and run the following code to ensure that everything works perfectly.

from qsiml import QuantumCircuit
qc = QuantumCircuit(2) 

Circuit Construction

The ethos of the function is as follows:

from qsiml import QuantumCircuit

def parity_check(is_even: bool, n: int):
    qc = QuantumCircuit(n)
    for i in range(n - 1):
        qc.h(i)

    if not is_even:
        qc.x(n - 1)

    qc.dump()

if __name__ == "__main__":
    parity_check(True, 2) 

The function parity_check prints prints possible basis-states[5] of the system. If is_even = True and \(n = 2\) it prints the following basis-states:

Basis State Probability Amplitude Phase
|00⟩ 50.000000% 0.707107 + 0.000000i 0
|10⟩ 50.000000% 0.707107 + 0.000000i 0

When \(n = 3\) and the parity is odd, we get the following output:

Basis State Probability Amplitude Phase
|001⟩ 25.000000% 0.500000 + 0.000000i 0
|101⟩ 25.000000% 0.500000 + 0.000000i 0
|011⟩ 25.000000% 0.500000 + 0.000000i 0
|111⟩ 25.000000% 0.500000 + 0.000000i 0

Try it out for yourself and make sure to deactivate the virtual environment one you're done!

$ deactivate