diff --git a/Standard/src/Math/Functions.qs b/Standard/src/Math/Functions.qs index e4212fa982d..dafc903deed 100644 --- a/Standard/src/Math/Functions.qs +++ b/Standard/src/Math/Functions.qs @@ -551,12 +551,6 @@ namespace Microsoft.Quantum.Math { return AccumulatedBitsizeI(a, 0); } - /// # Summary - /// Helper function used to recursively calculate the bitsize of a value. - internal function AccumulatedBitsizeL(val : BigInt, bitsize : Int) : Int { - return val == 0L ? bitsize | AccumulatedBitsizeL(val / 2L, bitsize + 1); - } - /// # Summary /// For a non-negative integer `a`, returns the number of bits required to represent `a`. @@ -572,7 +566,13 @@ namespace Microsoft.Quantum.Math { /// The bit-size of `a`. function BitSizeL(a : BigInt) : Int { Fact(a >= 0L, $"`a` must be non-negative"); - return AccumulatedBitsizeL(a, 0); + mutable bitsize = 0; + mutable val = a; + while (val != 0L) { + set bitsize += 1; + set val /= 2L; + } + return bitsize; } diff --git a/Standard/tests/Math/MathTests.qs b/Standard/tests/Math/MathTests.qs index b4fd41dfb35..f733f90e71e 100644 --- a/Standard/tests/Math/MathTests.qs +++ b/Standard/tests/Math/MathTests.qs @@ -68,6 +68,14 @@ namespace Microsoft.Quantum.Canon { EqualityFactI(BitSizeI(3), 2, $"BitSizeI(3) must be 2"); EqualityFactI(BitSizeI(7), 3, $"BitSizeI(7) must be 2"); } + + @Test("QuantumSimulator") + function CanComputeBitSizeFromLargeNumbers () : Unit { + for (k in 1 .. 100) { + let exp = 128 * k; + EqualityFactI(BitSizeL(1L <<< exp), exp + 1, $"unexpected bitsize for exponent {exp} (k = {k})"); + } + } @Test("QuantumSimulator") function ExpModIsCorrect () : Unit {