qsharp-lang 1.0.30-dev → 1.0.32-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -77,6 +77,6 @@ export default [
77
77
  {
78
78
  "title": "Shor",
79
79
  "shots": 1,
80
- "code": "/// # Sample\n/// Shor's algorithm\n///\n/// # Description\n/// Shor's algorithm is a quantum algorithm for finding the prime factors of an\n/// integer.\n///\n/// This Q# program implements Shor's algorithm.\nnamespace Sample {\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Random;\n open Microsoft.Quantum.Math;\n open Microsoft.Quantum.Unstable.Arithmetic;\n open Microsoft.Quantum.Arrays;\n\n @EntryPoint()\n operation Main() : (Int, Int) {\n let n = 143; // 11*13;\n // You can try these other examples for a lengthier computation.\n // let n = 16837; // = 113*149\n // let n = 22499; // = 149*151\n\n // Use Shor's algorithm to factor a semiprime integer.\n let (a, b) = FactorSemiprimeInteger(n);\n Message($\"Found factorization {n} = {a} * {b} \");\n return (a, b);\n }\n\n /// # Summary\n /// Uses Shor's algorithm to factor an input number.\n ///\n /// # Input\n /// ## number\n /// A semiprime integer to be factored.\n ///\n /// # Output\n /// Pair of numbers p > 1 and q > 1 such that p⋅q = `number`\n operation FactorSemiprimeInteger(number : Int) : (Int, Int) {\n // First check the most trivial case (the provided number is even).\n if number % 2 == 0 {\n Message(\"An even number has been given; 2 is a factor.\");\n return (number / 2, 2);\n }\n // These mutables will keep track of whether we found the factors, and\n // if so, what they are. The default value for the factors is (1,1).\n mutable foundFactors = false;\n mutable factors = (1, 1);\n mutable attempt = 1;\n repeat {\n Message($\"*** Factorizing {number}, attempt {attempt}.\");\n // Try to guess a number co-prime to `number` by getting a random\n // integer in the interval [1, number-1]\n let generator = DrawRandomInt(1, number - 1);\n\n // Check if the random integer is indeed co-prime.\n // If true use Quantum algorithm for Period finding.\n if GreatestCommonDivisorI(generator, number) == 1 {\n Message($\"Estimating period of {generator}.\");\n\n // Call Quantum Period finding algorithm for\n // `generator` mod `number`.\n let period = EstimatePeriod(generator, number);\n\n // Set the flag and factors values if the continued\n // fractions classical algorithm succeeds.\n set (foundFactors, factors) =\n MaybeFactorsFromPeriod(number, generator, period);\n }\n // In this case, we guessed a divisor by accident.\n else {\n // Find divisor.\n let gcd = GreatestCommonDivisorI(number, generator);\n Message($\"We have guessed a divisor {gcd} by accident. \" +\n \"No quantum computation was done.\");\n\n // Set the flag `foundFactors` to true, indicating that we\n // succeeded in finding factors.\n set foundFactors = true;\n set factors = (gcd, number / gcd);\n }\n set attempt = attempt+1;\n if (attempt > 100) {\n fail \"Failed to find factors: too many attempts!\";\n }\n }\n until foundFactors\n fixup {\n Message(\"The estimated period did not yield a valid factor. \" +\n \"Trying again.\");\n }\n\n // Return the factorization\n return factors;\n }\n\n /// # Summary\n /// Tries to find the factors of `modulus` given a `period` and `generator`.\n ///\n /// # Input\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## period\n /// The estimated period (multiplicative order) of the generator mod\n /// `modulus`.\n ///\n /// # Output\n /// A tuple of a flag indicating whether factors were found successfully,\n /// and a pair of integers representing the factors that were found.\n /// Note that the second output is only meaningful when the first output is\n /// `true`.\n function MaybeFactorsFromPeriod(\n modulus : Int,\n generator : Int,\n period : Int)\n : (Bool, (Int, Int)) {\n\n // Period finding reduces to factoring only if period is even\n if period % 2 == 0 {\n // Compute `generator` ^ `period/2` mod `number`.\n let halfPower = ExpModI(generator, period / 2, modulus);\n\n // If we are unlucky, halfPower is just -1 mod N, which is a trivial\n // case and not useful for factoring.\n if halfPower != modulus - 1 {\n // When the halfPower is not -1 mod N, halfPower-1 or\n // halfPower+1 share non-trivial divisor with `number`. Find it.\n let factor = MaxI(\n GreatestCommonDivisorI(halfPower - 1, modulus),\n GreatestCommonDivisorI(halfPower + 1, modulus)\n );\n\n // Add a flag that we found the factors, and return only if computed\n // non-trivial factors (not like 1:n or n:1)\n if (factor != 1) and (factor != modulus) {\n Message($\"Found factor={factor}\");\n return (true, (factor, modulus / factor));\n }\n } \n // Return a flag indicating we hit a trivial case and didn't get\n // any factors.\n Message($\"Found trivial factors.\");\n return (false, (1, 1));\n } else {\n // When period is odd we have to pick another generator to estimate\n // period of and start over.\n Message($\"Estimated period {period} was odd, trying again.\");\n return (false, (1, 1));\n }\n }\n\n /// # Summary\n /// Find the period of a number from an input frequency.\n ///\n /// # Input\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## frequencyEstimate\n /// The frequency that we want to convert to a period.\n /// ## bitsPrecision\n /// Number of bits of precision with which we need to estimate s/r to\n /// recover period r using continued fractions algorithm.\n /// ## currentDivisor\n /// The divisor of the generator period found so far.\n ///\n /// # Output\n /// The period as calculated from the estimated frequency via the continued\n /// fractions algorithm.\n function PeriodFromFrequency(\n modulus : Int,\n frequencyEstimate : Int,\n bitsPrecision : Int,\n currentDivisor : Int)\n : Int {\n // Now we use the ContinuedFractionConvergentI function to recover s/r\n // from dyadic fraction k/2^bitsPrecision.\n let (numerator, period) = ContinuedFractionConvergentI(\n (frequencyEstimate, 2 ^ bitsPrecision),\n modulus);\n\n // ContinuedFractionConvergentI does not guarantee the signs of the\n // numerator and denominator. Here we make sure that both are positive\n // using AbsI.\n let (numeratorAbs, periodAbs) = (AbsI(numerator), AbsI(period));\n\n // Compute and return the newly found divisor.\n let period =\n (periodAbs * currentDivisor) /\n GreatestCommonDivisorI(currentDivisor, periodAbs);\n Message($\"Found period={period}\");\n return period;\n }\n\n /// # Summary\n /// Finds a multiplicative order of the generator in the residue ring Z mod\n /// `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n ///\n /// # Output\n /// The period (multiplicative order) of the generator mod `modulus`\n operation EstimatePeriod(generator : Int, modulus : Int) : Int {\n // Here we check that the inputs to the EstimatePeriod operation are\n // valid.\n Fact(\n GreatestCommonDivisorI(generator, modulus) == 1,\n \"`generator` and `modulus` must be co-prime\");\n\n // Number of bits in the modulus with respect to which we are estimating\n // the period.\n let bitsize = BitSizeI(modulus);\n\n // The EstimatePeriod operation estimates the period r by finding an\n // approximation k/2^(bits precision) to a fraction s/r, where s is some\n // integer. Note that if s and r have common divisors we will end up\n // recovering a divisor of r and not r itself.\n\n // Number of bits of precision with which we need to estimate s/r to\n // recover period r, using continued fractions algorithm.\n let bitsPrecision = 2 * bitsize + 1;\n\n // Current estimate for the frequency of the form s/r.\n let frequencyEstimate = EstimateFrequency(generator, modulus, bitsize);\n if frequencyEstimate != 0 {\n return PeriodFromFrequency(\n modulus, frequencyEstimate, bitsPrecision, 1);\n }\n else {\n Message(\"The estimated frequency was 0, trying again.\");\n return 1;\n }\n }\n\n /// # Summary\n /// Estimates the frequency of a generator in the residue ring Z mod\n /// `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## bitsize\n /// Number of bits needed to represent the modulus.\n ///\n /// # Output\n /// The numerator k of dyadic fraction k/2^bitsPrecision approximating s/r.\n operation EstimateFrequency(generator : Int,modulus : Int, bitsize : Int)\n : Int {\n mutable frequencyEstimate = 0;\n let bitsPrecision = 2 * bitsize + 1;\n Message($\"Estimating frequency with bitsPrecision={bitsPrecision}.\");\n\n // Allocate qubits for the superposition of eigenstates of the oracle\n // that is used in period finding.\n use eigenstateRegister = Qubit[bitsize];\n\n // Initialize eigenstateRegister to 1, which is a superposition of the\n // eigenstates we are estimating the phases of.\n // We are interpreting the register as encoding an unsigned integer in\n // little-endian format.\n ApplyXorInPlace(1, eigenstateRegister);\n\n // Use phase estimation with a semiclassical Fourier transform to\n // estimate the frequency.\n use c = Qubit();\n for idx in bitsPrecision-1..-1..0 {\n H(c);\n Controlled ApplyOrderFindingOracle(\n [c],\n (generator, modulus, 1 <<< idx, eigenstateRegister));\n R1Frac(frequencyEstimate, bitsPrecision-1-idx, c);\n H(c);\n if M(c) == One {\n X(c); // Reset\n set frequencyEstimate += 1 <<< (bitsPrecision-1-idx);\n }\n }\n\n // Return all the qubits used for oracle's eigenstate back to 0 state\n // using ResetAll.\n ResetAll(eigenstateRegister);\n Message($\"Estimated frequency={frequencyEstimate}\");\n return frequencyEstimate;\n }\n\n /// # Summary\n /// Interprets `target` as encoding unsigned little-endian integer k and\n /// performs transformation |k⟩ ↦ |gᵖ⋅k mod N ⟩ where p is `power`, g is\n /// `generator` and N is `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## power\n /// Power of `generator` by which `target` is multiplied.\n /// ## target\n /// Register interpreted as little-endian which is multiplied by given power\n /// of the generator. The multiplication is performed modulo `modulus`.\n operation ApplyOrderFindingOracle(\n generator : Int,\n modulus : Int,\n power : Int,\n target : Qubit[])\n : Unit is Adj + Ctl {\n // Check that the parameters satisfy the requirements.\n Fact(\n GreatestCommonDivisorI(generator, modulus) == 1,\n \"`generator` and `modulus` must be co-prime\");\n\n // The oracle we use for order finding implements |x⟩ ↦ |x⋅a mod N⟩.\n // We also use `ExpModI` to compute a by which x must be multiplied.\n // Also note that we interpret target as unsigned integer in\n // little-endian fromat.\n ModularMultiplyByConstant(\n modulus,\n ExpModI(generator, power, modulus),\n target);\n }\n\n //\n // Arithmetic helper functions to implement order-finding oracle.\n //\n\n /// # Summary\n /// Returns the number of trailing zeroes of a number.\n ///\n /// ## Example\n /// let zeroes = NTrailingZeroes(21); // NTrailingZeroes(0b1101) = 0\n /// let zeroes = NTrailingZeroes(20); // NTrailingZeroes(0b1100) = 2\n function NTrailingZeroes(number : Int) : Int {\n Fact(number != 0, \"NTrailingZeroes: number cannot be 0.\");\n mutable nZeroes = 0;\n mutable copy = number;\n while (copy % 2 == 0) {\n set nZeroes += 1;\n set copy /= 2;\n }\n return nZeroes;\n }\n\n /// # Summary\n /// Performs modular in-place multiplication by a classical constant.\n ///\n /// # Description\n /// Given the classical constants `c` and `modulus`, and an input quantum\n /// register |𝑦⟩ in little-endian format, this operation computes\n /// `(c*x) % modulus` into |𝑦⟩.\n ///\n /// # Input\n /// ## modulus\n /// Modulus to use for modular multiplication\n /// ## c\n /// Constant by which to multiply |𝑦⟩\n /// ## y\n /// Quantum register of target\n operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[])\n : Unit is Adj + Ctl {\n use qs = Qubit[Length(y)];\n for idx in IndexRange(y) {\n let shiftedC = (c <<< idx) % modulus;\n Controlled ModularAddConstant(\n [y[idx]],\n (modulus, shiftedC, qs));\n }\n for idx in IndexRange(y) {\n SWAP(y[idx], qs[idx]);\n }\n let invC = InverseModI(c, modulus);\n for idx in IndexRange(y) {\n let shiftedC = (invC <<< idx) % modulus;\n Controlled ModularAddConstant(\n [y[idx]],\n (modulus, modulus - shiftedC, qs));\n }\n }\n\n /// # Summary\n /// Performs modular in-place addition of a classical constant into a\n /// quantum register.\n ///\n /// # Description\n /// Given the classical constants `c` and `modulus`, and an input quantum\n /// register |𝑦⟩ in little-endian format, this operation computes\n /// `(x+c) % modulus` into |𝑦⟩.\n ///\n /// # Input\n /// ## modulus\n /// Modulus to use for modular addition\n /// ## c\n /// Constant to add to |𝑦⟩\n /// ## y\n /// Quantum register of target\n operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[])\n : Unit is Adj + Ctl {\n body (...) {\n Controlled ModularAddConstant([], (modulus, c, y));\n }\n controlled (ctrls, ...) {\n // We apply a custom strategy to control this operation instead of\n // letting the compiler create the controlled variant for us in\n // which the `Controlled` functor would be distributed over each\n // operation in the body.\n //\n // Here we can use some scratch memory to save ensure that at most\n // one control qubit is used for costly operations such as\n // `AddConstant` and `CompareGreaterThenOrEqualConstant`.\n if Length(ctrls) >= 2 {\n use control = Qubit();\n within {\n Controlled X(ctrls, control);\n } apply {\n Controlled ModularAddConstant(\n [control],\n (modulus, c, y));\n }\n } else {\n use carry = Qubit();\n Controlled AddConstant(\n ctrls, (c, y + [carry]));\n Controlled Adjoint AddConstant(\n ctrls, (modulus, y + [carry]));\n Controlled AddConstant(\n [carry], (modulus, y));\n Controlled CompareGreaterThanOrEqualConstant(\n ctrls, (c, y, carry));\n }\n }\n }\n\n /// # Summary\n /// Performs in-place addition of a constant into a quantum register.\n ///\n /// # Description\n /// Given a non-empty quantum register |𝑦⟩ of length 𝑛+1 and a positive\n // constant 𝑐 < 2ⁿ, computes |𝑦 + c⟩ into |𝑦⟩.\n ///\n /// # Input\n /// ## c\n /// Constant number to add to |𝑦⟩.\n /// ## y\n /// Quantum register of second summand and target; must not be empty.\n operation AddConstant(c : Int, y : Qubit[]) : Unit is Adj + Ctl {\n // We are using this version instead of the library version that is\n // based on Fourier angles to show an advantage of sparse simulation\n // in this sample.\n let n = Length(y);\n Fact(n > 0, \"Bit width must be at least 1\");\n Fact(c >= 0, \"constant must not be negative\");\n Fact(c < 2^n, \"constant must be smaller than {2^n)}\");\n if c != 0 {\n // If c has j trailing zeroes than the j least significant bits of y\n // won't be affected by the addition and can therefore be ignored by\n // applying the addition only to the other qubits and shifting c\n // accordingly.\n let j = NTrailingZeroes(c);\n use x = Qubit[n - j];\n within {\n ApplyXorInPlace(c >>> j, x);\n } apply {\n IncByLE(x, y[j...]);\n }\n }\n }\n\n /// # Summary\n /// Performs greater-than-or-equals comparison to a constant.\n ///\n /// # Description\n /// Toggles output qubit `target` if and only if input register `x` is\n /// greater than or equal to `c`.\n ///\n /// # Input\n /// ## c\n /// Constant value for comparison.\n /// ## x\n /// Quantum register to compare against.\n /// ## target\n /// Target qubit for comparison result.\n ///\n /// # Reference\n /// This construction is described in [Lemma 3, arXiv:2201.10200]\n operation CompareGreaterThanOrEqualConstant(\n c : Int,\n x : Qubit[],\n target : Qubit)\n : Unit is Adj+Ctl {\n let bitWidth = Length(x);\n if c == 0 {\n X(target);\n } elif c >= (2^bitWidth) {\n // do nothing\n } elif c == (2^(bitWidth - 1)) {\n CNOT(Tail(x), target);\n } else {\n // normalize constant\n let l = NTrailingZeroes(c);\n let cNormalized = c >>> l;\n let xNormalized = x[l...];\n let bitWidthNormalized = Length(xNormalized);\n use qs = Qubit[bitWidthNormalized - 1];\n let cs1 = [Head(xNormalized)] + Most(qs);\n Fact(Length(cs1) == Length(qs),\n \"Arrays should be of the same length.\");\n within {\n for i in 0..Length(cs1)-1 {\n let op =\n cNormalized &&& (1 <<< (i+1)) != 0 ?\n ApplyAnd | ApplyOr;\n op(cs1[i], xNormalized[i+1], qs[i]);\n }\n } apply {\n CNOT(Tail(qs), target);\n }\n }\n }\n\n /// # Summary\n /// Inverts a given target qubit if and only if both control qubits are in\n /// the 1 state, using measurement to perform the adjoint operation.\n ///\n /// # Description\n /// Inverts `target` if and only if both controls are 1, but assumes that\n /// `target` is in state 0. The operation has T-count 4, T-depth 2 and\n /// requires no helper qubit, and may therefore be preferable to a CCNOT\n /// operation, if `target` is known to be 0.\n /// The adjoint of this operation is measurement based and requires no T\n /// gates.\n /// Although the Toffoli gate (CCNOT) will perform faster in in simulations,\n /// this version has lower T gate requirements.\n ///\n /// # Input\n /// ## control1\n /// First control qubit\n /// ## control2\n /// Second control qubit\n /// ## target\n /// Target auxiliary qubit; must be in state 0\n ///\n /// # References\n /// - Cody Jones: \"Novel constructions for the fault-tolerant\n /// Toffoli gate\",\n /// Phys. Rev. A 87, 022328, 2013\n /// [arXiv:1212.5069](https://arxiv.org/abs/1212.5069)\n /// doi:10.1103/PhysRevA.87.022328\n /// - Craig Gidney: \"Halving the cost of quantum addition\",\n /// Quantum 2, page 74, 2018\n /// [arXiv:1709.06648](https://arxiv.org/abs/1709.06648)\n /// doi:10.1103/PhysRevA.85.044302\n /// - Mathias Soeken: \"Quantum Oracle Circuits and the Christmas\n /// Tree Pattern\",\n /// [Blog article from December 19, 2019](https://msoeken.github.io/blog_qac.html)\n /// (note: explains the multiple controlled construction)\n operation ApplyAnd(control1 : Qubit, control2 : Qubit, target : Qubit)\n : Unit is Adj {\n body (...) {\n H(target);\n T(target);\n CNOT(control1, target);\n CNOT(control2, target);\n within {\n CNOT(target, control1);\n CNOT(target, control2);\n }\n apply {\n Adjoint T(control1);\n Adjoint T(control2);\n T(target);\n }\n H(target);\n S(target);\n }\n adjoint (...) {\n H(target);\n if (M(target) == One) {\n X(target);\n CZ(control1, control2);\n }\n }\n }\n\n /// # Summary\n /// Applies X to the target if any of the controls are 1.\n operation ApplyOr(control1 : Qubit, control2 : Qubit, target : Qubit)\n : Unit is Adj {\n within {\n ApplyToEachA(X, [control1, control2]);\n } apply {\n ApplyAnd(control1, control2, target);\n X(target);\n }\n }\n}\n"
80
+ "code": "/// # Sample\n/// Shor's algorithm\n///\n/// # Description\n/// Shor's algorithm is a quantum algorithm for finding the prime factors of an\n/// integer.\n///\n/// This Q# program implements Shor's algorithm.\nnamespace Sample {\n open Microsoft.Quantum.Convert;\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Random;\n open Microsoft.Quantum.Math;\n open Microsoft.Quantum.Unstable.Arithmetic;\n open Microsoft.Quantum.Arrays;\n\n @EntryPoint()\n operation Main() : (Int, Int) {\n let n = 143; // 11*13;\n // You can try these other examples for a lengthier computation.\n // let n = 16837; // = 113*149\n // let n = 22499; // = 149*151\n\n // Use Shor's algorithm to factor a semiprime integer.\n let (a, b) = FactorSemiprimeInteger(n);\n Message($\"Found factorization {n} = {a} * {b} \");\n return (a, b);\n }\n\n /// # Summary\n /// Uses Shor's algorithm to factor an input number.\n ///\n /// # Input\n /// ## number\n /// A semiprime integer to be factored.\n ///\n /// # Output\n /// Pair of numbers p > 1 and q > 1 such that p⋅q = `number`\n operation FactorSemiprimeInteger(number : Int) : (Int, Int) {\n // First check the most trivial case (the provided number is even).\n if number % 2 == 0 {\n Message(\"An even number has been given; 2 is a factor.\");\n return (number / 2, 2);\n }\n // These mutables will keep track of whether we found the factors, and\n // if so, what they are. The default value for the factors is (1,1).\n mutable foundFactors = false;\n mutable factors = (1, 1);\n mutable attempt = 1;\n repeat {\n Message($\"*** Factorizing {number}, attempt {attempt}.\");\n // Try to guess a number co-prime to `number` by getting a random\n // integer in the interval [1, number-1]\n let generator = DrawRandomInt(1, number - 1);\n\n // Check if the random integer is indeed co-prime.\n // If true use Quantum algorithm for Period finding.\n if GreatestCommonDivisorI(generator, number) == 1 {\n Message($\"Estimating period of {generator}.\");\n\n // Call Quantum Period finding algorithm for\n // `generator` mod `number`.\n let period = EstimatePeriod(generator, number);\n\n // Set the flag and factors values if the continued\n // fractions classical algorithm succeeds.\n set (foundFactors, factors) =\n MaybeFactorsFromPeriod(number, generator, period);\n }\n // In this case, we guessed a divisor by accident.\n else {\n // Find divisor.\n let gcd = GreatestCommonDivisorI(number, generator);\n Message($\"We have guessed a divisor {gcd} by accident. \" +\n \"No quantum computation was done.\");\n\n // Set the flag `foundFactors` to true, indicating that we\n // succeeded in finding factors.\n set foundFactors = true;\n set factors = (gcd, number / gcd);\n }\n set attempt = attempt+1;\n if (attempt > 100) {\n fail \"Failed to find factors: too many attempts!\";\n }\n }\n until foundFactors\n fixup {\n Message(\"The estimated period did not yield a valid factor. \" +\n \"Trying again.\");\n }\n\n // Return the factorization\n return factors;\n }\n\n /// # Summary\n /// Tries to find the factors of `modulus` given a `period` and `generator`.\n ///\n /// # Input\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## period\n /// The estimated period (multiplicative order) of the generator mod\n /// `modulus`.\n ///\n /// # Output\n /// A tuple of a flag indicating whether factors were found successfully,\n /// and a pair of integers representing the factors that were found.\n /// Note that the second output is only meaningful when the first output is\n /// `true`.\n function MaybeFactorsFromPeriod(\n modulus : Int,\n generator : Int,\n period : Int)\n : (Bool, (Int, Int)) {\n\n // Period finding reduces to factoring only if period is even\n if period % 2 == 0 {\n // Compute `generator` ^ `period/2` mod `number`.\n let halfPower = ExpModI(generator, period / 2, modulus);\n\n // If we are unlucky, halfPower is just -1 mod N, which is a trivial\n // case and not useful for factoring.\n if halfPower != modulus - 1 {\n // When the halfPower is not -1 mod N, halfPower-1 or\n // halfPower+1 share non-trivial divisor with `number`. Find it.\n let factor = MaxI(\n GreatestCommonDivisorI(halfPower - 1, modulus),\n GreatestCommonDivisorI(halfPower + 1, modulus)\n );\n\n // Add a flag that we found the factors, and return only if computed\n // non-trivial factors (not like 1:n or n:1)\n if (factor != 1) and (factor != modulus) {\n Message($\"Found factor={factor}\");\n return (true, (factor, modulus / factor));\n }\n }\n // Return a flag indicating we hit a trivial case and didn't get\n // any factors.\n Message($\"Found trivial factors.\");\n return (false, (1, 1));\n } else {\n // When period is odd we have to pick another generator to estimate\n // period of and start over.\n Message($\"Estimated period {period} was odd, trying again.\");\n return (false, (1, 1));\n }\n }\n\n /// # Summary\n /// Find the period of a number from an input frequency.\n ///\n /// # Input\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## frequencyEstimate\n /// The frequency that we want to convert to a period.\n /// ## bitsPrecision\n /// Number of bits of precision with which we need to estimate s/r to\n /// recover period r using continued fractions algorithm.\n /// ## currentDivisor\n /// The divisor of the generator period found so far.\n ///\n /// # Output\n /// The period as calculated from the estimated frequency via the continued\n /// fractions algorithm.\n function PeriodFromFrequency(\n modulus : Int,\n frequencyEstimate : Int,\n bitsPrecision : Int,\n currentDivisor : Int)\n : Int {\n // Now we use the ContinuedFractionConvergentI function to recover s/r\n // from dyadic fraction k/2^bitsPrecision.\n let (numerator, period) = ContinuedFractionConvergentI(\n (frequencyEstimate, 2 ^ bitsPrecision),\n modulus);\n\n // ContinuedFractionConvergentI does not guarantee the signs of the\n // numerator and denominator. Here we make sure that both are positive\n // using AbsI.\n let (numeratorAbs, periodAbs) = (AbsI(numerator), AbsI(period));\n\n // Compute and return the newly found divisor.\n let period =\n (periodAbs * currentDivisor) /\n GreatestCommonDivisorI(currentDivisor, periodAbs);\n Message($\"Found period={period}\");\n return period;\n }\n\n /// # Summary\n /// Finds a multiplicative order of the generator in the residue ring Z mod\n /// `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n ///\n /// # Output\n /// The period (multiplicative order) of the generator mod `modulus`\n operation EstimatePeriod(generator : Int, modulus : Int) : Int {\n // Here we check that the inputs to the EstimatePeriod operation are\n // valid.\n Fact(\n GreatestCommonDivisorI(generator, modulus) == 1,\n \"`generator` and `modulus` must be co-prime\");\n\n // Number of bits in the modulus with respect to which we are estimating\n // the period.\n let bitsize = BitSizeI(modulus);\n\n // The EstimatePeriod operation estimates the period r by finding an\n // approximation k/2^(bits precision) to a fraction s/r, where s is some\n // integer. Note that if s and r have common divisors we will end up\n // recovering a divisor of r and not r itself.\n\n // Number of bits of precision with which we need to estimate s/r to\n // recover period r, using continued fractions algorithm.\n let bitsPrecision = 2 * bitsize + 1;\n\n // Current estimate for the frequency of the form s/r.\n let frequencyEstimate = EstimateFrequency(generator, modulus, bitsize);\n if frequencyEstimate != 0 {\n return PeriodFromFrequency(\n modulus, frequencyEstimate, bitsPrecision, 1);\n }\n else {\n Message(\"The estimated frequency was 0, trying again.\");\n return 1;\n }\n }\n\n /// # Summary\n /// Estimates the frequency of a generator in the residue ring Z mod\n /// `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## bitsize\n /// Number of bits needed to represent the modulus.\n ///\n /// # Output\n /// The numerator k of dyadic fraction k/2^bitsPrecision approximating s/r.\n operation EstimateFrequency(generator : Int,modulus : Int, bitsize : Int)\n : Int {\n mutable frequencyEstimate = 0;\n let bitsPrecision = 2 * bitsize + 1;\n Message($\"Estimating frequency with bitsPrecision={bitsPrecision}.\");\n\n // Allocate qubits for the superposition of eigenstates of the oracle\n // that is used in period finding.\n use eigenstateRegister = Qubit[bitsize];\n\n // Initialize eigenstateRegister to 1, which is a superposition of the\n // eigenstates we are estimating the phases of.\n // We are interpreting the register as encoding an unsigned integer in\n // little-endian format.\n ApplyXorInPlace(1, eigenstateRegister);\n\n // Use phase estimation with a semiclassical Fourier transform to\n // estimate the frequency.\n use c = Qubit();\n for idx in bitsPrecision-1..-1..0 {\n H(c);\n Controlled ApplyOrderFindingOracle(\n [c],\n (generator, modulus, 1 <<< idx, eigenstateRegister));\n R1Frac(frequencyEstimate, bitsPrecision-1-idx, c);\n H(c);\n if M(c) == One {\n X(c); // Reset\n set frequencyEstimate += 1 <<< (bitsPrecision-1-idx);\n }\n }\n\n // Return all the qubits used for oracle's eigenstate back to 0 state\n // using ResetAll.\n ResetAll(eigenstateRegister);\n Message($\"Estimated frequency={frequencyEstimate}\");\n return frequencyEstimate;\n }\n\n /// # Summary\n /// Interprets `target` as encoding unsigned little-endian integer k\n /// and performs transformation |k⟩ ↦ |gᵖ⋅k mod N ⟩ where\n /// p is `power`, g is `generator` and N is `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period)\n /// of which is being estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus`\n /// in which the multiplicative order of `generator` is being estimated.\n /// ## power\n /// Power of `generator` by which `target` is multiplied.\n /// ## target\n /// Register interpreted as little-endian which is multiplied by\n /// given power of the generator. The multiplication is performed modulo\n /// `modulus`.\n internal operation ApplyOrderFindingOracle(\n generator : Int, modulus : Int, power : Int, target : Qubit[]\n )\n : Unit\n is Adj + Ctl {\n // The oracle we use for order finding implements |x⟩ ↦ |x⋅a mod N⟩. We\n // also use `ExpModI` to compute a by which x must be multiplied. Also\n // note that we interpret target as unsigned integer in little-endian\n // format.\n ModularMultiplyByConstant(\n modulus,\n ExpModI(generator, power, modulus),\n target);\n }\n\n /// # Summary\n /// Performs modular in-place multiplication by a classical constant.\n ///\n /// # Description\n /// Given the classical constants `c` and `modulus`, and an input quantum\n /// register |𝑦⟩ in little-endian format, this operation computes\n /// `(c*x) % modulus` into |𝑦⟩.\n ///\n /// # Input\n /// ## modulus\n /// Modulus to use for modular multiplication\n /// ## c\n /// Constant by which to multiply |𝑦⟩\n /// ## y\n /// Quantum register of target\n internal operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[])\n : Unit is Adj + Ctl {\n use qs = Qubit[Length(y)];\n for idx in IndexRange(y) {\n let shiftedC = (c <<< idx) % modulus;\n Controlled ModularAddConstant(\n [y[idx]],\n (modulus, shiftedC, qs));\n }\n for idx in IndexRange(y) {\n SWAP(y[idx], qs[idx]);\n }\n let invC = InverseModI(c, modulus);\n for idx in IndexRange(y) {\n let shiftedC = (invC <<< idx) % modulus;\n Controlled ModularAddConstant(\n [y[idx]],\n (modulus, modulus - shiftedC, qs));\n }\n }\n\n /// # Summary\n /// Performs modular in-place addition of a classical constant into a\n /// quantum register.\n ///\n /// Given the classical constants `c` and `modulus`, and an input quantum\n /// register |𝑦⟩ in little-endian format, this operation computes\n /// `(x+c) % modulus` into |𝑦⟩.\n ///\n /// # Input\n /// ## modulus\n /// Modulus to use for modular addition\n /// ## c\n /// Constant to add to |𝑦⟩\n /// ## y\n /// Quantum register of target\n internal operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[])\n : Unit is Adj + Ctl {\n body (...) {\n Controlled ModularAddConstant([], (modulus, c, y));\n }\n controlled (ctrls, ...) {\n // We apply a custom strategy to control this operation instead of\n // letting the compiler create the controlled variant for us in\n // which the `Controlled` functor would be distributed over each\n // operation in the body.\n //\n // Here we can use some scratch memory to save ensure that at most\n // one control qubit is used for costly operations such as\n // `AddConstant` and `CompareGreaterThenOrEqualConstant`.\n if Length(ctrls) >= 2 {\n use control = Qubit();\n within {\n Controlled X(ctrls, control);\n } apply {\n Controlled ModularAddConstant([control], (modulus, c, y));\n }\n } else {\n use carry = Qubit();\n Controlled IncByI(ctrls, (c, y + [carry]));\n Controlled Adjoint IncByI(ctrls, (modulus, y + [carry]));\n Controlled IncByI([carry], (modulus, y));\n Controlled ApplyIfLessOrEqualL(ctrls, (X, IntAsBigInt(c), y, carry));\n }\n }\n }\n}\n"
81
81
  }
82
82
  ];
Binary file
Binary file
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "qsharp-lang",
3
3
  "description": "qsharp language package for quantum development",
4
- "version": "1.0.30-dev",
4
+ "version": "1.0.32-dev",
5
5
  "license": "MIT",
6
6
  "engines": {
7
7
  "node": ">=16.17.0"