 Research
 Open Access
 Published:
A quantum circuit to generate random numbers within a specific interval
EPJ Quantum Technology volume 10, Article number: 17 (2023)
Abstract
Random numbers are of vital importance in fields such as cyptography and scientific simulations. However, it is well known how difficult it is for classical computers to generate random numbers. This is not the case for quantum computers, which are able to genuinely generate random numbers thanks to the property of superposition and their counterintuitive concept of measurement. However, despite the simplicity of designing a circuit that generates a random number between 0 and \(2^{N}1\) (being N the number of available qubits), designing a quantum circuit to generate a number within a specific interval is far from trivial. This paper proposes a customizable circuit design to generate random numbers. The circuit is non hardware dependent, it allows faulttolerance, and it can be used by current quantum devices. Therefore, it is a valuable tool for all those quantum applications and algorithms that need to work with random numbers. Moreover, a comparator circuit has also been designed as part of this work. This comparator is the best currently available in the literature in terms of qubits, Tcount, and Tdepth. It is therefore a useful tool for any other circuit or algorithm where this operation is needed.
1 Introduction
Random numbers have a wide variety of applications such as cryptography [1], numerical modelling [2], blockchain [3], or cybersecurity [4]. The quality of random numbers is of vital importance for such applications. For instance, in the case of cryptography, using predictable random numbers would have serious security implications [5]. Generating random numbers using a classical computer is a deterministic process, which is theoretically predictable [6]. Even the modern lattice or hashedbased quantumsafe cryptography methods and algorithms are unable to genuinely generate random numbers [7]. These pseudorandom numbers work well for simple applications, but may be insufficient when higher quality is needed as in the above example of cryptography. It is precisely for this reason that there is great interest in finding alternative ways to generate numbers that are truly random, unpredictable, and secure [8–10].
Quantum computing has emerged as a successful alternative for generating random numbers. In theory of quantum physics, the outcome of most phenomena is not deterministic. Only probabilities of the different possible results can be given. Quantum computing, in its role of emulating quantum physics, brings with it this unpredictability [11]. Properties such as the superposition of quantum states, entanglement, the collapse of states when measured, and the other counterintuitive properties of quantum physics play a fundamental role in the generation of random numbers using quantum computation [12]. There are a wide range of works in the literature that successfully use random numbers generated by quantum computers [13–15].
Currently, quantum computers are in the socalled NISQ (Noisy IntermediateScale Quantum) era. These computers are characterised by a limited amount of resources. Moreover, they are extremely sensitive to noise [16]. There are several options for programming a quantum computer, being the most widespread the use of reversible circuits. Of course, any circuit design must face the aforementioned scarcity of resources. At the same time, they must offer some kind of resistance to errors caused by noise. Therefore, it is important to look for ingenious solutions to reduce the number of involved qubits and quantum gates, but without neglecting the detection and correction of errors [17].
There are several current strategies to reduce the effects of noise [18]. One widespread strategy is to build circuits using only quantum gates belonging to the socalled Clifford + T group [19–22]. Circuits built only with this type of gates can benefit from the use of proven error detection and correction codes. However, among the gates belonging to the Clifford + T group, it is necessary to highlight one of them, the T gate. This gate has a cost in the order of 100 times higher than the cost of the other gates [23]. Its cost is so high that it makes the cost of the other gates almost irrelevant. So, in the literature the number of Tgates is used to measure the resources of quantum circuits [24–26]. The socalled Tcount parameter precisely measures the number of Tgates in a circuit. A second metric, the Tdepth, indicates the number of Tgates a circuit has on its critical path, allowing an estimation of the depth of the circuit. Keeping the Tcount and Tdepth values low, as well as involving as few qubits as possible, are probably the most important priorities for building a quantum circuit today [19].
This paper proposes a circuit to generate random numbers in quantum computers and simulators of the NISQ era. The circuit is focused on generating numbers within an interval of possible values to be defined by the user. The aim has been to design an easy to use circuit that generates highquality random numbers, without having to resort to lowlevel solutions that may be too challenging or simply beyond the reach of the general public [27–29]. It have also been sought to achieve a circuit with noise tolerance, as well as optimising the number of involved qubits and T gates to allow its viability on NISQ devices.
This paper is structured as follows. Section 2 introduces the formulation and ideas behind the quantum random number generator, and also its limitations. Section 3 presents the developed circuit, indicating how to reproduce it and showing the involved costs. Section 4 discusses the results achieved by the generator. We conclude in Sect. 5.
2 Methods
There are many quantum random number generators in the literature. These generators are of different natures: based on radioactive sources [30], electronic noise [31], atomic systems [32], etc. The proposed circuit is based on the measurement of qubits in superposition, which is the most easy and natural way of generating numbers in quantum computing. This kind of generator uses the collapse that occurs when measuring qubits to obtain random numbers [12].
A random number generator circuit can be designed in a quantum computer using only Hadamard gates. Starting with N qubits initialised in the state \(0\rangle \), it is enough to apply a Hadamard gate on each qubit to put them in a superposition state and then to measure all the qubits. This simple operation, requiring only N Hadamard gates, will produce a random string of N binary values (interpreting the \(0\rangle \) state as 0 and the \(1\rangle \) state as 1). If this string is numerically interpreted, the result is a number in binary notation whose value will always be between 0 and \(2^{N}1\). Increasing or decreasing the number of qubits allows us to extend or decrement the upper bound of the interval.
As easy as it is to create a number generator in the interval \([0, 2^{N}1]\), it is not easy to generate numbers in a customized interval. For instance, to generate numbers in the interval \([0, 5]\) to simulate the six possible outcomes of a die can be challenging. In order to represent the largest number, 5, three digits are needed. Using three qubits and the abovementioned procedure, numbers in the interval \([0, 7]\) can be generated. However, this interval includes several values (6 and 7) outside the range of interest. This problem can be solved by manipulating the obtained result using classical computation. For instance, the value can be checked and, in case an invalid value is obtained, to rerun the circuit until a value in the desired interval was achieved. However, this procedure requires to use classical computation as an intermediary, and may not be a valid (or simply not optimal) solution if we are interesting in using the generator as part of a larger quantum circuit that it does not interfere with a classical computer at that point.
Continuing with the example of generating numbers in the interval \([0, 5]\), another solution could be to add an ancilla qubit and perform some extra operations. Let \(A_{2}\), \(A_{1}\), \(A_{0}\) be the original three qubits, representing the digits of the generated number, and Q being the auxiliary qubit. \(A_{2}\), \(A_{1}\), \(A_{0}\) are set in superposition and measured. Then, the operations \(A_{2} A_{1} \oplus Q\) and \(Q \oplus A_{2}\) are sequentially performed. Using this circuit, random numbers in the desired interval are obtained. However, this solution also has drawbacks. First, it is far from generating the numbers uniformly. Secondly, and more importantly, this circuit only works for this specific interval. Customizing the circuit for larger interval will require more ingenuity. Furthermore, for quite large intervals this solution will become unfeasible.
A suitable method for generating random numbers that lie in a subinterval within the interval \([0, 2^{N}  1]\) is to modify the probabilistic amplitudes of those states corresponding to values within the subinterval. If the probabilistic amplitudes of the unwanted states cancel out, and those of the wanted states remain uniform, a quality random number generator would be achieved. This manipulation of the amplitudes can be done with Grover’s algorithm. Grover’s algorithm is shown schematically in Fig. 1. The algorithm (1) sets the N qubits in superposition, (2) recognises the solutions to the problem (the numbers of the desired subinterval in this case) through an oracle, and (3) amplifies the amplitudes of the solutions recognised by the oracle. Steps 1 and 2 are always the same and do not allow for customisation beyond how to implement the circuits that perform the operations. However, the oracle is delivered as a black box that the researcher must customise to the problem at hand. The oracle have to add a negative phase to any solution state. Therefore, being w a valid solution and \(x\rangle \) any possible state, the oracle must perform:
Therefore, in order to apply Grover, a valid oracle must be specified that allows a value to be selected within a given range.
2.1 The oracle
In order to amplify the amplitudes of the states corresponding to the numbers within the desired interval \([0, B]\), being B a natural number such that \(B > 0\), we need to recognise whether a state represents a number that is less than or equal to B, or not. Working with natural numbers, there is no need to check the lower limit of the interval because a negative number cannot be obtained. Then, it is only necessary to make sure that the generated number A is less than or equal to B. To do this, a halfcomparator can be used. This type of circuit compares two numbers A and B and returns 0 if \(A\le B\) and 1 otherwise. There are a wide variety of halfcomparators available in the literature [33–35]. However, in this paper we offer a customised comparator that allows us to reduce costs in terms of T gates and number of qubits.
Our comparator is based on the methodology of an adder proposed by Gidney in 2018 [36]. The idea is to use this adder to perform the operation \(AB\) computing \(\overline{\overline{A}+B}\). Once the operation is carried out, the sign of the subtraction will contain the result of the comparison. Since we are only interested in the sign, several operations can be simplified or even omitted as they are dedicated to performing the remaining operations of the sum. Moreover, we will not introduce B through the qubits, but we will progressively introduce it through quantum gates depending on whether its digits are 0 or 1. This technique of encoding an integrated number in the circuit itself is not new, and has been used successfully to simplify circuits and optimise resources [37]. The comparator has been built avoiding the use of Toffoli gates when possible, given the high cost of T gates. Instead, temporary logicalAND gates [36] have been used. The most efficient implementation of the Toffoli gate contains 7 T gates, while the temporary logicalAND only involves 4 of these gates. The construction of the proposed comparator and its metrics are detailed in the next section.
2.2 Limitations of the proposed circuit
Theoretically, a quantum computer produces perfectly random numbers. However, it has already been mentioned that current devices are exposed to internal and external noise. The result of this exposure is that current quantum computers do not generate these random numbers uniformly. There are several protocols in the literature, such as those presented by Combarro et al. [11], to improve the uniformity of random number generation by quantum computing. We have left as future work to incorporate this kind of techniques to our circuit to improve the quality of the obtained results.
On the other hand, each current quantum computer has its own internal architecture. This architecture does not usually establish connectivity between all the physical qubits of the machine; instead, each qubit is connected to some but not all of the others. When implementing a circuit from a design, each qubit in the circuit must be mapped to a physical qubit in the machine. All involved qubits in the same operation (for instance, the three qubits acting on a Toffoli gate) must be adjacent. If they are not, it is necessary to apply SWAP gates to move the values to be in adjacent qubits (and reverse the movements once the operation is performed). This causes an obvious increase in the number of quantum gates. Finding the optimal way to minimize the number of SWAP gates, as well as finding the most suitable initial mapping, are subjects of intense study by the research community [38]. It is not the aim of this work to present a customized implementation for each existing quantum device, so neither the extra costs due to SWAP operations nor an estimation of the best initial mapping have been included when analysing the proposed circuit.
3 Results
Since a comparator is required for the construction of the random number generator, the details concerning the comparator will be explained first. Once the comparator has been introduced, the implementation of the generator will be explained.
3.1 Proposed comparator
The circuit compares two Ndigit natural binary numbers \(a=a_{N1}\ldots a_{0}\) and \(b= b_{N1}\ldots b_{0}\), with the digits in position \({N1}\) being the most significant and the digits in position 0 the least significant. It can be easily built for any digit size \(N>2\) following these steps:

