Fermat's Little Theorem & Euler's Theorem

This page discusses Fermat's little theorem, Euler's theorem, and their extensions. These theorems solve the problem of computing powers with arbitrarily large exponents under arbitrary moduli.

Fermat's little theorem

Fermat's little theorem is one of the most fundamental theorems in number theory. It is also the theoretical basis of the Fermat primality test.

Fermat's little theorem

Let pp be a prime. For every integer aa with p∤ap\nmid a, we have ap−1≡1(modp)a^{p-1}\equiv 1\pmod p.

Theorem

Let pp be a prime. For every integer aa, we have ap≡a(modp)a^{p}\equiv a\pmod p.

These two congruences are equivalent when p∤ap\nmid a; when p∣ap\mid a, ap≡0≡a(modp)a^p\equiv 0\equiv a\pmod p holds trivially. Therefore, the two statements are equivalent. Both are often called Fermat's little theorem.

Proof 1

Let pp be prime and let p∤ap\nmid a. We first prove that for i=1,2,⋯ ,p−1i=1,2,\cdots,p-1, the remainders ia mod pia \bmod p are all distinct. Suppose otherwise. If there were 1≤i<j<p1\le i < j < p such that

ia mod p=ja mod p.  ⟺  (j−i)a≡0.(modp)ia \bmod p = ja \bmod p. \iff (j-i)a\equiv 0.\pmod p

But neither (j−i)(j-i) nor aa is a multiple of pp, which is a contradiction.

In other words, these remainders form a permutation of {1,2,⋯ ,p−1}\{1,2,\cdots,p-1\}. Hence,

∏i=1p−1i=∏i=1p−1(ia mod p)≡∏i=1p−1ia=ap−1∏i=1p−1i.(modp)\prod_{i=1}^{p-1}i = \prod_{i=1}^{p-1}(ia\bmod p) \equiv \prod_{i=1}^{p-1}ia = a^{p-1}\prod_{i=1}^{p-1}i.\pmod p

This implies

(ap−1−1)∏i=1p−1i≡0.(modp)(a^{p-1}-1)\prod_{i=1}^{p-1}i \equiv 0. \pmod{p}

In other words, the left-hand side is a multiple of pp. However, none of i=1,2,⋯ ,p−1i=1,2,\cdots, p-1 is a multiple of pp, so the only possibility is p∣(ap−1−1)p\mid (a^{p-1}-1); that is, Fermat's little theorem holds.

Proof 2

The second formulation of Fermat's little theorem holds for every a∈Na\in\mathbf N, so we can use mathematical induction. The case of negative integers is easily reduced to that of nonnegative integers.

The base case is 0p≡0(modp)0^p\equiv 0\pmod p, which is obvious. Assume that the statement holds for a∈Na\in\mathbf N; we need to prove that it also holds for a+1a+1. By the binomial theorem,

(a+1)p=ap+(p1)ap−1+(p2)ap−2+⋯+(pp−1)a+1.(a+1)^p=a^p+\binom{p}{1}a^{p-1}+\binom{p}{2}a^{p-2}+\cdots +\binom{p}{p-1}a+1.

Except for the first and last terms, in the expression (pk)=p!k!(p−k)!\dbinom{p}{k} = \dfrac{p!}{k!(p-k)!} for a binomial coefficient, pp divides the numerator but does not divide the denominator. Thus, for k≠0,pk\neq 0,p, these coefficients are multiples of pp. Therefore,

(a+1)p≡ap+1≡a+1.(modp)(a+1)^p \equiv a^p + 1\equiv a + 1. \pmod{p}

The second congruence uses the induction hypothesis. Thus, by mathematical induction, Fermat's little theorem holds.

The converse of Fermat's little theorem is false. Even if for every nn coprime to aa we have an−1≡1(modn)a^{n-1}\equiv 1\pmod n, nn need not be prime. See the Fermat primality test section for related discussion.

Euler's theorem

Euler's theorem generalizes Fermat's little theorem to arbitrary moduli, while still requiring the base and modulus to be coprime.

Euler's theorem

For an integer m>0m>0 and an integer aa with gcd⁡(a,m)=1\gcd(a,m)=1, we have aφ(m)≡1(modm)a^{\varphi(m)}\equiv 1\pmod{m}, where φ(⋅)\varphi(\cdot) is the Euler totient function.

Proof

As in the proof of Fermat's little theorem, take a sequence of numbers coprime to mm and operate on it. Consider the set

R={r∈N:0<r<m, gcd⁡(r,m)=1}.R = \{r\in\mathbf N : 0 < r < m,~\gcd(r,m)=1\}.

This is a reduced residue system modulo mm. By the definition of the Euler totient function, ∣R∣=φ(m)|R|=\varphi(m). As above, multiplying its elements by aa merely permutes the set:

R={ar mod m:r∈R}.R = \{ar\bmod m: r\in R\}.

Indeed, it is easy to verify that gcd⁡(ar,m)=1\gcd(ar,m)=1, and that distinct r1,r2∈Rr_1,r_2\in R give distinct values of ar1 mod mar_1\bmod m and ar2 mod mar_2\bmod m. Hence,

