Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
90e5163
Add Q# library for Arithmetic
fedimser Jul 23, 2026
ee4b7cf
add library tests to integration tests
fedimser Jul 23, 2026
04aff6b
remove tests from pyright config
fedimser Jul 23, 2026
9edcd90
Prevent divergent types from flowing out of loop and conjugate exprs …
swernli Jul 23, 2026
3fef601
Add outFiles to launch.json (#3506)
amcasey Jul 23, 2026
f97b3e1
update some references
fedimser Jul 23, 2026
d5be0d0
add trailing newlines
fedimser Jul 23, 2026
117b095
update references
fedimser Jul 23, 2026
a34c25b
add trailing newline
fedimser Jul 23, 2026
78950d2
Q# format
fedimser Jul 23, 2026
d537df3
update some comments
fedimser Jul 23, 2026
bec5264
update comments
fedimser Jul 23, 2026
9ee664f
Allow blocks in interpolated string expressions (#3503)
HABER7789 Jul 23, 2026
268e445
[Stim] Optimize noise intrinsic emission and support more noise instr…
joao-boechat Jul 24, 2026
b5ad165
Bump linkify-it from 5.0.1 to 5.0.2 (#3513)
dependabot[bot] Jul 24, 2026
7d8a8a6
[STIM] SELECT block improvements + support for REPEAT (#3499)
joao-boechat Jul 24, 2026
2b113cf
Bump dompurify from 3.4.11 to 3.4.12 (#3514)
dependabot[bot] Jul 24, 2026
88eddf6
Bump postcss from 8.5.12 to 8.5.23 in /source/jupyterlab (#3515)
dependabot[bot] Jul 24, 2026
0529b5a
Bump fast-uri from 3.1.2 to 3.1.4 in /source/jupyterlab (#3516)
dependabot[bot] Jul 24, 2026
51f714b
Fix a bug in Compiler::new (#3509)
fedimser Jul 24, 2026
1bd096a
Support qdk_config in qsharp.init (and rename qsharp_config to qdk_co…
fedimser Jul 24, 2026
b6217a7
Revert "Bump postcss from 8.5.12 to 8.5.23 in /source/jupyterlab (#35…
swernli Jul 24, 2026
e9fe064
Update grammar file (#3508)
ScottCarda-MS Jul 24, 2026
1b4e402
npm fixes (#3519)
billti Jul 24, 2026
9bf903b
Add Q# library for Arithmetic
fedimser Jul 23, 2026
7b5ffce
add library tests to integration tests
fedimser Jul 23, 2026
71f33aa
remove tests from pyright config
fedimser Jul 23, 2026
b4a7694
update some references
fedimser Jul 23, 2026
31cc879
add trailing newlines
fedimser Jul 23, 2026
40a4788
update references
fedimser Jul 23, 2026
2a0e628
add trailing newline
fedimser Jul 23, 2026
32ac1a4
Q# format
fedimser Jul 23, 2026
c5252ec
update some comments
fedimser Jul 23, 2026
706a681
update comments
fedimser Jul 23, 2026
58c837b
add reference to registry
fedimser Jul 23, 2026
cfadaf4
flatten files
fedimser Jul 23, 2026
ed6f1b5
rename optimization config
fedimser Jul 27, 2026
e204291
Merge branch 'fedimser/arith-lib' of github.com:microsoft/qdk into fe…
fedimser Jul 27, 2026
786d576
remove old files
fedimser Jul 27, 2026
510a85d
prettier fix
fedimser Jul 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion build.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,11 @@ def run_python_tests(cwd, interpreter, pip_env):
def run_python_integration_tests(cwd, interpreter):
# don't check to see if pip succeeds. We'll see if the import works later.
# If it doesn't, we'll skip the tests.
command_args = [interpreter, "-m", "pytest"]
paths = [
cwd,
os.path.join(root_dir, "library", "arithmetic", "test"),
]
command_args = [interpreter, "-m", "pytest", *paths]
subprocess.run(command_args, check=True, text=True, cwd=cwd)


Expand Down
37 changes: 37 additions & 0 deletions library/arithmetic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Arithmetic

This library contains advanced quantum arithmetic algorithms.

Unless otherwise noted, all quantum inputs are interpreted as unsigned little-endian
integers and represented by `Qubit[]`.

The library contains the following algorithms:
* `Add.qs` - quantum-quantum in-place addition and subtraction (modulo `2^n`).
* `AddConst.qs` - quantum-classical addition (modulo `2^n`).
* `AddLookup.qs` - computes `x += table[i]` where `x`, `i` are quantum registers and
`table` is a classical table. Supports modular and non-modular addition.
* `Compare.qs` - compares two unsigned quantum integers, writing the result to an output
qubit. Supports inequality and equality.
* Modular arithmetic:
* `Modular/ModAdd.qs` - quantum-quantum in-place addition modulo classical constant.
* `Modular/ModDiv.qs` - division of two quantum numbers modulo classical constant.
This is based on the extended Euclidean algorithm, so some restrictions apply (in
particular, the divisor must be mutually prime with the modulus). It can also be used
for modular multiplication and modular inversion.
* `Modular/ModMul.qs` - modular multiplication and square.
* `Modular/ModNegate.qs` - modular negation.
* `Modular/WindowModExp.qs` - modular exponentiation (computes `t:=(t*b^x)%m` where
`t`, `x` are quantum and `b`, `m` are classical).

### Qubit-optimized and gate-optimized variants

Some algorithms (addition, constant addition, comparison) are implemented with two
different circuit variants: gate-optimized and qubit-optimized. They are functionally
equivalent, but have different resource usage.

To specify which version to use, use Q# configuration `minimize_qubits`.
For example, when creating a QDK Context using the Python API:
`qdk.Context(..., qsharp_config={"minimize_qubits": True})`.

By default, qubit-optimized versions are used.

19 changes: 19 additions & 0 deletions library/arithmetic/qsharp.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"license": "MIT",
"author": "Microsoft Quantum",
"files": [
"src/Add.qs",
"src/AddConst.qs",
"src/AddLookup.qs",
"src/ClassicalMath.qs",
"src/Compare.qs",
"src/Modular/ModAdd.qs",
"src/Modular/ModDiv.qs",
"src/Modular/ModMul.qs",
"src/Modular/ModNegate.qs",
"src/Modular/WindowModExp.qs",
"src/MultiControl.qs",
"src/ResourceEstimation.qs",
"src/Utils.qs"
]
}
34 changes: 34 additions & 0 deletions library/arithmetic/src/Add.qs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import Std.Arithmetic.RippleCarryCGIncByLE;
import Std.Arithmetic.RippleCarryTTKIncByLE;

/// This file re-exports addition algorithms from Std.Arithmetic.

/// Computes y += x (mod 2^n).
operation Add(x : Qubit[], y : Qubit[]) : Unit is Ctl + Adj {
body (...) {
if (Std.Core.ConfigValue("minimize_qubits", true)) {
RippleCarryTTKIncByLE(x, y);
} else {
RippleCarryCGIncByLE(x, y);
}
}
controlled (controls, ...) {
if (Length(controls) == 0) {
Add(x, y);
} elif (Std.Core.ConfigValue("minimize_qubits", true)) {
Controlled RippleCarryTTKIncByLE(controls, (x, y));
} else {
Controlled RippleCarryCGIncByLE(controls, (x, y));
}
}
}

/// Computes y -= x (mod 2^n).
operation Subtract(x : Qubit[], y : Qubit[]) : Unit is Ctl + Adj {
Adjoint Add(x, y);
}

export Add, Subtract;
120 changes: 120 additions & 0 deletions library/arithmetic/src/AddConst.qs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import Std.Arithmetic.RippleCarryCGAddLE;
import Std.Arithmetic.RippleCarryCGIncByLE;
import Std.Convert.BigIntAsBoolArray;
import Std.Math.TrailingZeroCountL;

import ClassicalMath.SafeMod;

/// # Summary
/// Computes `input := (input + constant) % 2^Length(input)`.
///
/// # Reference
/// - [1](https://arxiv.org/pdf/2007.07391) "Compilation of Fault-Tolerant Quantum
/// Heuristics for Combinatorial Optimization", Sanders et al. (Fig. 18).
///
/// # Resources
/// Uses n-1 auxiliary qubits and 2n-2 Toffoli gates.
///
/// # Input
/// ## constant
/// Classical constant to add.
/// ## inp
/// Target register updated in place.
operation AddConstantSanders(constant : BigInt, inp : Qubit[]) : Unit is Adj + Ctl {
body (...) {
Controlled AddConstantSanders([], (constant, inp));
}
controlled (ctrl, ...) {
let n = Length(inp);
let constant_bits = BigIntAsBoolArray(constant, n);

if n == 1 {
// Base case: single qubit addition.
if (constant_bits[0]) { Controlled X(ctrl, (inp[0])); }
} else {
use ancillas = Qubit[n - 1];

if (constant_bits[0]) { CNOT(inp[0], ancillas[0]); }

for i in 1..n - 2 {
let j = i - 1;
Controlled CNOT(ctrl, (ancillas[j], inp[i]));
within {
if (constant_bits[i]) { X(ancillas[j]); }
} apply {
AND(ancillas[j], inp[i], ancillas[i]);
}
CNOT(ancillas[j], ancillas[i]);
}

Controlled CNOT(ctrl, (ancillas[n - 2], inp[n - 1]));

for i in n - 2..-1..1 {
let j = i - 1;
CNOT(ancillas[j], ancillas[i]);
within {
if (constant_bits[i]) { X(ancillas[j]); }
} apply {
Adjoint AND(ancillas[j], inp[i], ancillas[i]);
}
}

if (constant_bits[0]) { CNOT(inp[0], ancillas[0]); }

for i in 0..n - 1 {
if (constant_bits[i]) { Controlled X(ctrl, (inp[i])); }
}
}
}
}

/// # Summary
/// Constant adder using the Gidney ripple-carry adder.
///
/// # Reference
/// - [1](https://arxiv.org/abs/1709.06648) "Halving the cost of quantum addition",
/// Craig Gidney.
operation AddConstantUsingCGAdd(constant : BigInt, input : Qubit[]) : Unit is Adj + Ctl {
body (...) {
Controlled AddConstantUsingCGAdd([], (constant, input));
}
controlled (ctrl, ...) {
use anc = Qubit[Length(input)];
within {
Controlled ApplyXorInPlaceL(ctrl, (constant, anc));
} apply {
RippleCarryCGIncByLE(anc, input);
}
}
}

/// # Summary
/// Computes `input := (input + constant) % 2^Length(input)`.
///
/// # Input
/// ## constant
/// Classical constant to add.
/// ## input
/// Target register updated in place.
operation AddConstant(constant : BigInt, input : Qubit[]) : Unit is Adj + Ctl {
body (...) {
Controlled AddConstant([], (constant, input));
}
controlled (ctrl, ...) {
let n = Length(input);
let constant = SafeMod(constant, 1L <<< n);
if (constant != 0L) {
let tz = TrailingZeroCountL(constant);
if (Std.Core.ConfigValue("minimize_qubits", true) or Length(ctrl) == 0) {
Controlled AddConstantSanders(ctrl, (constant >>> tz, input[tz...]));
} else {
Controlled AddConstantUsingCGAdd(ctrl, (constant >>> tz, input[tz...]));
}
}
}
}

export AddConstantSanders, AddConstant;
160 changes: 160 additions & 0 deletions library/arithmetic/src/AddLookup.qs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import Std.Arithmetic.RippleCarryCGIncByLE;
import Std.Arrays.Mapped;
import Std.Convert.BigIntAsBoolArray;
import Std.Diagnostics.Fact;
import Std.ResourceEstimation.IsResourceEstimating;
import Std.ResourceEstimation.RepeatEstimates;
import Std.TableLookup.Select;

import ClassicalMath.SafeMod;
import Modular.ModAdd.ModAdd;

/// References:
/// - Thomas Haener, Vadym Kliuchnikov, Martin Roetteler, Mathias Soeken,
/// "Space-time optimized table lookup", 2022.
/// https://arxiv.org/abs/2211.01133
/// - Dominic W. Berry, Craig Gidney, Mario Motta, Jarrod R. McClean, Ryan Babbush,
/// "Qubitization of Arbitrary Basis Quantum Chemistry Leveraging Sparsity and
/// Low Rank Factorization" (Appendix C), 2019.
/// https://arxiv.org/abs/1902.02134

function _CombineTables(tables : BigInt[][], num_bits : Int, modulus : BigInt) : BigInt[] {
mutable combined = Mapped(x -> SafeMod(x, modulus), tables[0]);
for i in 1..Length(tables) - 1 {
let shift = i * num_bits;
for j in 0..Length(combined) - 1 {
let shifted_value = SafeMod(tables[i][j], modulus) <<< shift;
set combined w/= j <- combined[j] ||| shifted_value;
}
}
return combined;
}

function DataRowsAsBits(data : BigInt[], num_bits : Int) : Bool[][] {
let wrap = 1L <<< num_bits;
return Mapped(x -> BigIntAsBoolArray(SafeMod(x, wrap), num_bits), data);
}

// Requires 0 <= data[i] < 2^Length(address).
operation _Lookup(data : BigInt[], address : Qubit[], target : Qubit[]) : Unit is Adj {
let address_size = Length(address);
let can_use_formula = (address_size >= 3) and (Length(data) == 2^address_size);

if (can_use_formula and IsResourceEstimating()) {
// TODO: make Lookup a primitive instruction in resource estimator.
let num_ancilla = address_size - 1;
use q_anc = Qubit[num_ancilla];
within {
RepeatEstimates(2 ^^^ address_size - 2);
} apply {
AND(address[0], address[1], q_anc[0]);
Adjoint AND(address[0], address[1], q_anc[0]);
}
} else {
let data_bits = DataRowsAsBits(data, Length(target));
Select(data_bits, address, target);
}
}

/// # Summary
/// Computes `q_result := (q_result + data[q_address]) % 2^n`.
/// Requires `0 <= data[i] < 2^n`.
///
/// # Input
/// ## q_address
/// Register encoding the table index `q_address`.
/// ## q_result
/// Target register updated in place.
/// ## data
/// Lookup table of values to add.
operation AddLookup(
q_address : Qubit[],
q_result : Qubit[],
data : BigInt[]
) : Unit {
use q_select_output = Qubit[Length(q_result)];

within {
_Lookup(data, q_address, q_select_output);
} apply {
RippleCarryCGIncByLE(q_select_output, q_result);
}
}

/// # Summary
/// Computes `q_result := (q_result + data[q_address]) % modulus`.
///
/// # Input
/// ## q_address
/// Register encoding the table index `q_address`.
/// ## q_result
/// Target register updated in place.
/// ## data
/// Lookup table of values to add.
/// ## modulus
/// Modulus used for modular addition.
operation ModAddLookup(
q_address : Qubit[],
q_result : Qubit[],
data : BigInt[],
modulus : BigInt
) : Unit is Adj {
use q_select_output = Qubit[Length(q_result)];
let data_modded = Mapped(x -> SafeMod(x, modulus), data);
within {
_Lookup(data_modded, q_address, q_select_output);
} apply {
ModAdd(q_select_output, q_result, modulus);
}
}

/// # Summary
/// Computes `q_result[i] := (q_result[i] + tables[i][q_address]) % modulus` for each `i`.
///
/// # Input
/// ## q_address
/// Register encoding the table index `q_address`.
/// ## q_result
/// Array of target registers, each updated in place.
/// ## tables
/// Array of lookup tables matched one-to-one with `q_result`.
/// ## modulus
/// Modulus used for each modular addition.
operation ParallelModAddLookup(
q_address : Qubit[],
q_result : Qubit[][],
tables : BigInt[][],
modulus : BigInt
) : Unit {
let num_tables = Length(tables);
Fact(num_tables == Length(q_result), "Size mismatch.");
Fact(num_tables > 0, "Must provide at least one table.");
let result_size = Length(q_result[0]);
let table_length = Length(tables[0]);
for i in 0..num_tables - 1 {
Fact(Length(q_result[i]) == result_size, "All target registers must have equal size.");
Fact(Length(tables[i]) == table_length, "All tables must have the same length.");
}

if (Std.Core.ConfigValue("minimize_qubits", true)) {
for i in 0..num_tables - 1 {
ModAddLookup(q_address, q_result[i], tables[i], modulus);
}
} else {
use q_select_output = Qubit[num_tables * result_size];
let tables_combined = _CombineTables(tables, result_size, modulus);
within {
_Lookup(tables_combined, q_address, q_select_output);
} apply {
for i in 0..num_tables - 1 {
let q_temp = q_select_output[i * result_size..(i + 1) * result_size - 1];
ModAdd(q_temp, q_result[i], modulus);
}
}
}
}

export AddLookup, ModAddLookup, ParallelModAddLookup;
Loading
Loading