1
For \(i=0\) to \(i=N1\), to apply a PauliX gate at every bit \(a_{i}\) to perform a̅. These operations can be computed in parallel.

2
\(b_{0}\) must be introduced in the first ancilla qubit using a PauliX gate or an identity gate if \(b_{0}=1\) or \(b_{0}=0\), respectively.

3
To perform the operation \(\overline{a_{0}} b_{0}\) using a temporary logicalAND gate instead of a Toffoli gate to save Tcount and Tdepth. Each temporary logicalAND will require an extra qubit, which must be initialized to the state \(\frac{1}{\sqrt{2}}(0\rangle + e^{\frac{i\pi}{4}}1\rangle )\).

4
\(b_{0}\) is uncomputed applying (again, in the first ancilla qubit) a PauliX gate or an identity gate if \(b_{0}=1\) or \(b_{0}=0\), respectively.

5
The next step introduces a loop that will repeat from \(i=1\) to \(i=N1\). Prior to each instruction in this loop, we must codify \(b_{i}\) in a similar way to how \(b_{0}\) was codified. That is, a PauliX gate will be applied to the first ancilla qubit if \(b_{i}\) is 1, or an identity gate will be applied otherwise. Likewise, this action must be repeated after each instruction in the loop to uncompute the value \(b_{i}\) and to prepare the qubit to codify \(b_{i+1}\) in the next instruction.

