microsoft/qdk

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.20.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

samples/getting_started/RandomBits.qs

36lines · modeblame

c97c05a1DmitryVasilevsky1 years ago1/// # 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.
10GenerateNRandomBits(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
17mutable results = [];
18for _ in 1..nBits {
19// Append next random result to the array
20results += [GenerateRandomBit()];
21}
22results
23}
24
25/// # Summary
26/// Generates a random bit in the form of `Zero` or `One` result.
27operation GenerateRandomBit() : Result {
28// Allocate a qubit
29use q = Qubit();
30// Set the qubit into uniform superposition of |0〉 and |1〉
31H(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.
35MResetZ(q)
36}