# Modular Reduction

## Introduction

To calculate modular addition, $$(A+B) \mod q$$, we can simply&#x20;use a piecewise function:

$$
(A + B) \mod q = \begin{cases}
A + B &\text{if }A + B < q \\
A + B − q &\text{if }A + B ≥ q \end{cases}
$$

While modular adder is simple and easy to implement,&#x20;modular multipliers are trickier. The standard algorithm for&#x20;modular multiplication uses [trial division](https://en.wikipedia.org/wiki/Trial_division#:~:text=Trial%20division%20is%20the%20most,the%20square%20root%20of%20n.), which is inefficient, not scalable, and difficult to implement in hardware&#x20;architecture. The most popular workaround uses&#x20;[Barrett](https://app.gitbook.com/o/vlMwaGV8Ukn8S4gDaGYp/s/rwz1ZAZJtK5FHz4Y1esA/~/changes/55/primitives/modular-multiplication/barrett-reduction) or [Montgomery](https://app.gitbook.com/o/vlMwaGV8Ukn8S4gDaGYp/s/rwz1ZAZJtK5FHz4Y1esA/~/changes/55/primitives/modular-multiplication/montgomery-reduction) reduction based multiplication algorithm. There is also some specialized multiplication algorithms like Karatsuba-Barrett Algorithm etc.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://fractalyze.gitbook.io/intro/primitives/modular-arithmetic/modular-reduction.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