∏r∈Rr≡∏r∈Rar=aφ(m)∏r∈Rr.(modm)\prod_{r\in R}r \equiv \prod_{r\in R}ar = a^{\varphi(m)}\prod_{r\in R}r. \pmod{m}

Repeating the preceding argument and canceling ∏r∈Rr\prod_{r\in R}r gives aφ(m)≡1(modm)a^{\varphi(m)}\equiv 1\pmod m.

For a prime pp, φ(p)=p−1\varphi(p)=p-1, so Fermat's little theorem is a special case of Euler's theorem. In general, the exponent φ(m)\varphi(m) in Euler's theorem is not the smallest exponent for which the congruence holds. It can be improved to λ(m)\lambda(m), where λ(⋅)\lambda(\cdot) is the Carmichael function. For the algebraic background, see the multiplicative group of integer residue classes.

Extended Euler's theorem

Extended Euler's theorem1 further generalizes the result to the case where the base and modulus are not coprime. It completely solves the problem of computing powers of arbitrary bases under arbitrary moduli by reducing them to exponents smaller than 2φ(m)2\varphi(m), which can then be computed in O(log⁡φ(m))O(\log\varphi(m)) time using binary exponentiation.

Extended Euler's theorem

For every positive integer mm, integer aa, and nonnegative integer kk,