6
For \(i=1\) to \(i=N1\), apply two CNOT gates to compute \((\overline{a_{i1}} b_{i1}) \oplus \overline{a_{i}}\) and \((\overline{a_{i1}} b_{i1}) \oplus b_{i}\). Then, to apply a temporary logicalAND to compute \(\overline{a_{i}} b_{i}\). A CNOT performing again \((\overline{a_{i1}} b_{i1}) \oplus b_{i}\) is applied to uncompute the previous CNOT. Finally, to apply another CNOT gate to perform \((\overline{a_{i1}} b_{i1}) \oplus (\overline{a_{i}} b_{i})\). Each step of the loop must be computed sequentially.

7
The result is given by the last operation of the last iteration computed in the previous step.
The obtained comparator is fully functional, and will return 0 if \(a< b\), and 1 otherwise. However, this circuit contains \(N1\) garbage outputs, which correspond to the auxiliary qubits used to implement the temporary logicalAND gates, except for the last one, which contains the result of the comparison. To reverse the garbage outputs we resort to the Bennett’s garbage removal scheme [39] in combination with the measureandfixup approach used by the temporary logicalAND gate [36, 40]:

8
For \(i=N2\) to \(i=1\), to apply a CNOT gate to perform \((\overline{a_{i1}} b_{i1}) \oplus (\overline{a_{i}} b_{i})\). A CNOT performing \((\overline{a_{i1}} b_{i1}) \oplus b_{i}\) is applied. Then, to apply an uncomputation gate of the temporary logicalAND to uncompute \(\overline{a_{i}} b_{i}\). Finally, to apply two CNOT gates to compute \((\overline{a_{i1}} b_{i1}) \oplus b_{i}\) and \((\overline{a_{i1}} b_{i1}) \oplus \overline{a_{i}}\). Again, each step of the loop must be computed sequentially codifying and uncomputing \(b_{N2}, b_{N1},\ldots b_{1}\).

9
Uncompute the operation \(\overline{a_{0}} b_{0}\) using an uncomputation gate of the temporary logicalAND gate. \(b_{0}\) must be codified at the beginning and uncomputed at the end.

