microsoft / QuantumKatas

Tutorials and programming exercises for learning Q# and quantum computing
MIT License
4.53k stars 1.21k forks source link

Exercise 5 for RandomNumberGenerationTutorial - slightly cleaner solution #816

Closed abrassel closed 1 year ago

abrassel commented 2 years ago

The current approach for the RandomNumberGenerationTutorial tries to generate random numbers from [0, max) until it finds a value in [min, max]. You could make it a bit more efficient this way:

operation RandomNumberInRange (min : Int, max : Int) : Int {
    let range = max - min;
    let N = BitSizeI(range + 1);
    mutable result = 0;
    repeat {
        set result = RandomNBits(N);
    }
    until result <= range;
    return min + result;
}

Also, because the original implementation calls BitSizeI(max), and RandomNBits(N) generates values between [0, 2^N-1], if max is a power of 2 (e.g. 2^N), then RandomNBits will generate values in the range [0, max). Adding +1 to the range fixes this. Incidentally, it looks like the tests don't detect this edge case, as I was able to pass with and without the +1

Manvi-Agrawal commented 2 years ago

@abrassel , seems there are three things at play here: efficiency of current algorithm, correctness of existing solution and passing of your solution with and without +1.

For alternative solution, I have a minor suggestion to use let N= BitSizeI(range).

I hope this answers your query. @tcNickolas thoughts?

abrassel commented 2 years ago

Thank you Manvi!

tcNickolas commented 1 year ago

I'm sorry for not answering this back in summer! I'm not sure how I've missed it, possibly I've read it and nodded along but got distracted before I actually commented?

I agree that it makes sense to use the more efficient approach you're describing, both as the main reference solution in the ReferenceImplementation.qs and in the workbook. Would you be interested in sending the pull request with the change? (I understand if you're not, it's been a couple months, which I'm terribly sorry about...)

abrassel commented 1 year ago

Hi Nickolas! I don't have the time at the moment to submit the PR, but you are welcome to copy and paste this solution yourself!