microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
7c4c1b4c424591b52bf0c1009540c321c7756e69

Branches

Tags

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

Clone

HTTPS

Download ZIP

samples/OpenQASM/RandomNumber.qasm

44lines · modecode

1// 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
12 reset q;
13 // Sets the qubit into superposition of 0 and 1 using the Hadamard gate.
14 h 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.
18 bit b = measure q;
19
20 // Return the measurement result - a random bit.
21 return b;
22}
23
24// Generates a random integer with `nBit` bits using qubit `q`
25def GenerateRandomNumber(qubit q, int nBits) -> int {
26 int number = 0;
27
28 // Loop `nBits` times to generate `nBits` random bits.
29 for int k in [1:nBits] {
30 // Shift the number left by 1 to make space for the next bit.
31 number <<= 1;
32 // Set the least significant bit of the number to a random bit.
33 number |= GenerateRandomBit(q);
34 }
35
36 // Return the random number.
37 return 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);
45