microsoft/qdk

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
iadavis/3208-leak-fixes

Branches

Tags

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

Clone

HTTPS

Download ZIP

samples/getting_started/RandomBits.qs

36lines · modecode

1/// # Summary
2/// Simple Quantum Random Number Generator sample
3///
4/// # Description
5/// This program implements a quantum random number generator by setting qubits
6/// into superposition and then using the measurement results as random bits.
7/// This is equivalent to generating a random number in the range of 0..2ᴺ-1.
8operation Main() : Result[] {
9 // Generate a 5-bit random number.
10 GenerateNRandomBits(5)
11}
12
13/// # Summary
14/// Generates N random bits in the form of `Zero` or `One` results.
15operation GenerateNRandomBits(nBits : Int) : Result[] {
16 // Array for the results
17 mutable results = [];
18 for _ in 1..nBits {
19 // Append next random result to the array
20 results += [GenerateRandomBit()];
21 }
22 results
23}
24
25/// # Summary
26/// Generates a random bit in the form of `Zero` or `One` result.
27operation GenerateRandomBit() : Result {
28 // Allocate a qubit
29 use q = Qubit();
30 // Set the qubit into uniform superposition of |0〉 and |1〉
31 H(q);
32 // Now the qubit has 50% chance of being measured as `One`
33 // and 50% chance of being measured as `Zero`.
34 // Measure and reset the qubit. Return the result.
35 MResetZ(q)
36}
37