microsoft/qdk

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.0.10-rc

Branches

Tags

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

Clone

HTTPS

Download ZIP

samples/algorithms/QRNG.qs

64lines · modecode

1/// # Sample
2/// Quantum Random Number Generator
3///
4/// # Description
5/// This program implements a quantum ranndom number generator by setting qubits
6/// in superposition and then using the measurement results as random bits.
7namespace Sample {
8 open Microsoft.Quantum.Convert;
9 open Microsoft.Quantum.Intrinsic;
10 open Microsoft.Quantum.Math;
11
12 @EntryPoint()
13 operation Main() : Int {
14 let max = 100;
15 Message($"Sampling a random number between 0 and {max}: ");
16
17 // Generate random number in the 0..max range.
18 return GenerateRandomNumberInRange(max);
19 }
20
21 /// # Summary
22 /// Generates a random number between 0 and `max`.
23 operation GenerateRandomNumberInRange(max : Int) : Int {
24 // Determine the number of bits needed to represent `max` and store it
25 // in the `nBits` variable. Then generate `nBits` random bits which will
26 // represent the generated random number.
27 mutable bits = [];
28 let nBits = BitSizeI(max);
29 for idxBit in 1..nBits {
30 set bits += [GenerateRandomBit()];
31 }
32 let sample = ResultArrayAsInt(bits);
33
34 // Return random number if it is within the requested range.
35 // Generate it again if it is outside the range.
36 return sample > max ? GenerateRandomNumberInRange(max) | sample;
37 }
38
39 /// # Summary
40 /// Generates a random bit.
41 operation GenerateRandomBit() : Result {
42 // Allocate a qubit.
43 use q = Qubit();
44
45 // Set the qubit into superposition of 0 and 1 using the Hadamard
46 // operation `H`.
47 H(q);
48
49 // At this point the qubit `q` has 50% chance of being measured in the
50 // |0〉 state and 50% chance of being measured in the |1〉 state.
51 // Measure the qubit value using the `M` operation, and store the
52 // measurement value in the `result` variable.
53 let result = M(q);
54
55 // Reset qubit to the |0〉 state.
56 // Qubits must be in the |0〉 state by the time they are released.
57 Reset(q);
58
59 // Return the result of the measurement.
60 return result;
61
62 // Note that Qubit `q` is automatically released at the end of the block.
63 }
64}
65