10
Finally, for \(i=0\) to \(i=N1\) apply a PauliX gate at every bit \(\overline{a_{i}}\) to uncompute them. All the qubits except the one that contains the result have been uncomputed.
A complete example for the \(N=4\) case is shown in Fig. 2. In this example, the encoding of b is shown schematically. Each box labelled with a natural number between 0 and \(N1\) corresponds to a digit of b, so that the ith box will be an Identity gate (it may be omitted) if \(b_{i}=0\), or will be a PauliX gate if \(b_{i}=1\).
The logic on which the circuit is based is the one explained in the previous Section: the sign of the operation \(\overline{\overline{a}+b}\) is obtained and returned as the result of the comparison between a and b. Since the operation performed is a simplified addition, the circuit construction is started from the least significant digits and moves towards the most significant ones. The auxiliary qubits are used both to reduce the number of T gates and to store the carry of the sum of the previous digits. For instance, the first qubit marked as A in Fig. 2 stores the carry generated from \(\overline{a_{0}}\) and \(b_{0}\), and so on with the rest of the ancilla qubits for the following pairs \(\overline{a_{i}}\) and \(b_{i}\). Only the information necessary to generate the carries is stored, while the rest of the operations that in a normal adder would allow calculating the rest of the result of the sum are discarded.
For the general case of N digits, N qubits are needed to encode a. \(N+1\) auxiliary qubits are also used to perform auxiliary operations, making a total of \(2N+1\) qubits. N PauliX gates to invert \(a_{i}\) values, and 2N to encode b (depending on the 1 number of the b expression), add up to a maximum of 3N PauliX gates. \(4(N1)\) CNOT gates, and N temporary logicalAND gates are also involved in the whole process. On the other hand, reversing the garbage outputs will require N PauliX gates for \(a_{i}\) values and a maximum of \(2(N1)\) gates for b (making a maximum of \(3N2\) PauliX gates), \(4N7\) CNOT gates, and \(N1\) gates for uncompute the temporary logicalAND operations. The total numbers of the circuit are:

Number of qubits: \(2N+1\)

PauliX gate: \(6N2\)

CNOT gate: \(8N11\)

Temporary logicalAND gate: N

Uncomputation gate for the temporary logicalAND operation: \(N1\)
From the mentioned gates, only the temporary logicalAND gate involves T gates. Since the circuit contains N temporary logicalAND gates, and that the Tcount of each temporary logicalAND gate is 4, it can be established that the Tcount of the whole circuit is 4N. Moreover, since the N temporary logicalAND gates are executed sequentially, and since their Tdepth is 2, it can be established that the Tdepth of the comparator is 2N.
3.2 Quantum random number generator
The necessary steps to build the random number generator circuit for Ndigit numbers in the halfopen interval \([0, B)\), assuming that B can be represented by N digits, are as follows:

1
To design a comparator circuit using the methodology explained in the previous subsection, coding \(a=0\) (i.e., keeping all inputs \(a_{i}=0\)) and \(b=B\) (using the corresponding CNOT and Identity gates). It must only be designed until the result is obtained, i.e., without applying the uncomputation part yet. This circuit will henceforth be referred to as Comparator.

2
To obtain the inverse circuit of the previous one. In the previous subsection we explained how to reverse the garbage outputs of the comparator, which is a different process. The circuit that must be obtained now must also reverse the output of the comparator itself. That is to say, it must be identical to Comparator, but in reverse. We will call this second circuit Uncomputation of the comparator.

3
To prepare N qubits in the \(0\rangle \) state, and one qubit in the \(1\rangle \) state. We apply a Hadamard gate to each of these qubits. At this point, we will have N qubits in the \(+\rangle \) state, and one qubit in the \(\rangle \) state.

4
The Oracle phase:

(a)
To implement Comparator, so that the N qubits in the \(+\rangle \) state match the \(a_{i}\) inputs of Comparator.

(b)
After Comparator, to apply a CNOT gate. The control qubit will be the qubit resulting from Comparator, and the target qubit will be the qubit we initialise to the \(\rangle \) state.

(c)
To apply Uncomputation of the comparator to reverse Comparator.

(a)

5
Amplification phase:

(a)
To apply a Hadamard gate to each of the N qubits that were initially set to the \(+\rangle \) state. After the Hadamard gates, to apply a PauliX to each of these qubits.

(b)
Of the same N qubits above, to apply only to the most significant one a Hadamard gate. With the remaining \(N1\) qubits acting as control qubits, to apply a controlled Toffoli gate, with the most significant qubit being the target qubit.

(c)
To apply a PauliX gate to each of the previous N qubits. After the PauliX gates, to apply a Hadamard gate to each of these qubits.

(a)

6
To repeat steps 4 and 5 \(\\frac{\pi}{4} \sqrt{\frac{2^{N}}{l}}\\) times, being l the size of the interval \([0, B)\).

