---
id: 575
lang: en
translation_of: index.md
source_sha256: f7e56d0fa50d52d70c7961b04154fa0fc0857e945aec6a1d3c1eec4c7ee73425
title: "Elementary Number Theory"
description: "We write gcd(a,b) for the greatest common divisor of a and b."
tags: ["OI","Math","Number Theory"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Title 初级数论 (literally “beginner-level number theory”) rendered as “Elementary Number Theory”."
  - "更相减损术 rendered as “the method of successive subtraction”; the author's later 更相损减数 (sic) is read as the same term."
  - "N内有N/p个p的质数 rendered literally as “within N there are N/p primes of p” (the author evidently means multiples of p); the wording was not corrected."
  - "推到成 (sic) read as 推导成, “derived into”; 方成 (sic) read as 方程, “equation”."
  - "Two display formulas have Chinese written directly in the TeX without \\text{} (质数p|N under the product, and the three cases of the Legendre symbol definition), so they are kept unchanged (math must stay identical); they read “prime p|N”, “a is a quadratic residue of p” and “a is not a quadratic residue of p”."
  - "Problem name 古代猪文 rendered as “Ancient Pig Script”; 可爱的质数 as “Cute Primes”."
  - "爆掉 (a number overflowing) rendered as “blow up”, with a new chip."
---

## Contents

- GCD & LCM
- Euler's Totient Function
- The BSGS Algorithm
- CRT (Chinese Remainder Theorem)
- Primitive Roots

<!--more-->

## GCD & LCM

### GCD

We write $gcd(a,b)$ for the greatest common divisor of $a$ and $b$. $gcd$ satisfies the following properties:

- $m*gcd(a,b)=gcd(ma,mb)$
- $gcd(\frac{a}{c},\frac{b}{c})=\frac{gcd(a,b)}{c}$
- $gcd(a,m)*gcd(b,m)=gcd(ab,m)$

#### The Method of Successive Subtraction

$gcd(a,b)=gcd(b,a-b)=gcd(a,a-b)$

### LCM

We write $lcm(a,b)$ for the least common multiple of $a$ and $b$. $lcm$ can be converted into $gcd$, so readers can try deriving the properties of $lcm$ themselves:

$$
a*b=gcd(a,b)*lcm(a,b)
$$

## Euler's Totient Function

Euler's totient function is denoted $\varphi(x)$, and it means the number of integers in $[1,n]$ that are coprime to $n$. In general, the expression for Euler's totient function is as follows:

$$
\varphi(N) = N*\frac{p_1-1}{p_1}*\frac{p_2-1}{p_2}*\frac{p_3-1}{p_3} \dots = N*\prod_{质数p|N}(1-\frac{1}{p})
$$

Next comes the proof.

**Proof** Let $p,q$ be prime factors of $N$; then within $N$ there are $\frac{N}{p}$ primes of $p$, and $\frac{N}{q}$ primes of $q$. If we remove them, the common factor $p*q$ gets removed one extra time, so the complete expression after removal is:

$$
\begin{gathered} N- \frac{N}{p} - \frac{N}{q} + \frac{N}{pq} \\ N*( 1 - \frac{1}{pq} - \frac{1}{p} - \frac{1}{q} ) \\ N*(1 - \frac{1}{p})(1 - \frac{1}{q}) \end{gathered}
$$

Hence proved. In programming, just compute it directly while factorizing into primes.

### Properties of Euler's Totient Function

- The sum of the numbers in $[1,N]$ that are coprime to $N$ is $N*\frac{\varphi(N)}{2}$.\
  **Proof** By the method of successive subtraction, let $x$ be a number coprime to $N$, i.e. $gcd(x,N)=1$; then also $gcd(N - x,N)=1$. In other words, coprime numbers come in pairs, so the average of the numbers coprime to $N$ is $\frac{N}{2}$, which gives this property.
- If $a,b$ are coprime, then $\varphi(ab)=\varphi(a)\varphi(b)$
- $\sum_{i|N}\varphi(i)=N$

### Euler's Theorem

If $a$ and $n$ are coprime, then $a^{\varphi(n)} \equiv 1 (\mod n)$; if $a$ and $n$ are coprime, then $a^b \equiv a^{b \mod \varphi(n)}$.

## The BSGS Algorithm

The full name of the BSGS algorithm is the “**baby-step giant-step**” algorithm, and it is used to solve equations of the form $a^x \equiv b \; (\mod \; p)$. We can break this equation apart: let $m=\lfloor \sqrt{p} \rfloor$, then $x=im-j, i \in [1, m], j \in [0, m]$. This way, our equation can be derived into:

$$
\begin{gathered} a^x \equiv b \; (\mod \; p) \\ a^{im-j} \equiv b \; (\mod \; p) \\ a^{im} \equiv a^{j} b \; (\mod \; p) \end{gathered}
$$

We've derived it! At this point, we only need a hash table to handle the values of the second half: insert entries with key $a^{j} b$ and value $j$ into the hash table, then enumerate the first half, and as soon as the hash table has a matching entry, our answer:

$$
\begin{gathered} x = im-j \\ x = im - hashTable[im] \end{gathered}
$$

is easy to obtain. The code is as follows:

```cpp
hashTable.clear();
ll m = ceil(sqrt(p));
for (int j = 0, x = 1; j <= m; j++, x = x * a % p)
    hashTable[x * b % p] = j;
ll unit = quick_power(a, m);
for (int i = 1, x = unit; i <= m; i++, x = x * unit % p)
    if (hashTable.count(x))
    {
        ans = i * m + hashTable[x];
        break;
    }
```

[Template problem](https://www.luogu.org/problemnew/show/P3846); [P3846: [TJOI2007] Cute Primes — Solution](../570-p3846-tjoi2007-cute-prime/index.en.html)

## CRT (Chinese Remainder Theorem)

This algorithm is mainly used to solve systems of congruences, and the conclusion is very simple. Our equations look like this:

$$
\begin{cases} x \equiv a_1 \; (\mod \; p_1) \\  x \equiv a_2 \; (\mod \; p_2) \\  x \equiv a_3 \; (\mod \; p_3) \\  \dots \end{cases}
$$

### Algorithm Steps

1. Compute the product of these moduli, denoted $b=\prod^n_{i=1} p_i$.
2. Iterate over each congruence $i$
   1. Compute $m=\frac{b}{p_i}$.
   2. Compute $m^{-1}\; (\mod \; p_i)$
   3. Compute $c_i = \sum m \times m^{-1}$
3. The answer is $ans=\sum a_i*c_i \; (\mod \; m)$.

### Example: [[SDOI2010] Ancient Pig Script](https://www.luogu.org/problemnew/show/P2480)

The answer to this problem is very obvious: $ans = G^{\sum_{N|k}C_N^{\frac{k}{N}}} \mod \; P$. Since $P$ is a prime, we can use Fermat's theorem to simplify the expression to:

$$
ans = G^{(\sum_{N|k} C_N^{\frac{k}{N} })mod\;(P-1)} \mod \; P
$$

We find that $P-1$ factors as $2 \times 3 \times 4679 \times 35617$. Then we can simplify with Lucas's theorem, and then just set up the congruences (computing the answer directly would <span class="slang" data-zh="爆掉" data-gloss="bào diào, “explode”. OI slang for a number overflowing its integer type.">blow up</span>, so we solve it with equations).

```cpp
// P2480.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 500010;
const ll genP = 999911659;
ll n, g, level[MAX_N], mods[5] = {0, 2, 3, 4679, 35617}, a[5], ans;
ll quick_power(ll base, ll tim, ll p)
{
    ll tmp = 1;
    while (tim)
    {
        if (tim & 1)
            tmp = tmp * base % p;
        base = base * base % p;
        tim >>= 1;
    }
    return tmp;
}
void init(ll p)
{
    level[0] = 1;
    for (int i = 1; i <= p; i++)
        level[i] = level[i - 1] * i % p;
}
ll combine(ll n, ll m, ll p)
{
    if (m > n)
        return 0;
    return level[n] * quick_power(level[n - m], p - 2, p) * quick_power(level[m], p - 2, p) % p;
}
ll lucas(ll n, ll m, ll p)
{
    if (n < m)
        return 0;
    if (m == 0)
        return 1;
    return lucas(n / p, m / p, p) * combine(n % p, m % p, p) % p;
}
void crt()
{
    int tmp = genP - 1;
    for (int i = 1; i <= 4; i++)
        ans = (ans + a[i] * (tmp / mods[i]) % tmp * quick_power(tmp / mods[i], mods[i] - 2, mods[i])) % tmp;
}
int main()
{
    scanf("%lld%lld", &n, &g);
    if (g % genP == 0)
        printf("0"), exit(0);
    for (int k = 1; k <= 4; k++)
    {
        init(mods[k]);
        for (int i = 1; i * i <= n; i++)
            if (n % i == 0)
            {
                a[k] = (a[k] + lucas(n, i, mods[k])) % mods[k];
                if (i * i != n)
                    a[k] = (a[k] + lucas(n, n / i, mods[k])) % mods[k];
            }
    }
    crt();
    printf("%lld", quick_power(g, ans, genP));
    return 0;
}
```

## Quadratic Residues

### Problem Description

Given an expression $x^2 \equiv n \; (\mod \; p)$, find the value of $x$. Here, if $x$ has a solution, $n$ is called a quadratic residue of $p$.

### The Legendre Symbol

First, we need to determine whether this equation has a root. Here we introduce the Legendre symbol to make that judgment. We define:

$$
\left( \frac{a}{p} \right) = \begin{cases} 1, a 为 p 的二次剩余 \\ -1, a 不是 p 的二次剩余 \\ 0, a \equiv 0 \; (\mod \; p) \end{cases}
$$

How do we decide this by computation? Next we introduce Euler's criterion: for the Legendre symbol, we have

$$
\left( \frac{a}{p} \right) = a^{\frac{p-1}{2}} \; (\mod \; p)
$$

**Proof:** Consider the following cases

- When $\left( \frac{a}{p} \right) \equiv 1 \; (\mod \; p)$, the expression becomes $\sqrt{ a^{p-1} } \equiv 1 \; (\mod \; p)$, and by Fermat's little theorem, this is proved.
- When $\left( \frac{a}{p} \right) \equiv -1 \; (\mod \; p)$, there is no quadratic residue. This simplifies to $a^{\frac{p-1}{2}} \equiv -1 \; (\mod \; p)$; when no quadratic residue exists, there exist $ij \equiv a \; (\mod \; p), i != j, i, j \in [1, p-1]$. We know that in number theory there are $\frac{p-1}{2}$ such pairs $(i,j)$ in total, so the Legendre expression can be further transformed into $(p-1)! \equiv -1 \; (\mod \; p)$, and by Wilson's theorem, this is proved.

### Cipolla's Algorithm

Having covered the <span class="slang" data-zh="玄学" data-gloss="xuánxué, “metaphysics”. Something that seems to run on luck or mysterious rules rather than logic.">black-magic</span> criterion above, let's bring in Cipolla's algorithm, which can compute quadratic residues. First, as with any quadratic equation, we need to check for roots first; just compute it with the criterion above. After that, we randomly enumerate a $c$ such that the Legendre symbol of $c^2-n$ is $-1$, and let $i=\sqrt{c^2-n}$, forcibly taking the square root (somewhat like imaginary numbers). Then the following lemma gives the answer.

$$
x \equiv (n+i)^{\frac{p+1}{2}} \; (\mod \; p)
$$

**Proof:**

$$
\begin{gathered} x^2 \equiv (n+i)^{p+1} \\ \equiv (n+i)(n+i)^p \\ \equiv (n+i)(n^p+i^p) \\ \equiv (n+i)(n^p + (c^2-n)^{\frac{p-1}{2}} * i) \\ \equiv (n+i)(n^p - i) \\ \equiv (n+i)(n-i) \\ \equiv n \end{gathered}
$$

There are some shortcut steps in the proof, which I'll explain and prove here:

- $(a+b)^n \equiv \sum^n_{i=0} C_n^i a^ib^{n-i} \equiv a^n+b^n \; (\mod \; p)$; the middle terms vanish because the binomial coefficient $C_n^i$ supplies the factor $n$.
- By Fermat's little theorem, $a^p \equiv a \; (\mod \; p)$.

## Multiplicative Functions

Definition of a multiplicative function: if a function $f(x)$ is a multiplicative function, then it satisfies $f(a)f(b)=f(ab),gcd(a,b)=1$. Euler's totient function is one kind of multiplicative function; next we describe their properties.

Properties of multiplicative functions:

- Given $n=\prod^{m}_{i=1}p_i^{c_i}$, then $f(n)=\prod_{i=1}^{m}f(p_i^{c_i})$

## Primitive Roots

I'll only cover some fairly basic things here; if I learn other related things later, I'll come back and add them.

Working modulo a prime $p$, let $g$ be a primitive root of $p$; it has the following property:

- Any powers of $g$ can form a complete residue system of $p$; that is, $\{ g^k|k \in N \}$ can be regarded as $[0,p-1]$

So when solving problems, if we meet a problem where $a^b \equiv c (\mod \; p)$ and $b,c,p$ are known and we need to find $a$, we can write this expression as $g^{tb} \equiv g^s(\mod\; p)$ and just turn it into solving the congruence $tb \equiv s (\mod \; p-1)$.
