# How to create a q# operation to generate a random number from 1 to max?

I have the following problem: I want to create a q# operation for generating a random integer from 1 to max and return the generated number. What algorithm do I need? What does the q# code look like? I am very new to quantum computing so sorry if this is a simple question!

With Q# you can generate random numbers in two ways:

1. Using a classical pseudorandom number generator, which is exactly the same that a classical language like Python does when you use the library random. As Mariia Mykhailova says in the comments, Q# has a built-in operation RandomInt that does exactly this: RandomInt

2. Using a quantum operation that uses measurements on qubits to extract random bits to build a random number. Unfortunately, right now Q# is not yet compatible with any real quantum hardware, so to implement this method you will need to use a classical simulator of a quantum computer that ultimately will implement a classical pseudorandom function like in (1).

However, since you're new in quantum computing and you want to learn, choosing (2), even if at the end is just a convoluted version of (1), makes sense for pedagogical purposes. So let's see how to implement (2) using Q# and Python.

• a) First we need to create a Q# file (Operation.qs) to obtain random bits from measuring qubits. To see how you have a nice tutorial here. Your Q# code should look like this:

namespace Quantum { open Microsoft.Quantum.Intrinsic; operation QuantumRandomNumberGenerator() : Result { using(q = Qubit()) { H(q); let r = M(q); Reset(q); return r; } } }

• b) Secondly we need to create a Python file (in the same folder than the .qs file) that is going to build an integer by calling the quantum operation defined above several times. The code is the following (comments inside the code):

Text code:

import qsharp
from Quantum import QuantumRandomNumberGenerator
bit_string = []
max = 50
for i in range(0, max.bit_length()):
bit_string.append(QuantumRandomNumberGenerator.simulate())
number = int("".join(str(x) for x in bit_string), 2)
print(number)


Now if you execute this Python code in the terminal (supposing you have all the dependencies correctly installed) the following message should appear in the command promt:

Preparing Q# environment...
33


My random number was 33.