Q# Quantum Random Number Generator

Lou Mauget .NET, Development Technology Leave a Comment

Introduction to Building a Q# Quantum Random Number Generator

This blog focusses on building a Quantum Random Number Generator (QRNG) with Q#. In following sections, we will:

  • Give an overview of the current status of Quantum Computing today
  • Lightly discuss basic concepts surrounding quantum qubits: quantum entanglement, Superposition, and Decoherence
  • Relate superposition to the “Bloch Sphere”
  • Obtain a random value by measuring a qubit in superposition
  • Present a Q# (QRNG) that generates numbers to the console:
$ dotnet run
Hello from Quantum World!
10 Q#-generated 64-bit random integers:

We’ll begin by discussing the background of quantum computing, and then, we’ll dive into a small Q# random number generation demo.

Quantum Computers

Qubits and quantum gates compose a quantum computer. A qubit corresponds to a classical computer bit…somewhat. Its characteristics defy everyday macro-world experience. A quantum gate is an operator on one or more qubits. A Hadamard gate (H) places its input qubit into a superposition state that we’ll discuss later.

If we mindfully connect a sufficient number of qubits via a selection of quantum gates, we could create a quantum task that would vastly outperform certain classical computational tasks. Additionally, it’s possible that it could complete some tasks that are thought to be impossible for classical computers – for example, the unholy grail of breaking RSA encryption.

A hardware implementation of a logical qubit typically involves thousands of physical qubits founded on elemental particles. A logical qubit derives state from a statistical vote among physical qubits. To do this, current hardware needs supercooling to near-zero degrees Kelvin.

It’s clear that you won’t own a quantum smartwatch soon.

Quantum Computing Today

Where are the practical applications?

The issue lies in this phrase: “sufficient number of qubits.” Currently, qubits are profoundly expensive and error-prone due to “noise” in them. Adding more qubits quickly compounds the issue. That is one reason for the near-zero Kelvin temperatures involved. A quantum application may run many “shots” at some kinds of tasks, plucking a statistical winner.

Most real-world applications will need vastly more qubits than the approximately 50 that some current machines provide. Luckily, our little Quantum Random Number Generator, right now, will only need one qubit.

A quantum application concept often involves specialized algorithms that would not realistically be completed on a classical computer. Applications such as factoring large numbers can involve cooperation between a classical program and a quantum program.

Where are quantum computers?

Large organizations are making breakthroughs. Cloud-based quantum computer access for small tasks is a current or near-future on-ramp to limited quantum computing access by us, the unwashed. We have run a QRNG written in IBM’s QASM on real quantum hardware accessed via the IBM Q Experience cloud.

Check out this non-exhaustive list of enterprises working in this field:

Quantum Characteristics

We mentioned non-intuitive characteristics that defy our macro-world senses. Quantum characteristics manifest in the pico-world. For a longer, more authoritative discussion, refer to this article. If you drill down, English will give way to foundational math.

For the purposes of this blog, let’s just skim a couple of concepts at the 40,000-foot level.


Two or more qubits can be entangled, meaning that the state of each correlates with that of the others. Those state-mirroring qubits can be situated a great distance apart. In 2017, scientists experimentally verified entanglement at a 50-mile-separation. Entanglement has applications in the field of quantum information theory.

Enough said about entanglement here; we won’t need it for our QRNG.


Our QRNG depends upon superposition – another strange quantum characteristic. Placing a qubit into superposition causes its state to be indeterminate until we measure it, but observation destroys the measured state! Moreover, if we don’t measure it quickly enough, it suffers spontaneous decoherence, meaning it exits superposition.

See Also:  Quick Start: Spring Security 5 OAuth2 Login

With superposition, a measured value will be a 3D point, shown as |Ψ> in Dirac notation on the Bloch Sphere below. This comes across as complicated, but please relax. Convention simply designates any point in the Bloch northern hemisphere as a 0, while a point in the southern hemisphere as a 1.

Quantum Superposition Bloch Sphere

The word on the street is that a value sequence from a qubit is as random as any sequence in nature can be. Do you see where we’re headed for the QRNG demo?

Determining a qubit’s state by observation seems intuitive, but observation clears qubit state, taking it out of superposition. How rude! It’s as if obtaining a bank account’s balance removes the account. This is one of the hurdles of quantum computing.

Einstein wasn’t a fan: “Would a sidelong glance from a mouse suffice?”

Yet quantum computing works. It’s partially built upon observing an entity that is in superposition. Measurement takes it out of superposition, yielding its state.

Our Q# demo causes a single qubit to emit a random boolean. We call our q# operation 640 times, accumulating each 64-bit result into a set of 10 random integers. We return them as a result sequence to a C# controller.

Quantum Random Number Generator (QRNG)

Our QRNG consists of three parts:

  1. A quantum computer used like a coprocessor (simulated by a Microsoft library)
  2. Microsoft Q# code that orchestrates the quantum computer in a procedural manner
  3. Microsoft C# driver code that invokes and handles the Q# code

Quantum Simulator

If we can simulate a quantum computer on a classical computer, then what is the point of a quantum computer? Well, it’s that magic entanglement characteristic mixed as well as states of superposition. The ensuing global interconnection complexity increases exponentially with the number of qubits. Simulation processing delays for heavy problems increase accordingly.

