From a2d9863f444abaf489e8ee2769a71de76d37acc8 Mon Sep 17 00:00:00 2001 From: Mathias Soeken Date: Mon, 1 Feb 2021 09:16:54 +0100 Subject: [PATCH 1/2] Iterative BitSizeL implementation. --- Standard/src/Math/Functions.qs | 14 +++++++------- Standard/tests/Math/MathTests.qs | 8 ++++++++ 2 files changed, 15 insertions(+), 7 deletions(-) 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..b7fd4b245e3 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; + Fact(BitSizeL(1L <<< exp) == exp + 1, $"unexpected bitsize for exponent {exp} (k = {k})"); + } + } @Test("QuantumSimulator") function ExpModIsCorrect () : Unit { From fd4b2b335c3f327432885b8f4306ff542e845888 Mon Sep 17 00:00:00 2001 From: Mathias Soeken Date: Tue, 2 Feb 2021 17:24:54 +0100 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: Chris Granade --- Standard/tests/Math/MathTests.qs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Standard/tests/Math/MathTests.qs b/Standard/tests/Math/MathTests.qs index b7fd4b245e3..f733f90e71e 100644 --- a/Standard/tests/Math/MathTests.qs +++ b/Standard/tests/Math/MathTests.qs @@ -73,7 +73,7 @@ namespace Microsoft.Quantum.Canon { function CanComputeBitSizeFromLargeNumbers () : Unit { for (k in 1 .. 100) { let exp = 128 * k; - Fact(BitSizeL(1L <<< exp) == exp + 1, $"unexpected bitsize for exponent {exp} (k = {k})"); + EqualityFactI(BitSizeL(1L <<< exp), exp + 1, $"unexpected bitsize for exponent {exp} (k = {k})"); } }