GNU-Darwin Web

# A Tour of NTL: Examples: Modular Arithmetic

NTL also supports modular integer arithmetic. The class ZZ_p represents the integers mod p. Despite the notation, p need not in general be prime, except in situations where this is mathematically required. The classes vec_ZZ_p, mat_ZZ_p, and ZZ_pX represent vectors, matrices, and polynomials mod p, and work much the same way as the corresponding classes for ZZ.

Here is a program that reads a prime number p, and a polynomial f modulo p, and factors it.

```#include <NTL/ZZ_pXFactoring.h>

int main()
{
ZZ p;
cin >> p;
ZZ_p::init(p);

ZZ_pX f;
cin >> f;

vec_pair_ZZ_pX_long factors;

CanZass(factors, f);

cout << factors << "\n";
// calls "Cantor/Zassenhaus" algorithm
}
```

As a program is running, NTL keeps track of a "current modulus" for the class ZZ_p, which can be initialized or changed using ZZ_p::init. This must be done before any variables are declared or computations are done that depend on this modulus.

Please note that for efficiency reasons, NTL does not make any attempt to ensure that variables declared under one modulus are not used under a different one. If that happens, the behavior of a program in this case is completely unpredictable.

Here are two more examples that illustrate the ZZ_p-related classes. The first is a vector addition routine (already supplied by NTL):

```#include <NTL/vec_ZZ_p.h>

void add(vec_ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b)
{
long n = a.length();
if (b.length() != n) Error("vector add: dimension mismatch");

x.SetLength(n);
long i;
for (i = 0; i < n; i++)
}
```

The second example is an inner product routine (also supplied by NTL):

```#include <NTL/vec_ZZ_p.h>

void InnerProduct(ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b)
{
long n = min(a.length(), b.length());
long i;
ZZ accum, t;

accum = 0;
for (i = 0; i < n; i++) {
mul(t, rep(a[i]), rep(b[i]));
}

conv(x, accum);
}
```

This second example illustrates two things. First, it illustrates the use of function rep which returns a read-only reference to the representation of a ZZ_p as a ZZ between 0 and p-1. Second, it illustrates a useful algorithmic technique, whereby one computes over ZZ, reducing mod p only when necessary. This reduces the number of divisions that need to be performed significantly, leading to much faster execution.

The class ZZ_p supports all the basic arithmetic operations in both operator and procedural form. All of the basic operations support a "promotion logic", promoting long to ZZ_p.

Note that the class ZZ_p is mainly useful only when you want to work with vectors, matrices, or polynomials mod p. If you just want to do some simple modular arithemtic, it is probably easier to just work with ZZs directly. This is especially true if you want to work with many different moduli: modulus switching is supported, but it is a bit awkward.

The class ZZ_pX supports all the basic arithmetic operations in both operator and procedural form. All of the basic operations support a "promotion logic", promoting both long and ZZ_p to ZZ_pX.

See ZZ_p.txt for details on ZZ_p; see ZZ_pX.txt for details on ZZ_pX; see ZZ_pXFactoring.txt for details on the routines for factoring polynomials over ZZ_p; see vec_ZZ_p.txt for details on vec_ZZ_p; see mat_ZZ_p.txt for details on mat_ZZ_p.

There is a mechanism for saving and restoring a modulus, which the following example illustrates. This routine takes as input an integer polynomial and a prime, and tests if the polynomial is irreducible modulo the prime.

```#include <NTL/ZZX.h>
#include <NTL/ZZ_pXFactoring.h>

long IrredTestMod(const ZZX& f, const ZZ& p)
{
ZZ_pBak bak;  // save current modulus in bak
bak.save();

ZZ_p::init(p);  // set the current modulus to p

return DetIrredTest(to_ZZ_pX(f));

// old modulus is restored automatically when bak is destroyed
// upon return
}
```

The modulus switching mechanism is actually quite a bit more general and flexible than this example illustrates.

The function to_ZZ_pX is yet another of NTL's many conversion functions. We could also have used the equivalent procedural form:

```   ZZ_pX f1;
conv(f1, f);
return DetIrredTest(f1);
```

Suppose in the above example that p is known in advance to be a small, single-precision prime. In this case, NTL provides a class zz_p, that acts just like ZZ_p, along with corresponding classes vec_zz_p, mat_zz_p, and zz_pX. The interfaces to all of the routines are generally identical to those for ZZ_p. However, the routines are much more efficient, in both time and space.