Since our Quantum Random Number Generator uses just one qubit, a simulator is up to the task … in a pseudo-random manner.

Q# Language

Programming a raw quantum computer could involve rearranging or connecting physical hardware components. That was how users programmed the first analog computers to solve problems such as artillery ballistics.

Microsoft took another approach. Instead of interactively arranging entities in an editor, they developed Q#, a .NET language, that uses a procedural approach to abstract oddities of quantum computer hardware into a more classical language environment. This seems more accessible to some of us classical folks.

Q# supports an interface that enables delegation to pluggable backend hardware or to a quantum simulator. Our Q# currently uses a quantum simulator. Sure, this implies that our results boil down to plain old pseudo-random sequences. Nonetheless, our code would actually work on real-life quantum hardware. If Microsoft enabled the unwashed to queue jobs to actual (expensive) quantum hardware, our QRNG would be up to it.

Quantum Random Number Generator Demo

Let’s discuss our demo Quantum Random Number Generator from bottom-up: output first, followed by relevant code, and then, we’ll bring it home by discussing installation and execution. Our QRNG demo is a .NET Core application consisting of a C# controller invoking a Q# quantum task.


A dotnet run issued from the root of our QRNG project produced the following kind of console output:

Hello from Quantum World!
10 Q#-generated 64-bit random integers:

Process finished with exit code 0

Values vary with each invocation. This execution ran our core Q# fragment 10 x 64 = 640
times to accumulate that output.

See Also:  Elm Language

Heart of The Quantum Random Number Generator

Q# is a statically-typed blend of C# and F#. A type follows a declaration but can be omitted if compile-time flow type-derivation permits.

The Q# Quantum Random Number Generator operation follows. It should be readable by JavaScript, C#, Golang, or Java programmers.

   operation QuantumRandomNumberGenerator() : Int {
       mutable randomNumber = 0;
       // Accumulate 64 random bits, right-to-left, 
// each taken per-step from a single qubit
       for (i in 1 .. 64) {
           using(q = Qubit())  {   // Allocate single qubit.
               H(q);               // Hadamard gate moves qubit into superposition.
               let res = M(q);     // Measure qubit: a 50% chance of seeing 0 or 1
               // Accumulate to sliding bit sequence
               set randomNumber = LeftShiftedI(randomNumber, 1);
               if (res == One) {
                   set randomNumber = Or(randomNumber, 1);
               Reset(q);  // We must reset released qubits
       return randomNumber;

This operation’s code is taken from Microsoft’s Quickstart QRN. We suggest reading this page for more details about its relevance to the Bloch Sphere.

The central logic is:

  1. Obtain a single qubit via a Q# using statement
  2. Send it to a Hadamard quantum gate that inputs the qubit, returning it in the superposition state
  3. Measure the qubit, collapsing the superposition to a random concrete state

The quantum action centers on this fragment operating on qubit, q:

   H(q);            // Hadamard gate moves qubit into superposition.
   let res = M(q);  // Measure the qubit value: a 50% chance of seeing 0 or 1.         

Q# can carry out classical operations as well. Our operation accumulates a random 64-bit integer from repeatedly placing one qubit in superposition and then measuring it. Our invoking C# driver collects ten of those Q#-generated 64-bit integers, logging each to the console:

// C#: Gen random numbers
Console.WriteLine($"{ResultCount} Q#-generated 64-bit random integers:");
for (var d = 0; d < ResultCount; d++)
   // Call q# processing here
   var res = QuantumRandomNumberGenerator.Run(quantumSimulator).Result;
   Console.WriteLine("{0,20:X16}", res);

Build and Run

It may be helpful to view the project on gitHub. View it by clicking here.


  • A Linux, MacOS, or Windows system capable of running .NET Core
  • .NET Core 3 (ours is 3.0.101)


.NET core makes this easy on Windows, Linux, or MacOS, no IDE needed. Carry out the following steps:

  1. dotnet new -i Microsoft.Quantum.ProjectTemplates
  2. git clone https://github.com/mauget/QSharp-Random-Gen

Verify that the cloned directory tree is this:

        ── QSharp-Random-Gen
           ├── Driver.cs
           ├── Operation.qs
           ├── QSharp-Random-Gen.csproj
           ├── QSharp-Random-Gen.sln
           ├── README.md
           └── run.sh


Enter the following commands:

  1. cd QSharp-Random-Gen
  2. dotnet run

Then, verify that the console displays 10 random 64-bit numbers, as shown earlier. Run again. Verify that the numeric values differ from the first run.

That’s it. Ten distinct random numbers. A successful Quantum Random Number Generator. End of story!


In this post, we:

  • skimmed basic concepts surrounding quantum qubits
  • discussed measuring a qubit placed into quantum superposition so as to obtain its random boolean value
  • presented a Q# quantum program that generates random numbers to the console
  • showed how to clone and run the Quantum Random Number Generator project on Linux, Windows, or macOS

Consult the references listed below for more details regarding the subject matter. For quick extra credit, refer to the meta summary below.

(ID AML-18370, Andrews McNeal Licensing)


Creative Commons Bloch Sphere image attribution to Glosser.ca

Related Posts

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments