microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
katas/content/random_numbers/random_number/solution.qs
38lines · modecode
| 1 | namespace Kata { |
| 2 | open Microsoft.Quantum.Math; |
| 3 | |
| 4 | operation RandomNumberInRange(min : Int, max : Int) : Int { |
| 5 | let nBits = BitSizeI(max - min); |
| 6 | mutable output = 0; |
| 7 | repeat { |
| 8 | set output = RandomNBits(nBits); |
| 9 | } until output <= max - min; |
| 10 | return output + min; |
| 11 | } |
| 12 | |
| 13 | operation RandomNBits(N : Int) : Int { |
| 14 | mutable result = 0; |
| 15 | for i in 0..(N - 1) { |
| 16 | set result = result * 2 + RandomBit(); |
| 17 | } |
| 18 | return result; |
| 19 | } |
| 20 | |
| 21 | operation RandomBit() : Int { |
| 22 | // Allocate single qubit. |
| 23 | use q = Qubit(); |
| 24 | |
| 25 | // Set qubit in superposition state. |
| 26 | H(q); |
| 27 | |
| 28 | // Measuring the qubit and reset. |
| 29 | let result = M(q); |
| 30 | Reset(q); |
| 31 | |
| 32 | // Return integer value of result. |
| 33 | if result == One { |
| 34 | return 1; |
| 35 | } |
| 36 | return 0; |
| 37 | } |
| 38 | } |
| 39 | |