For small primes, the routine in the previous example could be coded as follows.

```#include <NTL/ZZX.h>
#include <NTL/lzz_pXFactoring.h>

long IrredTestMod(const ZZX& f, long p)
{
zz_pBak bak;
bak.save();

zz_p::init(p);

return DetIrredTest(to_zz_pX(f));
}
```

The following is a routine (essentially the same as implemented in NTL) for computing the GCD of polynomials with integer coefficients. It uses a "modular" approach: the GCDs are computed modulo small primes, and the results are combined using the Chinese Remainder Theorem (CRT). The small primes are specially chosen "FFT primes", which are of a special form that allows for particular fast polynomial arithmetic.

```#include <NTL/ZZX.h>

void GCD(ZZX& d, const ZZX& a, const ZZX& b)
{
if (a == 0) {
d = b;
if (LeadCoeff(d) < 0) negate(d, d);
return;
}

if (b == 0) {
d = a;
if (LeadCoeff(d) < 0) negate(d, d);
return;
}

ZZ c1, c2, c;
ZZX f1, f2;

content(c1, a);
divide(f1, a, c1);

content(c2, b);
divide(f2, b, c2);

GCD(c, c1, c2);

ZZ ld;

ZZX g, res;

ZZ prod;

zz_pBak bak;
bak.save();

long FirstTime = 1;

long i;
for (i = 0; ;i++) {
zz_p::FFTInit(i);
long p = zz_p::modulus();

if (divide(LeadCoeff(f1), p) || divide(LeadCoeff(f2), p)) continue;

zz_pX G, F1, F2;
zz_p  LD;

conv(F1, f1);
conv(F2, f2);
conv(LD, ld);

GCD(G, F1, F2);
mul(G, G, LD);

if (deg(G) == 0) {
res = 1;
break;
}

if (FirstTime || deg(G) < deg(g)) {
prod = 1;
g = 0;
FirstTime = 0;
}
else if (deg(G) > deg(g)) {
continue;
}

if (!CRT(g, prod, G)) {
PrimitivePart(res, g);
if (divide(f1, res) && divide(f2, res))
break;
}

}

mul(d, res, c);
if (LeadCoeff(d) < 0) negate(d, d);
}
```

See lzz_p.txt for details on zz_p; see lzz_pX.txt for details on zz_pX; see lzz_pXFactoring.txt for details on the routines for factoring polynomials over zz_p; see vec_lzz_p.txt for details on vec_zz_p; see mat_lzz_p.txt for details on mat_zz_p.

Arithmetic mod 2 is such an important special case that NTL provides a class GF2, that acts just like ZZ_p when p == 2, along with corresponding classes vec_GF2, mat_GF2, and GF2X. The interfaces to all of the routines are generally identical to those for ZZ_p. However, the routines are much more efficient, in both time and space.

This example illustrates the GF2X and mat_GF2 classes with a simple routine to test if a polynomial over GF(2) is irreducible using linear algebra. NTL's built-in irreducibility test is to be preferred, however.

```
#include <NTL/GF2X.h>
#include <NTL/mat_GF2.h>

long MatIrredTest(const GF2X& f)
{
long n = deg(f);

if (n <= 0) return 0;
if (n == 1) return 1;

if (GCD(f, diff(f)) != 1) return 0;

mat_GF2 M;

M.SetDims(n, n);

GF2X x_squared = GF2X(2, 1);

GF2X g;
g = 1;

for (long i = 0; i < n; i++) {
VectorCopy(M[i], g, n);
M[i][i] += 1;
g = (g * x_squared) % f;
}

long rank = gauss(M);

if (rank == n-1)
return 1;
else
return 0;
}
```

Note that the statement

```   g = (g * x_squared) % f;
```
could be replace d by the more efficient code sequence
```   MulByXMod(g, g, f);
MulByXMod(g, g, f);
```
but this would not significantly impact the overall running time, since it is the Gaussian elimination that dominates the running time.

See GF2.txt for details on GF2; see GF2X.txt for details on GF2X; see GF2XFactoring.txt for details on the routines for factoring polynomials over GF2; see vec_GF2.txt for details on vec_GF2; see mat_GF2.txt for details on mat_GF2.