Current Location: Home> Latest Articles> Understanding the gmp_legendre() Function in PHP: Determine Quadratic Residues and Non-Residues

Understanding the gmp_legendre() Function in PHP: Determine Quadratic Residues and Non-Residues

gitbox 2025-06-10

What Is the gmp_legendre() Function?

The gmp_legendre() function is provided by PHP's GMP extension and is used to calculate the Legendre symbol, a concept in number theory. It is particularly useful for determining whether a number is a quadratic residue modulo a given prime number.

The function signature is:

int gmp_legendre(GMP $a, GMP $p)

Here, $a is the integer to be evaluated, and $p is a prime number. Both parameters must be of GMP type.

Definition and Meaning of the Legendre Symbol

The Legendre symbol is a mathematical notation that indicates whether an integer is a quadratic residue modulo a prime. It is defined as:

(a/p) = a(p?1)/2 mod p

In this formula, a is any integer and p is an odd prime. The result indicates:

  • 1: a is a quadratic residue modulo p.
  • ?1: a is a quadratic non-residue modulo p.
  • 0: a and p are not coprime, or a = 0.

How to Use the gmp_legendre() Function

Below are examples demonstrating how to use gmp_legendre() to determine whether a number is a quadratic residue or a quadratic non-residue.

Check if a Number Is a Quadratic Residue


$a = gmp_init(5);
$p = gmp_init(7);
$ls = gmp_legendre($a, $p);
if ($ls == 1) {
    echo "$a is a quadratic residue modulo $p";
} else {
    echo "$a is not a quadratic residue modulo $p";
}

The output will be: “5 is a quadratic residue modulo 7.”

Check if a Number Is a Quadratic Non-Residue


$a = gmp_init(5);
$p = gmp_init(11);
$ls = gmp_legendre($a, $p);
if ($ls == -1) {
    echo "$a is a quadratic non-residue modulo $p";
} else {
    echo "$a is not a quadratic non-residue modulo $p";
}

This code will output: “5 is not a quadratic non-residue modulo 11.”

Important Notes When Using gmp_legendre()

Keep the following in mind when using this function:

  • Both arguments must be GMP-type numbers.
  • The second argument, $p, must be an odd prime.
  • The GMP extension must be installed and enabled in your PHP environment.

Conclusion

The gmp_legendre() function is a useful tool in PHP for performing number-theoretic calculations. It helps determine if an integer is a quadratic residue modulo a prime, which is important in various mathematical and cryptographic contexts. As long as the parameters are properly defined and the GMP extension is enabled, this function can be a powerful part of your PHP toolkit.

Reference

  • Liu Rujia. Algorithms on Integers and Polynomials. Beijing: Tsinghua University Press, 2008.