---
title: "Modular arithmetic"
description: "Use BigInt modular arithmetic, square roots and congruences from the curves package root"
canonical_url: "https://curves.agntn.dev/math/field"
---
# Modular arithmetic

> Use BigInt modular arithmetic, square roots and congruences from the curves package root

## BigInt modular arithmetic

Import modular arithmetic directly from `@agntn/curves`. These are the functions the curve code uses, with input checks at the root.

```ts
import { invert, jacobi, mod, power, squareRoot, squareRootMod } from "@agntn/curves";

mod(-7n, 5n); // 3n
power(2n, 10n, { modulus: 1000n }); // 24n
invert(3n, 10n); // 7n
squareRoot(10n ** 30n + 1n); // 1000000000000000n
```

Every numeric argument must be a `bigint`. Pass a `Number` and you get a `TypeError`. Why insist? A `Number` above 2^53 can already have lost digits. A silent wrong answer is worse than a refusal.

These functions are not constant time. Don't use them with secrets.

## Modular reduction and exponentiation

`mod(value, modulus)` returns a value from zero to `modulus - 1n`. Negative values work too. The modulus must be at least `1n`. A smaller modulus throws a `RangeError`.

`power(base, exponent, { modulus })` takes its modulus in an options object. The exponent must be zero or more. A negative exponent throws a `RangeError`. Anything to the zeroth power mod `1n` is `0n`.

Pass the modulus bare? You get a `TypeError` that shows the right shape.

```ts
power(3n, 2n ** 61n - 2n, { modulus: 2n ** 61n - 1n }); // 1n, Fermat says hi
```

## Modular inverse

`invert(value, modulus)` works with composite moduli too. The value and modulus must have gcd 1. Otherwise, it throws a `RangeError` naming the shared factor. For modulus `1n`, the result is `0n`.

## Integer square root

`squareRoot(value)` returns the integer square root, rounded down. It accepts values of any size. A negative value throws a `RangeError`.

## Jacobi symbol

`jacobi(value, modulus)` returns the number `1`, `-1` or `0`. The result is `0` when the arguments share a factor. The modulus must be odd and at least `1n`. Other moduli throw a `RangeError`.

Does `1` mean a square exists? Not for every composite modulus. Jacobi says `1` for `2n` mod `15n`, but `2n` is no square there. A confident answer to a different question.

## Modular square roots

`squareRootMod(value, prime)` returns the smaller root. If no square root exists, it returns `undefined`. The prime `2n` works too. Tonelli-Shanks handles primes beyond those congruent to 3 mod 4.

```ts
squareRootMod(2n, 7n); // 3n
squareRootMod(3n, 7n); // undefined
squareRootMod(1n, 2n); // 1n
jacobi(3n, 7n); // -1
jacobi(2n, 15n); // 1, and 2 is still no square mod 15
```

The function checks primality before finding a root. A modulus that isn't prime throws a `RangeError`. That's better than a loop that never ends.

## Chinese remainder theorem

Do the moduli have to be coprime? No. Their residues just have to agree mod the gcd. Otherwise `crt` returns `undefined`. No coprime juggling needed.

```ts
import { crt } from "@agntn/curves";

crt([
  { residue: 3n, modulus: 10n },
  { residue: 7n, modulus: 12n },
]); // { residue: 43n, modulus: 60n }
crt([
  { residue: 1n, modulus: 4n },
  { residue: 2n, modulus: 6n },
]); // undefined, odd and even won't agree mod 2
crt([
  { residue: 2n, modulus: 3n },
  { residue: 3n, modulus: 5n },
  { residue: 2n, modulus: 7n },
]); // { residue: 23n, modulus: 105n }
```

That last one is the puzzle from the Sunzi Suanjing. Still 23.

Pass any iterable of `{ residue, modulus }` objects, a generator included. Residues may be negative. Every modulus must be at least `1n`. The answer comes mod their lcm, with a residue from `0n` up to one less. Feed it back into `crt` to add more congruences.

An empty iterable gives `{ residue: 0n, modulus: 1n }`, every integer. A generator is read once. All inputs are checked before solving, even after a disagreement. A `[residue, modulus]` pair throws a `TypeError`.

## Linear congruences

`linearCongruence(coefficient, value, { modulus })` solves `coefficient * x = value` mod a modulus. The modulus goes in an options object, like `power`.

```ts
import { linearCongruence } from "@agntn/curves";

linearCongruence(6n, 4n, { modulus: 10n }); // { residue: 4n, modulus: 5n, count: 2n }
linearCongruence(2n ** 64n, 0n, { modulus: 2n ** 65n }); // { residue: 0n, modulus: 2n, count: 18446744073709551616n }
```

That first answer means `4n` or `9n` mod `10n`. You get one class mod the modulus divided by the gcd. Its `count` is the gcd, not a list of classes. Want 2^64 classes printed one by one? Neither do we.

If the gcd doesn't divide the value, the result is `undefined`. With coefficient `0n`, a value divisible by the modulus gives residue `0n`, modulus `1n` and count equal to the modulus. Everything stays BigInt. Neither function is constant time.

## Primality testing

`isPrime(value)` is also available from the package root. Primality checks use Baillie-PSW. It combines Miller-Rabin tests on small prime bases with a strong Lucas test. No known composite passes it. But nobody has proved that none does.

## Modular arithmetic errors

Wrong inputs fail with a useful message.

```text
invert(4n, 10n)                  // No inverse exists mod 10: the value shares the factor 2 with it
squareRootMod(2n, 15n)           // The modulus must be a prime
squareRoot(-1n)                  // The value must be 0 or more
power(2n, 3n, 7n)                // power takes the modulus as { modulus }
crt([[3n, 10n]])                 // crt takes each congruence as { residue, modulus }
linearCongruence(6n, 4n, 10n)    // linearCongruence takes the modulus as { modulus }
```

The first three throw `RangeError`. The rest throw `TypeError`.


## Sitemap

See the full [sitemap](https://curves.agntn.dev/sitemap.md) for all pages.
