microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.21.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

samples/OpenQASM/RandomNumber.qasm

44lines · modeblame

285baa4cDmitryVasilevsky1 years ago1// OpenQASM Quantum Random Number Generator
2//
3// This program implements a quantum random number generator by setting qubits
4// in superposition and then using the measurement results as random bits.
5
6OPENQASM 3;
7include "stdgates.inc";
8
9// Generates one random bit using a qubit `q`.
10def GenerateRandomBit(qubit q) -> bit {
11// Resets qubit `q` to |0〉 state
12reset q;
13// Sets the qubit into superposition of 0 and 1 using the Hadamard gate.
14h q;
15
16// At this point qubit `q` has 50% chance of being measured in the |0〉 state
17// and 50% chance of being measured in the |1〉 state.
18bit b = measure q;
19
20// Return the measurement result - a random bit.
21return b;
22}
23
24// Generates a random integer with `nBit` bits using qubit `q`
25def GenerateRandomNumber(qubit q, int nBits) -> int {
26int number = 0;
27
28// Loop `nBits` times to generate `nBits` random bits.
29for int k in [1:nBits] {
30// Shift the number left by 1 to make space for the next bit.
31number <<= 1;
32// Set the least significant bit of the number to a random bit.
33number |= GenerateRandomBit(q);
34}
35
36// Return the random number.
37return number;
38}
39
40// User one qubit `q`.
41qubit q;
42
43// Generate a 5-bit random number using the qubit `q`.
44int random = GenerateRandomNumber(q, 5);