7
To measure the N qubits that was initially set to \(+\rangle \). They will contain the random number.
A scheme of the quantum random number generator circuit, for the case \(N=4\), is shown in Fig. 3. The generator circuit can be easily adapted to generate random numbers in the closed interval \([0, B']\) by simply setting \(B' = B + 1\). Likewise, a circuit that generates random numbers in the closed interval \([B, 2^{N}1]\) can be obtained by inverting the output of Comparator using a PauliX gate (this gate must also be taken into account when designing Uncomputation of the comparator). To generate numbers in the halfopen interval \((B', 2^{N}1]\), it is only necessary to set \(B' = B + 1\).
The circuit involves a total of \(2N+2\) qubits. In terms of quantum gates, the first part involves \(N+1\) Hadamard gates. The Oracle phase involves:

PauliX gates: 6N.

CNOT gates: \(8N7\).

Temporary logicalAND gates: N.

Uncomputation gates for the temporary logicalAND operation: N
Finally, the amplification phase involves:

Hadamard gates: \(2N+3\).

PauliX gates: 2N.

Nqubit Toffoli gates: 1.
Bearing in mind that the oracle and the amplification phases can be repeated I times, the final numbers are:

Number of qubits: \(2N+2\)

Hadamad gates: \((N+1)+I \times (2N+3)\)

PauliX gate: \(I \times 8N\)

CNOT gate: \(I \times (8N7)\)

Temporary logicalAND gate: \(I \times N\)

Uncomputation gate for the temporary logicalAND operation: \(I \times (N1)\)

Nqubit Toffoli gates: I.
4 Discussion
The main contribution of this work is the random number generator circuit. However, the comparator presented has been designed as part of this work. Therefore, not only the results of the generator will be discussed, but also those obtained with the comparator circuit.
4.1 Discussion on the comparator
The circuits included in the following comparison have been implemented using the Qiskit Programming Language and run in the quantum simulator simulator_mps, available in the IBM Quantum platform [41].
Table 1 shows a comparison between the comparator circuit proposed in this work and the most important halfcomparators available in the stateoftheart. This comparison has been carried out in terms of Tcount, Tdepth, and number of necessary qubits. In view of the results, it can be seen that there is no other circuit that outperforms the proposed comparator in any of the indicated metrics, except for the case of Tdepth. In terms of Tcount, the proposed circuit has a value of 4N. This value is matched by the circuit of Orts et al. [35] (labelled as Orts et al.[a] in Table 1). The rest of the circuits have values of more than double the results obtained by these two comparators.
Regarding of the Tdepth, the best circuit is a logarithmic depth version of the Orts et al. comparator (presented in the same paper as the previous one, and labelled as Orts et al. [b] in Table 1). However, this second comparator achieves this depth reduction at the cost of an increase in the Tcount and, above all, in the number of needed qubits, being in these terms the worst circuit of the whole comparison. This circuit needs \(4N  2W(N)  2log(N)\) ancilla qubits (being \(W(N)\) the number of ones in the binary expansion of N) to perform the comparison between numbers of N qubits (plus 2N qubits to encode the numbers). This number is too high for current quantum computers and simulators. For feasibility purposes, it can be stated that the following two circuits with the best Tdepth (Orts et al. [a], and the proposed circuit, with a Tdepth of 2N, almost three times less than the rest of the circuits) are the most suitable options.
Finally, in terms of the number of qubits, the best circuits are the proposed circuit and the circuit of Li et al [33], with a value of \(2N+1\). However, the circuit of Li et al. has almost three times the Tcount and Tdepth of the proposed circuit. The rest of the circuits, except for those presented in Orts et al., involve a single qubit increment but with very high Tcount and Tdepth values. Furthermore, the Orts et al. circuits, despite reducing these two metrics, require a higher number of qubits.
Previously, the most suitable choice was either the circuit of Li et al. when the number of qubits was to be optimised, or the circuit of Orts et al.[a] when a reduced number of Tgates was required. The circuit proposed in this work maintains the same number of qubits than the Li et al. circuit, but keeping the optimal levels of T gates presented by the Orts et al. circuit. It is, therefore, the most optimised comparator in such metrics currently available to the authors’ knowledge.
4.2 Discussion on the random number generator circuit
The generator circuit has been implemented using the Qiskit Programming Language and run in the quantum noisy modeling simulator ibmq_qasm_simulator, available in the IBM Quantum platform [41], according to what is specified below in this subsection.
The utility of the circuit has been measured in a context where it is useful, as explained below. Given N qubits, the numbers in the interval \([0, 2^{N}1]\) can be represented. Random numbers can be produced in this complete interval using the generator circuit, but this is pointless as it can be done simply by applying N Hadamard gates to N qubits initialised to \(0\rangle \), and then simply measuring them. Likewise, the cases in which there is only one possible value to be produced can also be discarded since such an operation is meaningless. We can also discard the cases where there are only two possible values in the interval (intervals \([0, 1]\) or \([2^{N}2, 2^{N}1]\)) as in such cases the least significant qubits could be set to 0 or 1 and randomly decide only the last qubit. The latter could also be set for intervals whose size coincides with a power of 2, but for simplicity such cases are included.
On the other hand, tests have been done for circuits generating numbers between 3 and 8 digits. The largest current quantum computers whose access is not exclusively restricted to the manufacturer have a capacity of around 20 qubits (e.g. IBM Q 20 Tokyo or IBM Q 20 Austin computers). The random number generator requires \(2N+2\) qubits. Considering a 20 qubit computer, the maximum number of digits that can be worked with is \(N=8\). This circuit is focused on current NISQera computers and simulators, so larger sizes have not been tested.
Figures 4 and 5 show the number of required circuit iterations (oracle and amplification phases) for each value of N as a function of the size of the solution interval l. Figure 4 displays the number of iterations for the 3, 4, and 5 digit cases (in blue, orange, and green, respectively). In the Figure, the Yaxis represents the number of iterations needed, while the Xaxis indicates the size of the interval. For instance, the value \([714]\) on the Xaxis indicates that this includes intervals with between 7 and 14 numbers (both cases included). The minimum number of solutions (the minimal width of the interval, l) addressed is 3 in all cases, as justified above. The maximum number of possible random values in the interval is 6, 14, and 30 for 3 digits, 4 digits, and 5 digits, respectively. For the cases of 3 and 4 digit numbers, only one Grover’s iteration is needed in all cases. For the \(N=5\) case, a single iteration is required for 5 or more solutions. 2 iterations are required when there are 3 or 4 possible solutions.
Figure 5 shows the same information as Fig. 4, but for sizes \(N=6, 7\), and 8 (in blue, orange, and green, respectively). The minimum number of solutions is still 3. The maximum number of solutions is 62, 127, and 254, respectively. Each size reaches the optimal number of iterations (i.e., a single iteration) from 10, 20, and 40 iterations, respectively. It takes 2 iterations starting at 5, 9, and 18 solutions, respectively. If these values are reduced, the number of iterations quickly starts to become unfeasible, as shown in Fig. 5.
Table 2 summarises the minimum interval sizes to run the circuit with a single iteration. It also shows this value as a percentage of the number of distinct values that can be obtained using N digits. In the best cases, all possible values results in a resourceoptimal circuit. On the other hand, for larger sizes it is necessary to include at least about a 15.625% of the possible values if the most efficient circuit possible is required. For these single iteration cases, the metrics are:

Number of qubits: \(2N+2\)

Hadamad gates: \(3N+4\)

PauliX gate: 8N

CNOT gate: \(8N7\)

Temporary logicalAND gate: N

Uncomputation gate for the temporary logicalAND operation: \(N1\)

Nqubit Toffoli gates: 1.
For each case, 10 tests (of 1024 runs each) were carried out in order to measure the effectiveness of the circuit. Figure 6 shows the average probabilities of successfully obtaining a value for the number of digits and optimal interval configurations (the cases where the circuit needs only one iteration) listed in Table 2. The shape of the plots shown in Fig. 6 conforms to what is expected by Grover’s algorithm [44]. The algorithm ensures probabilities of success above 50%. The probabilities increase until they reach a maximum, at which point they start to decrease. This pattern will continue to repeat if the number of iterations is increased, but each time with a longer repetition period. Values around 50% may be adequate in certain domains, but are insufficient for the problem at hand. However, in Fig. 6 it can be seen that random numbers with a probability always higher than 80% can be obtained for any interval if the right number of qubits is used. For instance, to generate a number in the interval \([0, 76]\) (i.e. \(l=77\)) using 8 qubits, will have a probability of success of only 70% according to Fig. 6. However, the probability of success becomes almost 100% if 7 qubits are used instead. We can then define a number of qubits for each interval so that we can ensure that the probabilities never go below 80%, as shown in Fig. 7. We can even define certain interval sizes where the probability is always greater than 90% or even 95%, as shown in Table 3. Moreover, all possible intervals can be covered using a single Grover iteration.
Finally, the uniformity of the numbers has been measured using the TestU01 software [45]. Only the values generated within the interval have been included in the measurement, thus discarding the erroneous values. Table 4 shows the percentage of uniformity achieved for each number of digits as described in Table 3. The quality of the numbers has been tested both without noise and with noise. In the latter case, the configuration described by Combarro et al. [11] was used in order to have some reference value against which to compare the results. In the work of Combarro et al., the Monobit test is used to measure the quality, obtaining a value of 0.9899 in the ideal case without noise, and 0.3962 in the case with noise. The values achieved by our generator are similar to those measured by Combarro et al. The slight improvement of our values can be attributed to the fact that we are discarding in advance the values that fall outside the intervals. Our results confirms what Combarro et al. have already indicated: the numbers generated in the presence of noise using this methodology are not uniform. In case such uniformity is needed, the application of techniques and protocols that improve the quality of the numbers generated must be used. We leave the application of such protocols for future work, as mentioned in previous sections.
5 Conclusions
In this work, a functional circuit has been proposed to generate random numbers in quantum devices. The circuit is faulttolerant, and it is optimized in terms of number of qubits, Tcount, and Tdepth. Its design is customisable for a userspecified interval. Detailed steps are given to reproduce the circuit for any digit size and interval configuration. For each of these cases, the required resources are indicated. The effectiveness of the circuit has been also tested. It has been indicated in which cases it is feasible with respect to the number of resources, and its probability of success has been measured. Complementary, we have indicated those cases in which the circuit works exceptionally well, with a probability of success of over 90% or even 95%.
Another important contribution of this work is that a reversible comparator has been presented. This circuit is used as a subcircuit of the random number generator, but is valid for use in other quantum circuits and algorithms. We have shown that this comparator is the best currently available in the literature in terms of number of qubits, Tcount, and Tdepth.
Availability of data and materials
Data sharing is not applicable to this article as no datasets were generated or analysed during the current study.
References
Pirandola S, Andersen UL, Banchi L, Berta M, Bunandar D, Colbeck R, Englund D, Gehring T, Lupo C, Ottaviani C et al.. Advances in quantum cryptography. Adv Opt Photonics. 2020;12(4):1012–236.
Pan C, Chen G, Tang J, Wu K. Numerical modeling of partial discharges in a solid dielectricbounded cavity: a review. IEEE Trans Dielectr Electr Insul. 2019;26(3):981–1000.
Chatterjee K, Goharshady AK, Pourdamghani A. Probabilistic smart contracts: secure randomness on the blockchain. In: 2019 IEEE international conference on blockchain and cryptocurrency (ICBC). IEEE; 2019. p. 403–12.
Cambou B, Telesca D. Ternary computing to strengthen cybersecurity. In: Science and information conference. Berlin: Springer; 2018. p. 898–919.
Gehring T, Lupo C, Kordts A, Solar Nikolic D, Jain N, Rydberg T, Pedersen TB, Pirandola S, Andersen UL. Homodynebased quantum random number generator at 2.9 gbps secure against quantum sideinformation. Nat Commun. 2021;12(1):1–11.
Avesani M, Marangon DG, Vallone G, Villoresi P. Sourcedeviceindependent heterodynebased quantum random number generator at 17 gbps. Nat Commun. 2018;9(1):1–7.
Huang L, Zhou H, Feng K, Xie C. Quantum random number cloud platform. npj Quantum Inf. 2021;7(1):1–7.
Ryan C, Kshirsagar M, Vaidya G, Cunningham A, Sivaraman R. Design of a cryptographically secure pseudo random number generator with grammatical evolution. Sci Rep. 2022;12(1):1–10.
Crocetti L, Di Matteo S, Nannipieri P, Fanucci L, Saponara S. Design and test of an integrated random number generator with alldigital entropy source. Entropy. 2022;24(2):139.
Cang S, Kang Z, Wang Z. Pseudorandom number generator based on a generalized conservative sprotta system. Nonlinear Dyn. 2021;104(1):827–44.
Combarro EF, Carminati F, Vallecorsa S, Ranilla J, Rúa IF. On protocols for increasing the uniformity of random bits generated with noisy quantum computers. J Supercomput. 2021;77(8):8063–81.
Mannalath V, Mishra S, Pathak A. A comprehensive review of quantum random number generators: concepts, classification and the origin of randomness. 2022. arXiv preprint. arXiv:2203.00261.
Bacco D, Vagniluca I, Da Lio B, Biagi N, Della Frera A, Calonico D, Toninelli C, Cataliotti FS, Bellini M, Oxenløwe LK et al.. Field trial of a threestate quantum key distribution scheme in the Florence metropolitan area. EPJ Quantum Technol. 2019;6(1):5.
Lowndes D, Frick S, Hart A, Rarity J. A low cost, short range quantum key distribution system. EPJ Quantum Technol. 2021;8(1):15.
Polnik M, Mazzarella L, Di Carlo M, Oi DK, Riccardi A, Arulselvan A. Scheduling of space to ground quantum key distribution. EPJ Quantum Technol. 2020;7(1):3.
Bharti K, CerveraLierta A, Kyaw TH, Haug T, AlperinLea S, Anand A, Degroote M, Heimonen H, Kottmann JS, Menke T et al.. Noisy intermediatescale quantum algorithms. Rev Mod Phys. 2022;94(1):015004.
Preskill J. Quantum computing in the NISQ era and beyond. Quantum. 2018;2:79.
Nielsen MA, Chuang IL. Quantum computation and quantum information: 10th anniversary edition. New York: Cambridge University Press; 2011.
Thapliyal H, MuñozCoreas E, Khalus V. Quantum circuit designs of carry lookahead adder optimized for Tcount, Tdepth and qubits. Sustain Comput: Inf Syst. 2021;29:100457.
Gayathri S, Kumar R, Dhanalakshmi S, Dooly G, Duraibabu DB. Tcount optimized quantum circuit designs for singleprecision floatingpoint division. Electronics. 2021;10(6):703.
Mosca M, Mukhopadhyay P. A polynomial time and space heuristic algorithm for Tcount. Quantum Sci Technol. 2021;7(1):015003.
Orts F, Ortega G, Filatovas E, Garzón EM. Implementation of three efficient 4digit faulttolerant quantum carry lookahead adders. J Supercomput. 2022;78:13323–41.
Abdessaied N, Amy M, Soeken M, Drechsler R. Technology mapping of reversible circuits to Clifford + T quantum circuits. In: 2016 IEEE 46th international symposium on multiplevalued logic (ISMVL). IEEE; 2016. p. 150–5.
Kissinger A, van de Wetering J, Vilmart R. Classical simulation of quantum circuits with partial and graphical stabiliser decompositions. 2022. arXiv preprint. arXiv:2202.09202.
Fösel T, Niu MY, Marquardt F, Li L. Quantum circuit optimization with deep reinforcement learning. 2021. arXiv preprint. arXiv:2103.07585.
de Brugière TG, Baboulin M, Valiron B, Martiel S, Allouche C. Reducing the depth of linear reversible quantum circuits. IEEE Trans Quantum Eng. 2021;2:1–22.
Schmidt H. Quantummechanical randomnumber generator. J Appl Phys. 1970;41(2):462–8.
Vincent C. The generation of truly random binary numbers. J Phys E, Sci Instrum. 1970;3(8):594.
Vincent C. Precautions for accuracy in the generation of truly random binary numbers. J Phys E, Sci Instrum. 1971;4(11):825.
Alkassar A, Nicolay T, Rohe M. Obtaining truerandom binary numbers from a weak radioactive source. In: International conference on computational science and its applications. Berlin: Springer; 2005. p. 634–46.
Gude M. Concept for a high performance random number generator based on physical random phenomena. Frequenz. 1985;39(7–8):187–90.
Pironio S, Acín A, Massar S, de La Giroday AB, Matsukevich DN, Maunz P, Olmschenk S, Hayes D, Luo L, Manning TA et al.. Random numbers certified by Bell’s theorem. Nature. 2010;464(7291):1021–4.
Li HS, Fan P, Xia HY, Peng H, Long GL. Efficient quantum arithmetic operation circuits for quantum image processing. Sci China, Phys Mech Astron. 2020;63:1–13.
Xia HY, Zhang H, Song SX, Li H, Zhou YJ, Chen X. Design and simulation of quantum image binarization using quantum comparator. Mod Phys Lett A. 2020;35(9):2050049.
Orts F, Ortega G, Cucura A, Filatovas E, Garzón E. Optimal faulttolerant quantum comparators for image binarization. J Supercomput. 2021;77(8):8433–44.
Gidney C. Halving the cost of quantum addition. Quantum. 2018;2:74.
PérezSalinas A, CerveraLierta A, GilFuster E, Latorre JI. Data reuploading for a universal quantum classifier. Quantum. 2020;4:226.
Bhattacharjee D, Saki AA, Alam M, Chattopadhyay A, Ghosh S. Muqut: multiconstraint quantum circuit mapping on NISQ computers. In: 2019 IEEE/ACM international conference on computeraided design (ICCAD). IEEE; 2019. p. 1–7.
Bennett CH. Logical reversibility of computation. IBM J Res Dev. 1973;17(6):525–32.
Jones C. Lowoverhead constructions for the faulttolerant Toffoli gate. Phys Rev A. 2013;87(2):022328.
Qiskit 0.36.2 documentation. https://qiskit.org/documentation/. Accessed: 20220531
Xia HY, Li H, Zhang H, Liang Y, Xin J. An efficient design of reversible multibit quantum comparator via only a single ancillary bit. Int J Theor Phys. 2018;57(12):3727–44.
Xia HY, Li H, Zhang H, Liang Y, Xin J. Novel multibit quantum comparators and their application in image binarization. Quantum Inf Process. 2019;18(7):229.
Cafaro C, Mancini S. On Grover’s search algorithm from a quantum information geometry viewpoint. Phys A, Stat Mech Appl. 2012;391(4):1610–25.
L’ecuyer P, Simard R. Testu01: ac library for empirical testing of random number generators. ACM Trans Math Softw. 2007;33(4):1–40.
Acknowledgements
Not applicable.
Funding
This work has been supported by the projects: RTI2018095993BI00, PID2021123278OBI00 (funded by MCIN/AEI/10.13039/501100011033/ FEDER “A way to make Europe”); P20_00748, UAL2020TICA2101, and UAL18TICA020B (funded by Junta de Andalucía and the European Regional Development Fund, ERDF); and the Research Council of Lithuania (LMTLT), agreement No. SMIP2153.
Author information
Authors and Affiliations
Contributions
Francisco Orts conceived the experiment and carried out the technical and experimental work. All authors discussed the results and contributed to the writing of the manuscript. All authors read and approved the final manuscript.
Corresponding author
Ethics declarations
Competing interests
The authors declare no competing interests.
Additional information
Publisher’s Note
Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.
Rights and permissions
Open Access This article is licensed under a Creative Commons Attribution 4.0 International License, which permits use, sharing, adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if changes were made. The images or other third party material in this article are included in the article’s Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article’s Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/licenses/by/4.0/.
About this article
Cite this article
Orts, F., Filatovas, E., Garzón, E.M. et al. A quantum circuit to generate random numbers within a specific interval. EPJ Quantum Technol. 10, 17 (2023). https://doi.org/10.1140/epjqt/s40507023001741
Received:
Accepted:
Published:
DOI: https://doi.org/10.1140/epjqt/s40507023001741
Keywords
 Quantum random numbers
 Random number generation
 Quantum computing
 Quantum circuit
 Quantum comparator
 Clifford + T gates