ak≡{ak mod φ(m),gcd⁡(a,m)=1,ak,gcd⁡(a,m)≠1,k<φ(m),a(k mod φ(m))+φ(m),gcd⁡(a,m)≠1,k≥φ(m).(modm)a^k \equiv \begin{cases} a^{k \bmod \varphi(m)}, &\gcd(a,m) = 1, \\ a^k, &\gcd(a,m)\ne 1, k < \varphi(m), \\ a^{(k \bmod \varphi(m)) + \varphi(m)}, &\gcd(a,m)\ne 1, k \ge \varphi(m). \end{cases} \pmod m

The second case says that if k<φ(m)k < \varphi(m), no further exponent reduction is needed and binary exponentiation can be applied directly. The main difference between the third and first cases is whether an additional φ(m)\varphi(m) must be added after reducing the exponent modulo the period. Of course, it is also correct to merge the first case into the second and third cases.

Intuitive understanding

Before proving the theorem rigorously, we can first develop an intuitive understanding of its meaning.

fermat1
fermat1

Consider how the remainder ak mod ma^k\bmod m changes as bb increases. The remainder always lies in [0,m)[0,m), while there are infinitely many values of kk. Regard ak mod m↦ak+1 mod ma^k\bmod m \mapsto a^{k+1}\bmod m as a directed edge between remainder nodes. A cycle like the one shown in the figure must therefore arise.

Extended Euler's theorem says that these cycles may be pure cycles (the first case) or lasso-shaped cycles (the second and third cases). In a pure cycle, no node has two predecessors, whereas such nodes appear in a lasso-shaped cycle. Thus, in general, it is enough to determine the cycle length and the length before entering the cycle to reduce the exponent using this property.

Rigorous proof

This section gives a rigorous proof of extended Euler's theorem.

Proof

First, we show that there exists k0∈Nk_0\in\mathbf N such that the integer aa is coprime to m′:=mgcd⁡(ak0,m)m':=\dfrac{m}{\gcd(a^{k_0},m)}. Let νp(n)\nu_p(n) denote, for an integer nn, the exponent of the prime pp in its prime factorization. We may take

k0=max⁡{⌈νp(m)νp(a)⌉:νp(a)>0}.k_0 = \max\left\{\left\lceil\dfrac{\nu_p(m)}{\nu_p(a)}\right\rceil : \nu_p(a)>0\right\}.

Every power of a prime common to mm and aa is then already contained in ak0a^{k_0}, so aa is coprime to the remaining factor of mm, namely m′=mgcd⁡(ak0,m)m'=\dfrac{m}{\gcd(a^{k_0},m)}.

Now, for k≥k0k\ge k_0, consider the congruence

b≡ak.(modm)b\equiv a^k. \pmod m

Since gcd⁡(ak0,m)=gcd⁡(ak,m)∣b\gcd(a^{k_0},m)=\gcd(a^k,m)\mid b, dividing both sides of the congruence (including the modulus) by gcd⁡(ak0,m)\gcd(a^{k_0},m) gives

bgcd⁡(ak0,m)=ak0gcd⁡(ak0,m)⋅ak−k0.(modm′)\dfrac{b}{\gcd(a^{k_0},m)} = \dfrac{a^{k_0}}{\gcd(a^{k_0},m)}\cdot a^{k-k_0}. \pmod{m'}

Since aa is coprime to the modulus m′m', Euler's theorem can be applied directly, giving

bgcd⁡(ak0,m)≡ak0gcd⁡(ak0,m)⋅a(k−k0) mod φ(m′).(modm′)\dfrac{b}{\gcd(a^{k_0},m)} \equiv \dfrac{a^{k_0}}{\gcd(a^{k_0},m)}\cdot a^{(k-k_0)\bmod\varphi(m')}. \pmod{m'}

Multiplying back by gcd⁡(ak0,m)\gcd(a^{k_0},m) yields

b≡ak0⋅a(k−k0) mod φ(m′)=ak0+(k−k0) mod φ(m′).(modm)b \equiv a^{k_0}\cdot a^{(k-k_0)\bmod\varphi(m')} = a^{k_0 + (k-k_0)\bmod\varphi(m')}. \pmod{m}

This is the form of extended Euler's theorem. The formula shows that the cycle length is φ(m′)\varphi(m'), while the length before entering the cycle is k0k_0.

The parameters obtained here are tighter than those in the statement of extended Euler's theorem, but are relatively difficult to compute. We can show that they can be relaxed to the parameters in that theorem. First, from the formula for the Euler totient function, since m′∣mm'\mid m, we have φ(m′)∣φ(m)\varphi(m')\mid\varphi(m). In other words, φ(m)\varphi(m) is also a cycle length. Second, k0k_0 can be relaxed to φ(m)\varphi(m). For every m∈N+m\in\mathbf N_+ and every p∣mp\mid m,

φ(m)≥φ(pνp(m))=(p−1)pνp(m)−1≥pνp(m)−1=(1+(p−1))νp(m)−1≥1+(p−1)(νp(m)−1)≥1+(νp(m)−1)=νp(m).\begin{aligned} \varphi(m) &\ge \varphi(p^{\nu_p(m)}) = (p-1)p^{\nu_p(m)-1} \ge p^{\nu_p(m)-1} \\ &= (1+(p-1))^{\nu_p(m)-1} \ge 1 + (p-1)(\nu_p(m)-1) \\ &\ge 1 + (\nu_p(m)-1) = \nu_p(m). \end{aligned}

The inequality in the second line follows from the binomial expansion, retaining only the constant and linear terms. Therefore,

k0≤max⁡{νp(m):p∈P}≤φ(m).k_0 \le \max\{\nu_p(m):p\in\mathbf P\}\le \varphi(m).

This completes the proof of the stated result.

Example

This section demonstrates a classic application of extended Euler's theorem: computing a power tower under an arbitrary modulus. A power tower is an expression of the form A↑(B↑(C↑(D↑⋯ )))A\uparrow(B\uparrow(C\uparrow(D\uparrow\cdots))), where ↑\uparrow is Knuth's arrow notation and A,B,C,D,⋯A,B,C,D,\cdots are a sequence of nonnegative integers.

Library Checker - Tetration Mod

There are TT test cases. In each test case, given A,B,MA,B,M, compute (A↑↑B) mod M(A\uparrow\uparrow B)\bmod M. Here, A↑↑BA\uparrow\uparrow B denotes a power tower consisting of BB copies of AA. Formally,

A↑↑B={1,B=0,A↑(A↑↑(B−1)),B>0.A \uparrow\uparrow B = \begin{cases} 1 , & B = 0,\\ A\uparrow(A\uparrow\uparrow(B-1)), & B > 0. \end{cases}

We define 00=10^0=1.

Solution

The definition of A↑↑BA\uparrow\uparrow B allows us to compute it recursively. To compute (A↑↑B) mod M(A\uparrow\uparrow B)\bmod M, we only need to apply extended Euler's theorem and compute (A↑↑(B−1)) mod φ(M)(A\uparrow\uparrow(B-1))\bmod\varphi(M). Since φ(φ(n))≤n/2\varphi(\varphi(n)) \le n/2 holds for all n≥2n\ge 2, the recursion always finishes within O(log⁡M)O(\log M) steps. Because extended Euler's theorem is used, we must distinguish whether the current result is strictly smaller than the current modulus. This only requires one additional check when taking the remainder. Boundary cases also require attention.

Reference code
#include <iostream>

// Calculate Euler's totient for n.
int phi(int n) {
  int res = n;
  for (int i = 2; i * i <= n; ++i) {
    if (n % i == 0) {
      res = res / i * (i - 1);
      while (n % i == 0) n /= i;
    }
  }
  if (n > 1) res = res / n * (n - 1);
  return res;
}

// Find remainder as in the exponent of extended Euler theorem.
int mod(long long v, int m) { return v >= m ? v % m + m : v; }

// Modular power.
int pow(int a, int b, int m) {
  long long res = 1, po = a;
  for (; b; b >>= 1) {
    if (b & 1) res = mod(res * po, m);
    po = mod(po * po, m);
  }
  return res;
}

// Modular tetration.
int tetra(int a, int b, int m) {
  if (a == 0) return !(b & 1);
  if (b == 0 || m == 1) return 1;
  if (b == 1) return mod(a, m);
  return pow(a, tetra(a, b - 1, phi(m)), m);
}

int main() {
  int t;
  std::cin >> t;
  for (; t; --t) {
    int a, b, m;
    std::cin >> a >> b >> m;
    std::cout << (tetra(a, b, m) % m) << std::endl;
  }
}

Exercises

References and notes

Footnotes

  1. This name is used mainly in algorithm-contest circles rather than being the general name of the result. ↩

This content comes from OI Wiki: Fermat's Little Theorem & Euler's Theorem. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.