% $Id$
% Copyright (c) 2000  The PARI Group
%
% This file is part of the PARI/GP documentation
%
% Permission is granted to copy, distribute and/or modify this document
% under the terms of the GNU General Public License
\chapter{Technical Reference Guide: the basics}

In the following chapters, we describe all public low-level functions of the
PARI library. These include specialized functions for handling all the PARI
types. Simple higher level functions, such as arithmetic or transcendental
functions, are described in Chapter~3 of the GP user's manual; we will
eventually see more general or flexible versions in the chapters to come. A
general introduction to the major concepts of PARI programming can be found
in Chapter~4, which you should really read first.

We shall now study specialized functions, more efficient than the library
wrappers, but sloppier on argument checking and damage control; besides
speed, their main advantage is to give finer control about the inner
workings of generic routines, offering more options to the programmer.

\misctitle{Important advice} Generic routines eventually call lower level
functions. Optimize your algorithms first, not overhead and conversion costs
between PARI routines. For generic operations, use generic routines first;
do not waste time looking for the most specialized one available unless you
identify a genuine bottleneck, or you need some special behavior the generic
routine does not offer. The PARI source code is part of the documentation;
look for inspiration there.\smallskip

The type \kbd{long} denotes a \tet{BITS_IN_LONG}-bit signed long integer (32
or 64 bits). The type \tet{ulong} is defined as \kbd{unsigned long}. The word
\emph{stack} always refer to the PARI stack, allocated through an initial
\kbd{pari\_init} call. Refer to Chapters 1--2 and~4 for general background.
\kbdsidx{BIL}

We shall often refer to the notion of \tev{shallow} function, which means that
some components of the result may point to components of the input, which is
more efficient than a \emph{deep} copy (full recursive copy of the object
tree). Such outputs are not suitable for \kbd{gerepileupto} and particular
care must be taken when garbage collecting objects which have been input to
shallow functions: corresponding outputs also become invalid and should no
longer be accessed.

\section{Initializing the library}

The following functions enable you to start using the PARI functions
in a program, and cleanup without exiting the whole program.

\subsec{General purpose}

\fun{void}{pari_init}{size_t size, ulong maxprime} initialize the
library, with a stack of \kbd{size} bytes and a prime table
up to the maximum of \kbd{maxprime} and $2^{16}$. Unless otherwise
mentioned, no PARI function will function properly before such an
initialization.

\fun{void}{pari_close}{void} stop using the library (assuming it was
initialized with \kbd{pari\_init}) and frees all allocated objects.

\subsec{Technical functions}\label{se:pari_init_tech}

\fun{void}{pari_init_opts}{size_t size, ulong maxprime, ulong opts} as
\kbd{pari\_init}, more flexible. \kbd{opts} is a mask of flags
among the following:

  \kbd{INIT\_JMPm}: install PARI error handler. When an exception is
raised, the program is terminated with \kbd{exit(1)}.

  \kbd{INIT\_SIGm}: install PARI signal handler.

  \kbd{INIT\_DFTm}: initialize the \kbd{GP\_DATA} environment structure.
This one \emph{must} be enabled once. If you close pari, then restart it,
you need not reinitialize \kbd{GP\_DATA}; if you do not, then old values are
restored.

\fun{void}{pari_close_opts}{ulong init_opts} as \kbd{pari\_close},
for a library initialized with a mask of options using
\kbd{pari\_init\_opts}. \kbd{opts} is a mask of flags among

  \kbd{INIT\_SIGm}: restore \kbd{SIG\_DFL} default action for signals
tampered with by PARI signal handler.

  \kbd{INIT\_DFTm}: frees the \kbd{GP\_DATA} environment structure.

\fun{void}{pari_sig_init}{void (*f)(int)} install the signal handler \kbd{f}
(see \kbd{signal(2)}): the signals \kbd{SIGBUS}, \kbd{SIGFPE}, \kbd{SIGINT},
\kbd{SIGBREAK}, \kbd{SIGPIPE} and \kbd{SIGSEGV} are concerned.

\fun{void}{pari_stackcheck_init}{void *stackbase} controls the system stack
exhaustion checking code in the GP interpreter. This should be used when the
system stack base address change or when the address seen by \kbd{pari\_init}
is too far from the base address. If stackbase is \kbd{NULL}, disable the
check, else set the base address to stackbase. It is normally used this way
\bprog
int thread_start (...)
{
  long first_item_on_the_stack;
  ...
  pari_stackcheck_init(&first_item_on_the_stack);
}
@eprog

\fun{int}{pari_daemon}{void} fork a PARI daemon, detaching from the main
process group. The function returns 1 in the parent, and 0 in the
forked son.

\subsec{Notions specific to the GP interpreter}

An \kbd{entree} is the generic object associated to an identifier (a name)
in GP's interpreter, be it a built-in or user function, or a variable. For
a function, it has at least the following fields:

  \kbd{char *name} : the name under which the interpreter knows us.

  \kbd{void *value} :  a pointer to the C function to call.

  \kbd{long menu} : an integer from 1 to 11 (to which group of function
                    help do we belong).

  \kbd{char *code} : the prototype code.

  \kbd{char *help} : the help text for the function.

A routine in GP is described to the analyzer by an \kbd{entree}
structure. Built-in PARI routines are grouped in \emph{modules}, which
are arrays of \kbd{entree} structs, the last of which satisfy
\kbd{name = NULL} (sentinel).

There are currently five modules in PARI/GP: general functions
(\tet{functions_basic}, known to \kbd{libpari}), gp-specific functions
(\tet{functions_gp}), gp-specific highlevel functions
(\tet{functions_highlevel}), and two modules of obsolete functions. The
function \kbd{pari\_init} initializes the interpreter and declares all
symbols in \kbd{functions\_basic}. You may declare further functions on a
case by case basis or as a whole module using

\fun{void}{pari_add_function}{entree *ep} adds a single routine to the
table of symbols in the interpreter. It assumes \kbd{pari\_init} has been
called.

\fun{void}{pari_add_module}{entree *mod} adds all the routines in module
\kbd{mod} to the table of symbols in the interpreter. It assumes
\kbd{pari\_init} has been called.

\noindent For instance, gp implements a number of private routines, which
it adds to the default set via the calls
\bprog
  pari_add_module(functions_gp);
  pari_add_module(functions_highlevel);
@eprog

\fun{void}{pari_add_oldmodule}{entree *mod} adds all the routines in module
\kbd{mod} to the table of symbols in the interpreter when running in
"PARI 1.xx compatible" mode (see \kbd{default(compatible)}) . It assumes
that
\kbd{pari\_init} has been called.

A GP \kbd{default} is likewise associated to a helper routine, that is run
when the value is consulted, or changed by \tet{default0} or \tet{setdefault}.
Such routines are grouped into modules: \tet{functions_default} containing all
defaults that make sense in libpari context, \tet{functions_gp_rl_default}
containing defaults that are \kbd{gp}-specific and do not make sense unless
we use \kbd{libreadline}, and \tet{functions_gp_default} containing all other
\kbd{gp}-specific defaults.

\fun{void}{pari_add_defaults_module}{entree *mod} adds all the defaults in
module \kbd{mod} to the interpreter. It assumes that \kbd{pari\_init} has
been called. From this point on, all defaults in module \kbd{mod} are known
to \tet{setdefault} and friends.

\subsec{Public callbacks}

The \kbd{gp} calculator associates elaborate functions (for instance the
break loop handler) to the following callbacks, and so can you:

\doc{cb_pari_ask_confirm}{void (*cb_pari_ask_confirm)(const char *s)}
initialized to \kbd{NULL}. Called with argument $s$ whenever PARI wants
confirmation for action $s$, for instance in \tet{secure} mode.

\doc{cb_pari_handle_exception}{extern int (*cb_pari_handle_exception)(long)}
initialized to \kbd{NULL}. If not \kbd{NULL} called with argument $-1$
on \kbd{SIGINT}, and argument \kbd{err} on error \kbd{err}. If it returns a
non-zero value, the error or signal handler returns, in effect further
ignoring the error or signal, otherwise it raises a fatal error.

\doc{cb_pari_sigint}{void (*cb_pari_sigint)(void)}.
Function called when \kbd{SIGINT} is raised. By default, raises
\bprog
  pari_err(talker, "user interrupt");
@eprog

\doc{cb_pari_err_recover}{extern void (*cb_pari_err_recover)(long)}
initialized to \kbd{pari\_exit()}. This call-back must not return.
This call-back is called after PARI has cleaned-up from an error.
The error number is passed as argument, unless the PARI stack
has been destroyed, in which case it is called with argument $-1$.

\doc{cb_pari_whatnow}{int (*cb_pari_whatnow)(PariOUT *out, const char *s, int flag)}
initialized to \kbd{NULL}. If not \kbd{NULL}, must check whether
$s$ existed in older versions of \kbd{pari} (the \kbd{gp} callback
checks against \kbd{pari-1.39.15}). All output must be done via \kbd{out}
methods.

\item $\fl = 0$: should print verbosely the answer, including help text if
available.

\item $\fl = 1$: must return $0$ if the function did not change, and a
non-$0$ result otherwise. May print a help message.

\misctitle{Utility function}

\fun{void}{pari_ask_confirm}{const char *s} raise an error if the
callback \tet{cb_pari_ask_confirm} is \kbd{NULL}. Otherwise
calls
\bprog
  cb_pari_ask_confirm(s);
@eprog
\subsec{Saving and restoring the GP context}

\fun{void}{gp_context_save}{struct gp_context* rec} save the current GP
context.

\fun{void}{gp_context_restore}{struct gp_context* rec} restore a GP context.
The new context must be an ancestor of the current context.

\subsec{GP history}

These functions allow to control the GP history (the \kbd{\%} operator).

\fun{GEN}{pari_add_hist}{GEN x} adds \kbd{x} as the last history entry.

\fun{GEN}{pari_get_hist}{long p}, if $p>0$ returns entry of index $p$
(i.e. \kbd{\%p}), else returns entry of index $n+p$ where $n$ is the
index of the last entry (used for \kbd{\%}, \kbd{\%`}, \kbd{\%``}, etc.).

\fun{ulong}{pari_nb_hist}{void} return the index of the last entry.

\section{Handling \kbd{GEN}s}
\noindent Almost all these functions are either macros or inlined. Unless
mentioned otherwise, they do not evaluate their arguments twice. Most of them
are specific to a set of types, although no consistency checks are made:
e.g.~one may access the \kbd{sign} of a \typ{PADIC}, but the result is
meaningless.

\subsec{Allocation}

\fun{GEN}{cgetg}{long l, long t} allocates (the root of) a \kbd{GEN}
of type $t$ and length $l$. Sets $z[0]$.

\fun{GEN}{cgeti}{long l} allocates a \typ{INT} of length $l$ (including the
2 codewords). Sets $z[0]$ only.

\fun{GEN}{cgetr}{long l} allocates a \typ{REAL} of length $l$ (including the
2 codewords). Sets $z[0]$ only.

\fun{GEN}{cgetc}{long prec} allocates a \typ{COMPLEX} whose real and
imaginary parts are \typ{REAL}s of length \kbd{prec}.

\fun{GEN}{cgetg_copy}{GEN x, long *lx} fast version of \kbd{cgetg}:
allocate a \kbd{GEN} with the same type and length as $x$, setting \kbd{*lx}
to \kbd{lg(x)} as a side-effect. (Only sets the first codeword.) This is
a little faster than \kbd{cgetg} since we may reuse the bitmask in
$x[0]$ instead of recomputing it, and we do not need to check that the
length does not overflow the possibilities of the
implementation (since an object with that length already exists). Note that
\kbd{cgetg} with arguments known at compile time, as in
\bprog
  cgetg(3, t_INTMOD)
@eprog\noindent will be even faster since the compiler will directly perform
all computations and checks.

\fun{GEN}{vectrunc_init}{long l} perform \kbd{cgetg(l,t\_VEC)}, then
set the length to $1$ and return the result. This is used to  implement
vectors whose final length is easily bounded at creation time, that we intend
to fill gradually using:

\fun{void}{vectrunc_append}{GEN x, GEN y} assuming $x$ was allocated using
\tet{vectrunc_init}, appends $y$ as the last element of $x$, which
grows in the process. The function is shallow: we append $y$, not a copy;
it is equivalent to
\bprog
  long lx = lg(x); gel(x,lx) = y; setlg(x, lx+1);
@eprog\noindent
Beware that the maximal size of $x$ (the $l$ argument to \tet{vectrunc_init})
is unknown, hence unchecked, and stack corruption will occur if we append
more than $l-1$ elements to $x$. Use the safer (but slower)
\kbd{shallowconcat} when $l$ is not easy to bound in advance.

An other possibility is simply to allocate using \kbd{cgetg(l, t)} then fill
the components as they become available: this time the downside is that we do
not obtain a correct \kbd{GEN} until the vector is complete. Almost no PARI
function will be able to operate on it.

\fun{GEN}{vecsmalltrunc_init}{long l}

\fun{void}{vecsmalltrunc_append}{GEN x, long t} analog to the above for a
\typ{VECSMALL} container.

\subsec{Length conversions}

These routines convert a non-negative length to different units. Their
behavior is undefined at negative integers.

\fun{long}{ndec2nlong}{long x} converts a number of decimal digits to a number
of words. Returns $ 1 + \kbd{floor}(x \times \B \log_2 10)$.

\fun{long}{ndec2prec}{long x} converts a number of decimal digits to a number
of codewords. This is equal to 2 + \kbd{ndec2nlong(x)}.

\fun{long}{prec2ndec}{long x} converts a number of of codewords to a
number of decimal digits.

\fun{long}{nbits2nlong}{long x} converts a number of bits to a number of
words. Returns the smallest word count containing $x$ bits, i.e $
\kbd{ceil}(x / \B)$.

\fun{long}{nbits2prec}{long x} converts a number of bits to a number of
codewords. This is equal to 2 + \kbd{nbits2nlong(x)}.

\fun{long}{nchar2nlong}{long x} converts a number of bytes to number of
words. Returns the smallest word count containing $x$ bytes, i.e
$\kbd{ceil}(x / \kbd{sizeof(long)})$.

\fun{long}{bit_accuracy}{long x} converts a \typ{REAL} length into a number
of significant bits. Returns $(x - 2)\B$.

\fun{double}{bit_accuracy_mul}{long x, double y} returns $(x - 2)\B \times y$.

\subsec{Read type-dependent information}

\fun{long}{typ}{GEN x} returns the type number of~\kbd{x}. The header files
included through \kbd{pari.h} define symbolic constants for the \kbd{GEN}
types: \typ{INT} etc. Never use their actual numerical values. E.g to determine
whether \kbd{x} is a \typ{INT}, simply check
\bprog
  if (typ(x) == t_INT) { }
@eprog\noindent
The types are internally ordered and this simplifies the implementation of
commutative binary operations (e.g addition, gcd). Avoid using the ordering
directly, as it may change in the future; use type grouping functions
instead (\secref{se:typegroup}).

\fun{const char*}{type_name}{long t} given a type number \kbd{t} this routine
returns a string containing its symbolic name. E.g \kbd{type\_name(\typ{INT})}
returns \kbd{"\typ{INT}"}. The return value is read-only.

\fun{long}{lg}{GEN x} returns the length of~\kbd{x} in \B-bit words.

\fun{long}{lgefint}{GEN x} returns the effective length of the \typ{INT} \kbd{x}
in \B-bit words.

\fun{long}{signe}{GEN x} returns the sign ($-1$, 0 or 1) of~\kbd{x}. Can be
used for \typ{INT}, \typ{REAL}, \typ{POL} and \typ{SER} (for the last two
types, only 0 or 1 are possible).

\fun{long}{gsigne}{GEN x} returns the sign of a real number $x$,
valid for \typ{INT}, \typ{REAL} as \kbd{signe}, but also for \typ{FRAC}.
Raise a type error if \kbd{typ(x)} is not among those three.

\fun{long}{expi}{GEN x} returns the binary exponent of the real number equal
to the \typ{INT}~\kbd{x}. This is a special case of \kbd{gexpo}.

\fun{long}{expo}{GEN x} returns the binary exponent of the
\typ{REAL}~\kbd{x}.

\fun{long}{mpexpo}{GEN x} returns the binary exponent of the \typ{INT}
or \typ{REAL}~\kbd{x}.

\fun{long}{gexpo}{GEN x} same as \kbd{expo}, but also valid when \kbd{x}
is not a \typ{REAL} (returns the largest exponent found among the components
of \kbd{x}). When \kbd{x} is an exact~0, this returns
\hbox{\kbd{-HIGHEXPOBIT}}, which is lower than any valid exponent.

\fun{long}{valp}{GEN x} returns the $p$-adic valuation (for
a \typ{PADIC}) or $X$-adic valuation (for a \typ{SER}, taken with respect to
the main variable) of~\kbd{x}.

\fun{long}{precp}{GEN x} returns the precision of the \typ{PADIC}~\kbd{x}.

\fun{long}{varn}{GEN x} returns the variable number of the
\typ{POL} or \typ{SER}~\kbd{x} (between 0 and \kbd{MAXVARN}).

\fun{long}{gvar}{GEN x} returns the main variable number when any variable
at all occurs in the composite object~\kbd{x} (the smallest variable number
which occurs), and \tet{NO_VARIABLE} otherwise.

\fun{long}{gvar2}{GEN x} returns the variable number for the ring over which
$x$ is defined, e.g. if $x\in \Z[a][b]$ return (the variable number for)
$a$. Return \tet{NO_VARIABLE} if $x$ has no variable or is not defined over a
polynomial ring.

\fun{long}{degpol}{GEN x} returns the degree of \typ{POL}~\kbd{x},
\emph{assuming} its leading coefficient is non-zero (an exact $0$ is
impossible, but an inexact $0$ is allowed). By convention the degree of an
exact $0$ polynomial is $-1$. If the leading coefficient of \kbd{x} is $0$,
the result is undefined.

\fun{long}{lgpol}{GEN x} is equal to \kbd{degpol(x) + 1}. Used to loop over
the coefficients of a \typ{POL} in the following situation:
\bprog
    GEN xd = x + 2;
    long i, l = lgpol(x);
    for (i = 0; i < l; i++) foo( xd[i] ).
@eprog

\fun{long}{precision}{GEN x} If \kbd{x} is of type \typ{REAL}, returns the
precision of~\kbd{x}, namely the length of \kbd{x} in \B-bit words if \kbd{x}
is not zero, and a reasonable quantity obtained from the exponent of \kbd{x}
if \kbd{x} is numerically equal to zero. If \kbd{x} is of type
\typ{COMPLEX}, returns the minimum of the precisions of the real and
imaginary part. Otherwise, returns~0 (which stands for infinite precision).

\fun{long}{gprecision}{GEN x} as \kbd{precision} for scalars. Returns the
lowest precision encountered among the components otherwise.

\fun{long}{sizedigit}{GEN x} returns 0 if \kbd{x} is exactly~0. Otherwise,
returns \kbd{\key{gexpo}(x)} multiplied by $\log_{10}(2)$. This gives a crude
estimate for the maximal number of decimal digits of the components
of~\kbd{x}.

\subsec{Eval type-dependent information}
These routines convert type-dependent information to bitmask to fill the
codewords of \kbd{GEN} objects (see \secref{se:impl}). E.g for a
\typ{REAL}~\kbd{z}:
\bprog
  z[1] = evalsigne(-1) | evalexpo(2)
@eprog
Compatible components of a codeword for a given type can be OR-ed as above.

\fun{ulong}{evaltyp}{long x} convert type~\kbd{x} to bitmask (first
codeword of all \kbd{GEN}s)

\fun{long}{evallg}{long x} convert length~\kbd{x} to bitmask (first
codeword of all \kbd{GEN}s). Raise overflow error if \kbd{x} is so large that
the corresponding length cannot be represented

\fun{long}{_evallg}{long x} as \kbd{evallg} \emph{without} the overflow
check.

\fun{ulong}{evalvarn}{long x} convert variable number~\kbd{x} to bitmask
(second codeword of \typ{POL} and \typ{SER})

\fun{long}{evalsigne}{long x} convert sign~\kbd{x} (in $-1,0,1$) to bitmask
(second codeword of \typ{INT}, \typ{REAL}, \typ{POL}, \typ{SER})

\fun{long}{evalprecp}{long x} convert $p$-adic ($X$-adic) precision~\kbd{x}
to bitmask (second codeword of \typ{PADIC}, \typ{SER})

\fun{long}{evalvalp}{long x} convert $p$-adic ($X$-adic) valuation~\kbd{x} to
bitmask (second codeword of \typ{PADIC}, \typ{SER}). Raise overflow error if
\kbd{x} is so large that the corresponding valuation cannot be represented

\fun{long}{_evalvalp}{long x} same as \kbd{evalvalp} \emph{without} the
overflow check.

\fun{long}{evalexpo}{long x} convert exponent~\kbd{x} to bitmask (second
codeword of \typ{REAL}). Raise overflow error if \kbd{x} is so
large that the corresponding exponent cannot be represented

\fun{long}{_evalexpo}{long x} same as \kbd{evalexpo} \emph{without} the
overflow check.

\fun{long}{evallgefint}{long x} convert effective length~\kbd{x} to bitmask
(second codeword \typ{INT}). This should be less or equal than the length
of the \typ{INT}, hence there is no overflow check for the effective length.

\subsec{Set type-dependent information}
Use these functions and macros with extreme care since usually the
corresponding information is set otherwise, and the components and further
codeword fields (which are left unchanged) may not be compatible with the new
information.

\fun{void}{settyp}{GEN x, long s} sets the type number of~\kbd{x} to~\kbd{s}.

\fun{void}{setlg}{GEN x, long s} sets the length of~\kbd{x} to~\kbd{s}. This
is an efficient way of truncating vectors, matrices or polynomials.

\fun{void}{setlgefint}{GEN x, long s} sets the effective length
of the \typ{INT} \kbd{x} to~\kbd{s}. The number \kbd{s} must be less than or
equal to the length of~\kbd{x}.

\fun{void}{setsigne}{GEN x, long s} sets the sign of~\kbd{x} to~\kbd{s}.
If \kbd{x} is a \typ{INT} or \typ{REAL}, \kbd{s} must be equal to $-1$, 0
or~1, and if \kbd{x} is a \typ{POL} or \typ{SER}, \kbd{s} must be equal to 0
or~1. No sanity check is made; in particular, setting the sign of a
$0$ \typ{INT} to $\pm1$ creates an invalid object.

\fun{void}{togglesign}{GEN x} sets the sign $s$ of~\kbd{x} to $-s$, in place.

\fun{void}{togglesign_safe}{GEN *x} sets the $s$ sign of~\kbd{*x} to $-s$, in
place, unless \kbd{*x} is one of the integer universal constants in which case
replace \kbd{*x} by its negation (e.g.~replace \kbd{gen\_1} by \kbd{gen\_m1}).

\fun{void}{setabssign}{GEN x} sets the sign $s$ of~\kbd{x} to $|s|$, in place.

\fun{void}{affectsign}{GEN x, GEN y} shortcut for \kbd{setsigne(y, signe(x))}.
No sanity check is made; in particular, setting the sign of a
$0$ \typ{INT} to $\pm1$ creates an invalid object.

\fun{void}{affectsign_safe}{GEN x, GEN *y} sets the sign of~\kbd{*y} to that
of~\kbd{x}, in place, unless \kbd{*y} is one of the integer universal
constants in which case replace \kbd{*y} by its negation if needed
(e.g.~replace \kbd{gen\_1} by \kbd{gen\_m1} if \kbd{x} is negative). No other
sanity check is made; in particular, setting the sign of a $0$
\typ{INT} to $\pm1$ creates an invalid object.

\fun{void}{normalize_frac}{GEN z} assuming $z$ is of the form \kbd{mkfrac(a,b)}
with $b\neq 0$, make sure that $b > 0$ by changing the sign of $a$ in place if
needed (use \kbd{togglesign}).

\fun{void}{setexpo}{GEN x, long s} sets the binary exponent of the
\typ{REAL}~\kbd{x} to \kbd{s}. The value \kbd{s} must be a 24-bit signed
number.

\fun{void}{setvalp}{GEN x, long s} sets the $p$-adic or $X$-adic valuation
of~\kbd{x} to~\kbd{s}, if \kbd{x} is a \typ{PADIC} or a \typ{SER},
respectively.

\fun{void}{setprecp}{GEN x, long s} sets the $p$-adic precision of the
\typ{PADIC}~\kbd{x} to~\kbd{s}.

\fun{void}{setvarn}{GEN x, long s} sets the variable number of the \typ{POL}
or \typ{SER}~\kbd{x} to~\kbd{s} (where $0\le \kbd{s}\le\kbd{MAXVARN}$).

\subsec{Type groups}\label{se:typegroup}
In the following functions, \kbd{t} denotes the type of a \kbd{GEN}.
They used to be implemented as macros, which could evaluate their argument
twice; \emph{no longer}: it is not inefficient to write
\bprog
  is_intreal_t(typ(x))
@eprog

\fun{int}{is_recursive_t}{long t} \kbd{true} iff \kbd{t} is a recursive
type (the non-recursive types are \typ{INT}, \typ{REAL},
\typ{STR}, \typ{VECSMALL}). Somewhat contrary to intuition, \typ{LIST} is
also non-recursive, ; see the Developer's guide for details.

\fun{int}{is_intreal_t}{long t} \kbd{true} iff \kbd{t} is \typ{INT}
or \typ{REAL}.

\fun{int}{is_rational_t}{long t} \kbd{true} iff \kbd{t} is \typ{INT}
or \typ{FRAC}.

\fun{int}{is_vec_t}{long t} \kbd{true} iff \kbd{t} is \typ{VEC}
or \typ{COL}.

\fun{int}{is_matvec_t}{long t} \kbd{true} iff \kbd{t} is \typ{MAT}, \typ{VEC}
or \typ{COL}.

\fun{int}{is_scalar_t}{long t} \kbd{true} iff \kbd{t} is a scalar, i.e
a \typ{INT},
a \typ{REAL},
a \typ{INTMOD},
a \typ{FRAC},
a \typ{COMPLEX},
a \typ{PADIC},
a \typ{QUAD},
or
a \typ{POLMOD}.

\fun{int}{is_extscalar_t}{long t} \kbd{true} iff \kbd{t} is a scalar (see
\kbd{is\_scalar\_t}) or \kbd{t} is \typ{POL}.

\fun{int}{is_const_t}{long t} \kbd{true} iff \kbd{t} is a scalar which is not
\typ{POLMOD}.

\fun{int}{is_noncalc_t}{long t} true if generic operations (\kbd{gadd},
\kbd{gmul}) do not make sense for $t$ : corresponds to types
\typ{LIST}, \typ{STR}, \typ{VECSMALL}, \typ{CLOSURE}

\subsec{Accessors and components}\label{se:accessors}
The first two functions return \kbd{GEN} components as copies on the stack:

\fun{GEN}{compo}{GEN x, long n} creates a copy of the \kbd{n}-th true
component (i.e.\ not counting the codewords) of the object~\kbd{x}.

\fun{GEN}{truecoeff}{GEN x, long n} creates a copy of the coefficient of
degree~\kbd{n} of~\kbd{x} if \kbd{x} is a scalar, \typ{POL} or \typ{SER},
and otherwise of the \kbd{n}-th component of~\kbd{x}.
\smallskip

\noindent On the contrary, the following routines return the address of a
\kbd{GEN} component. No copy is made on the stack:

\fun{GEN}{constant_term}{GEN x} returns the address the constant term of
\typ{POL}~\kbd{x}. By convention, a $0$ polynomial (whose \kbd{sign} is $0$)
has \kbd{gen\_0} constant term.

\fun{GEN}{leading_term}{GEN x} returns the address the leading term of
\typ{POL}~\kbd{x}. This may be an inexact $0$.

\fun{GEN}{gel}{GEN x, long i} returns the address of the
\kbd{x[i]} entry of~\kbd{x}. (\kbd{el} stands for element.)

\fun{GEN}{gcoeff}{GEN x, long i, long j} returns the address of the
\kbd{x[i,j]} entry of \typ{MAT}~\kbd{x}, i.e.~the coefficient at row~\kbd{i}
and column~\kbd{j}.

\fun{GEN}{gmael}{GEN x, long i, long j} returns the address of the
\kbd{x[i][j]} entry of~\kbd{x}. (\kbd{mael} stands for multidimensional array
element.)

\fun{GEN}{gmael2}{GEN A, long x1, long x2} is an alias for \kbd{gmael}.
Similar macros \tet{gmael3}, \tet{gmael4}, \tet{gmael5} are available.

\section{Global numerical constants}
These are defined in the various public PARI headers.

\subsec{Constants related to word size}

\noindent \kbd{long} $\tet{BITS_IN_LONG} = 2^{\tet{TWOPOTBITS_IN_LONG}}$:
number of bits in a \kbd{long} (32 or 64).

\noindent \kbd{long} \tet{BITS_IN_HALFULONG}: \kbd{BITS\_IN\_LONG} divided by
$2$.

\noindent \kbd{long} \tet{LONG_MAX}: the largest positive \kbd{long}.

\noindent \kbd{ulong} \tet{ULONG_MAX}: the largest \kbd{ulong}.

\noindent \kbd{long} \tet{DEFAULTPREC}:    the length (\kbd{lg}) of a
\typ{REAL} with 64 bits of accuracy

\noindent \kbd{long} \tet{MEDDEFAULTPREC}: the length (\kbd{lg}) of a
\typ{REAL} with 128 bits of accuracy

\noindent \kbd{long} \tet{BIGDEFAULTPREC}: the length (\kbd{lg}) of a
\typ{REAL} with 192 bits of accuracy

\noindent \kbd{ulong} \tet{HIGHBIT}: the largest power of $2$ fitting in an
\kbd{ulong}.

\noindent \kbd{ulong} \tet{LOWMASK}: bitmask yielding the least significant
bits.

\noindent \kbd{ulong} \tet{HIGHMASK}: bitmask yielding the most significant
bits.

\noindent The last two are used to implement the following convenience macros,
returning half the bits of their operand:

\fun{ulong}{LOWWORD}{ulong a} returns least significant bits.

\fun{ulong}{HIGHWORD}{ulong a} returns most significant bits.

\noindent Finally

\fun{long}{divsBIL}{long n} returns the Euclidean quotient of $n$ by
\kbd{BITS\_IN\_LONG} (with non-negative remainder).

\fun{long}{remsBIL}{n} returns the (non-negative) Euclidean remainder of $n$
by \kbd{BITS\_IN\_LONG}

\fun{long}{dvmdsBIL}{long n, long *r}

\fun{ulong}{dvmduBIL}{ulong n, ulong *r} sets $r$ to \kbd{remsBIL(n)}
and returns \kbd{divsBIL(n)}.

\subsec{Masks used to implement the \kbd{GEN} type}

These constants are used by higher level macros, like \kbd{typ} or \kbd{lg}:

\noindent \tet{EXPOnumBITS},
\tet{LGnumBITS},
\tet{SIGNnumBITS},
\tet{TYPnumBITS},
\tet{VALPnumBITS},
\tet{VARNnumBITS}:
number of bits used to encode \kbd{expo}, \kbd{lg}, \kbd{signe},
\kbd{typ}, \kbd{valp}, \kbd{varn}.

\noindent \tet{PRECPSHIFT},
\tet{SIGNSHIFT},
\tet{TYPSHIFT},
\tet{VARNSHIFT}: shifts used to recover or encode \kbd{precp}, \kbd{varn},
\kbd{typ}, \kbd{signe}

\noindent \tet{CLONEBIT},
\tet{EXPOBITS},
\tet{LGBITS},
\tet{PRECPBITS},
\tet{SIGNBITS},
\tet{TYPBITS},
\tet{VALPBITS},
\tet{VARNBITS}: bitmasks used to extract \kbd{isclone}, \kbd{expo}, \kbd{lg},
\kbd{precp}, \kbd{signe}, \kbd{typ}, \kbd{valp}, \kbd{varn} from \kbd{GEN}
codewords.

\noindent \tet{MAXVARN}: the largest possible variable number.

\noindent \tet{NO_VARIABLE}:  sentinel returned by \kbd{gvar(x)} when \kbd{x}
does not contain any polynomial; has a lower priority than any valid variable
number.

\noindent \tet{HIGHEXPOBIT}: a power of $2$, one more that the largest possible
exponent for a \typ{REAL}.

\noindent \tet{HIGHVALPBIT}: a power of $2$, one more that the largest possible
valuation for a \typ{PADIC} or a \typ{SER}.

\subsec{$\log 2$, $\pi$}

These are \kbd{double} approximations to useful constants:

\noindent \tet{LOG2}: $\log 2$.

\noindent \tet{LOG10_2}: $\log 2 / \log 10$.

\noindent \tet{LOG2_10}: $\log 10 / \log 2$.

\noindent \tet{PI}: $\pi$.

\section{Handling the PARI stack}

\subsec{Allocating memory on the stack}

\fun{GEN}{cgetg}{long n, long t} allocates memory on the stack for
an object of length \kbd{n} and type~\kbd{t}, and initializes its first
codeword.

\fun{GEN}{cgeti}{long n} allocates memory on the stack for a \typ{INT}
of length~\kbd{n}, and initializes its first codeword. Identical to
\kbd{cgetg(n,\typ{INT})}.

\fun{GEN}{cgetr}{long n} allocates memory on the stack for a \typ{REAL}
of length~\kbd{n}, and initializes its first codeword. Identical to
\kbd{cgetg(n,\typ{REAL})}.

\fun{GEN}{cgetc}{long n} allocates memory on the stack for a
\typ{COMPLEX}, whose real and imaginary parts are \typ{REAL}s
of length~\kbd{n}.

\fun{GEN}{cgetp}{GEN x} creates space sufficient to hold the
\typ{PADIC}~\kbd{x}, and sets the prime $p$ and the $p$-adic precision to
those of~\kbd{x}, but does not copy (the $p$-adic unit or zero representative
and the modulus of)~\kbd{x}.

\fun{GEN}{new_chunk}{size_t n} allocates a \kbd{GEN} with $n$ components,
\emph{without} filling the required code words. This is the low-level
constructor underlying \kbd{cgetg}, which calls \kbd{new\_chunk} then sets
the first code word. It works by simply returning the address
\kbd{((GEN)avma) - n}, after checking that it is larger than \kbd{(GEN)bot}.

\fun{char*}{stackmalloc}{size_t n} allocates memory on the stack for $n$
chars (\emph{not} $n$ \kbd{GEN}s). This is faster than using \kbd{malloc},
and easier to use in most situations when temporary storage is needed. In
particular there is no need to \kbd{free} individually all variables thus
allocated: a simple \kbd{avma = oldavma} might be enough. On the other hand,
beware that this is not permanent independent storage, but part of the stack.

\noindent Objects allocated through these last two functions cannot be
\kbd{gerepile}'d, since they are not yet valid \kbd{GEN}s: their codewords
must be filled first.

\fun{GEN}{cgetalloc}{long t, size_t l}, same as \kbd{cgetg(t, l)}, except
that the result is allocated using \tet{pari_malloc} instead of the PARI
stack. The resulting \kbd{GEN} is now impervious to garbage collecting
routines, but should be freed using \tet{pari_free}.

\subsec{Stack-independent binary objects}

\fun{GENbin*}{copy_bin}{GEN x} copies $x$ into a malloc'ed structure suitable
for stack-independent binary transmission or storage. The object obtained
is architecture independent provided, \kbd{sizeof(long)} remains the same
on all PARI instances involved, as well as the multiprecision kernel (either
native or GMP).

\fun{GENbin*}{copy_bin_canon}{GEN x} as \kbd{copy\_bin}, ensuring furthermore
that the binary object is independent of the multiprecision kernel. Slower
than \kbd{copy\_bin}.

\fun{GEN}{bin_copy}{GENbin *p} assuming $p$ was created by \kbd{copy\_bin(x)}
(not necessarily by the same PARI instance: transmission or external storage
may be involved), restores $x$ on the PARI stack.

\noindent The routine \kbd{bin\_copy} transparently encapsulate the following
functions:

\fun{GEN}{GENbinbase}{GENbin *p} the \kbd{GEN} data actually stored in $p$.
All addresses are stored as offsets with respect to a common reference point,
so the resulting \kbd{GEN} is unusable unless it is a non-recursive type;
private low-level routines must be called first to restore absolute addresses.

\fun{void}{shiftaddress}{GEN x, long dec} converts relative addresses to
absolute ones.

\fun{void}{shiftaddress_canon}{GEN x, long dec} converts relative addresses to
absolute ones, and converts leaves from a canonical form to the one
specific to the multiprecision kernel in use. The \kbd{GENbin} type stores
whether leaves are stored in canonical form, so \kbd{bin\_copy} can call
the right variant.

\subsec{Garbage collection}
See \secref{se:garbage} for a detailed explanation and many examples.

\fun{void}{cgiv}{GEN x} frees object \kbd{x}, assuming it is the last created
on the stack.

\fun{GEN}{gerepile}{pari_sp p, pari_sp q, GEN x} general garbage collector
for the stack.

\fun{void}{gerepileall}{pari_sp av, int n, ...} cleans up the stack from
\kbd{av} on (i.e from \kbd{avma} to \kbd{av}), preserving the \kbd{n} objects
which follow in the argument list (of type \kbd{GEN*}). For instance,
\kbd{gerepileall(av, 2, \&x, \&y)} preserves \kbd{x} and \kbd{y}.

\fun{void}{gerepileallsp}{pari_sp av, pari_sp ltop, int n, ...}
cleans up the stack between \kbd{av} and \kbd{ltop}, updating
the \kbd{n} elements which follow \kbd{n} in the argument list (of type
\kbd{GEN*}). Check that the elements of \kbd{g} have no component between
\kbd{av} and \kbd{ltop}, and assumes that no garbage is present between
\kbd{avma} and \kbd{ltop}. Analogous to (but faster than) \kbd{gerepileall}
otherwise.

\fun{GEN}{gerepilecopy}{pari_sp av, GEN x} cleans up the stack  from
\kbd{av} on, preserving the object \kbd{x}. Special case of \kbd{gerepileall}
(case $\kbd{n} = 1$), except that the routine returns the preserved \kbd{GEN}
instead of updating its address through a pointer.

\fun{void}{gerepilemany}{pari_sp av, GEN* g[], int n} alternative interface
to \kbd{gerepileall}. The preserved \kbd{GEN}s are the elements of the array
\kbd{g} of length $n$: \kbd{g[0]}, \kbd{g[1]}, \dots,
\kbd{g[$n$-1]}. Obsolete: no more efficient than \kbd{gerepileall},
error-prone, and clumsy (need to declare an extra \kbd{GEN *g}).

\fun{void}{gerepilemanysp}{pari_sp av, pari_sp ltop, GEN* g[], int n}
alternative interface to \kbd{gerepileallsp}. Obsolete.

\fun{void}{gerepilecoeffs}{pari_sp av, GEN x, int n} cleans up the stack
from \kbd{av} on, preserving \kbd{x[0]}, \dots, \kbd{x[n-1]} (which are
\kbd{GEN}s).

\fun{void}{gerepilecoeffssp}{pari_sp av, pari_sp ltop, GEN x, int n}
cleans up the stack from \kbd{av} to \kbd{ltop}, preserving \kbd{x[0]},
\dots, \kbd{x[n-1]} (which are \kbd{GEN}s). Same assumptions as in
\kbd{gerepilemanysp}, of which this is a variant. For instance
\bprog
  z = cgetg(3, t_COMPLEX);
  av = avma; garbage(); ltop = avma;
  z[1] = fun1();
  z[2] = fun2();
  gerepilecoeffssp(av, ltop, z + 1, 2);
  return z;
@eprog\noindent
cleans up the garbage between \kbd{av} and \kbd{ltop}, and connects \kbd{z}
and its two components. This is marginally more efficient than the standard
\bprog
  av = avma; garbage(); ltop = avma;
  z = cgetg(3, t_COMPLEX);
  z[1] = fun1();
  z[2] = fun2(); return gerepile(av, ltop, z);
@eprog\noindent

\fun{GEN}{gerepileupto}{pari_sp av, GEN q} analogous to (but faster than)
\kbd{gerepilecopy}. Assumes that \kbd{q} is connected and that its root was
created before any component. If \kbd{q} is not on the stack, this is
equivalent to \kbd{avma = av}; in particular, sentinels which are not even
proper \kbd{GEN}s such as \kbd{q = NULL} are allowed.

\fun{GEN}{gerepileuptoint}{pari_sp av, GEN q} analogous to (but faster than)
\kbd{gerepileupto}. Assumes further that \kbd{q} is a \typ{INT}. The
length and effective length of the resulting \typ{INT} are equal.

\fun{GEN}{gerepileuptoleaf}{pari_sp av, GEN q} analogous to (but faster than)
\kbd{gerepileupto}. Assumes further that \kbd{q} is a leaf, i.e a
non-recursive type (\kbd{is\_recursive\_t(typ(q))} is non-zero). Contrary to
\kbd{gerepileuptoint} and \kbd{gerepileupto}, \kbd{gerepileuptoleaf} leaves
length and effective length of a \typ{INT} unchanged.

\subsec{Garbage collection : advanced use}

\fun{void}{stackdummy}{pari_sp av, pari_sp ltop} inhibits the memory area
between \kbd{av} \emph{included} and \kbd{ltop} \emph{excluded} with respect to
\kbd{gerepile}, in order to avoid a call to \kbd{gerepile(av, ltop,...)}.
The stack space is not reclaimed though.

More precisely, this routine assumes that \kbd{av} is recorded earlier
than \kbd{ltop}, then marks the specified stack segment as a
non-recursive type of the correct length. Thus gerepile will not inspect
the zone, at most copy it. To be used in the following situation:
\bprog
  av0 = avma; z = cgetg(t_VEC, 3);
  gel(z,1) = HUGE(); av = avma; garbage(); ltop = avma;
  gel(z,2) = HUGE(); stackdummy(av, ltop);
@eprog\noindent
Compared to the orthodox
\bprog
  gel(z,2) = gerepile(av, ltop, gel(z,2));
@eprog\noindent
or even more wasteful
\bprog
  z = gerepilecopy(av0, z);
@eprog\noindent
we temporarily lose $(\kbd{av} - \kbd{ltop})$ words but save a costly
\kbd{gerepile}. In principle, a garbage collection higher up the call
chain should reclaim this later anyway.

Without the \kbd{stackdummy}, if the $[\kbd{av}, \kbd{ltop}]$ zone is
arbitrary (not even valid \kbd{GEN}s as could happen after direct
truncation via \kbd{setlg}), we would leave dangerous data in the middle
of~\kbd{z}, which would be a problem for a later
\bprog
  gerepile(..., ... , z);
@eprog\noindent
And even if it were made of valid \kbd{GEN}s, inhibiting the area makes sure
\kbd{gerepile} will not inspect their components, saving time.

Another natural use in low-level routines is to ``shorten'' an existing
\kbd{GEN} \kbd{z} to its first $\kbd{n}-1$ components:
\bprog
  setlg(z, n);
  stackdummy((pari_sp)(z + lg(z)), (pari_sp)(z + n));
@eprog\noindent
or to its last \kbd{n} components:
\bprog
  long L = lg(z) - n, tz = typ(z);
  stackdummy((pari_sp)(z + L), (pari_sp)z);
  z += L; z[0] = evaltyp(tz) | evallg(L);
@eprog

The first scenario (safe shortening an existing \kbd{GEN}) is in fact so
common, that we provide a function for this:

\fun{void}{fixlg}{GEN z, long ly} a safe variant of \kbd{setlg(z, ly)}. If
\kbd{ly} is larger than \kbd{lg(z)} do nothing. Otherwise, shorten $z$ in
place, using \kbd{stackdummy} to avoid later \kbd{gerepile} problems.

\fun{GEN}{gcopy_avma}{GEN x, pari_sp *AVMA} return a copy of $x$ as from \kbd{gcopy},
except that we pretend that initially \kbd{avma} is \kbd{*AVMA}, and that \kbd{*AVMA}
is updated accordingly (so that the total size of $x$ is the difference between the
two successive values of \kbd{*AVMA}). It is not necessary for \kbd{*AVMA}
to initially point on the stack: \tet{gclone} is implemented using this mechanism.

\fun{GEN}{icopy_avma}{GEN x, pari_sp av} analogous to \kbd{gcopy\_avma} but simpler:
assume $x$ is a \typ{INT} and return a copy allocated as if initially we had
\kbd{avma} equal to \kbd{av}. There is no need to pass a pointer and update the value
of the second argument: the new (fictitious) \kbd{avma} is just the return value
(typecast to \kbd{pari\_sp}).

\subsec{Debugging the PARI stack}

\fun{int}{chk_gerepileupto}{GEN x} returns 1 if \kbd{x} is suitable for
\kbd{gerepileupto}, and 0 otherwise. In the latter case, print a warning
explaining the problem.

\fun{void}{dbg_gerepile}{pari_sp ltop} outputs the list of all objects on the
stack between \kbd{avma} and \kbd{ltop}, i.e. the ones that would be inspected
in a call to \kbd{gerepile(...,ltop,...)}.

\fun{void}{dbg_gerepileupto}{GEN q} outputs the list of all objects on the
stack that would be inspected in a call to \kbd{gerepileupto(...,q)}.

\subsec{Copies}

\fun{GEN}{gcopy}{GEN x} creates a new copy of $x$ on the stack.

\fun{GEN}{gcopy_lg}{GEN x, long l} creates a new copy of $x$
on the stack, pretending that \kbd{lg(x)} is $l$, which must be less than or
equal to \kbd{lg(x)}. If equal, the function is equivalent to \kbd{gcopy(x)}.

\fun{int}{isonstack}{GEN x} \kbd{true} iff $x$ belongs to the stack.

\fun{void}{copyifstack}{GEN x, GEN y} sets \kbd{y = gcopy(x)} if
$x$ belongs to the stack, and \kbd{y = x} otherwise. This macro evaluates
its arguments once, contrary to
\bprog
  y = isonstack(x)? gcopy(x): x;
@eprog

\fun{void}{icopyifstack}{GEN x, GEN y} as \kbd{copyifstack} assuming \kbd{x}
is a \typ{INT}.

\subsec{Simplify}

\fun{GEN}{simplify}{GEN x} you should not need that function in library mode.
One rather uses:

\fun{GEN}{simplify_shallow}{GEN x} shallow, faster, version of \tet{simplify}.

\section{The PARI heap}
\subsec{Introduction}

It is implemented as a doubly-linked list of \kbd{malloc}'ed blocks of
memory, equipped with reference counts. Each block has type \kbd{GEN} but need
not be a valid \kbd{GEN}: it is a chunk of data preceded by a hidden header
(meaning that we allocate $x$ and return $x + \kbd{header size}$). A
\tev{clone}, created by \tet{gclone}, is a block which is a valid \kbd{GEN}
and whose \emph{clone bit} is set.

\subsec{Public interface}

\fun{GEN}{newblock}{size_t n} allocates a block of $n$ \emph{words} (not bytes).

\fun{void}{killblock}{GEN x} deletes the block~$x$ created by \kbd{newblock}.
Fatal error if $x$ not a block.

\fun{GEN}{gclone}{GEN x} creates a new permanent copy of $x$ on the heap
(allocated using \kbd{newblock}). The \emph{clone bit} of the result is set.

\fun{void}{gunclone}{GEN x} deletes a clone. In the current implementation,
this is an alias for \kbd{killblock}, but it is cleaner to kill clones (valid
\kbd{GEN}s) using this function, and other blocks using \kbd{killblock}.

\fun{void}{gunclone_deep}{GEN x} is only useful in the context of the GP
interpreter which may replace arbitrary components of container types
(\typ{VEC}, \typ{COL}, \typ{MAT}, \typ{LIST}) by clones. If $x$ is such
a container, the function recursively deletes all clones among the components
of $x$, then unclones $x$. Useless in library mode: simply use
\kbd{gunclone}.

\fun{void}{traverseheap}{void(*f)(GEN, void *), void *data} this applies
\kbd{f($x$, data)} to each object $x$ on the PARI heap, most recent
first. Mostly for debugging purposes.

\fun{GEN}{getheap}{} a simple wrapper around \kbd{traverseheap}. Returns  a
two-component row vector giving the number of objects on the heap and the
amount of memory they occupy in long words.

\subsec{Implementation note} The hidden block header is manipulated using the
following private functions:

\fun{void*}{bl_base}{GEN x} returns the pointer that was actually allocated
by \kbd{malloc} (can be freed).

\fun{long}{bl_refc}{GEN x} the reference count of $x$: the number of pointers
to this block. Decremented in \kbd{killblock}, incremented by the private
function \fun{void}{gclone_refc}{GEN x}; block is freed when the reference
count reaches $0$.

\fun{long}{bl_num}{GEN x} the index of this block in the list of all blocks
allocated so far (including freed blocks). Uniquely identifies a block until
$2^\B$ blocks have been allocated and this wraps around.

\fun{GEN}{bl_next}{GEN x} the block \emph{after} $x$ in the linked list of
blocks (\kbd{NULL} if $x$ is the last block allocated not yet killed).

\fun{GEN}{bl_prev}{GEN x} the block allocated \emph{before} $x$ (never
\kbd{NULL}).

We documented the last four routines as functions for clarity (and type
checking) but they are actually macros yielding valid lvalues. It is allowed
to write \kbd{bl\_refc(x)++} for instance.

\section{Handling user and temp variables}
Low-level implementation of user / temporary variables is liable to change. We
describe it nevertheless for completeness. Currently variables are
implemented by a single array of values divided in 3 zones: 0--\kbd{nvar}
(user variables), \kbd{max\_avail}--\kbd{MAXVARN} (temporary variables),
and \kbd{nvar+1}--\kbd{max\_avail-1} (pool of free variable numbers).

\subsec{Low-level}

\fun{void}{pari_var_init}{}: a small part of \kbd{pari\_init}. Resets
variable counters \kbd{nvar} and \kbd{max\_avail}, notwithstanding existing
variables! In effect, this even deletes \kbd{x}. Don't use it.

\fun{long}{pari_var_next}{}: returns \kbd{nvar}, the number of the next user
variable we can create.

\fun{long}{pari_var_next_temp}{} returns \kbd{max\_avail}, the number of the
next temp variable we can create.

\fun{void}{pari_var_create}{entree *ep} low-level initialization of an
\kbd{EpVAR}.

\noindent The obsolete function \fun{long}{manage_var}{long n, entree *ep}
is kept for backward compatibility only. Don't use it.

\subsec{User variables}

\fun{long}{fetch_user_var}{char *s} returns a user variable whose name
is \kbd{s}, creating it is needed (and using an existing variable otherwise).
Returns its variable number.

\fun{entree*}{fetch_named_var}{char *s} as \kbd{fetch\_user\_var}, but
returns an \kbd{entree*} suitable for inclusion in the interpreter hashlists
of symbols, not a variable number. \kbd{fetch\_user\_var} is a trivial
wrapper.

\fun{GEN}{fetch_var_value}{long v} returns a shallow copy of the
current value of the variable numbered $v$. Return \kbd{NULL} for a temporary
variable.

\fun{entree*}{is_entry}{const char *s} returns the \kbd{entree*} associated
to an identifier \kbd{s} (variable or function), from the interpreter
hashtables. Return \kbd{NULL} is the identifier is unknown.

\subsec{Temporary variables}

\fun{long}{fetch_var}{void} returns the number of a new temporary variable
(decreasing \kbd{max\_avail}).

\fun{long}{delete_var}{void} delete latest temp variable created and return
the number of previous one.

\fun{void}{name_var}{long n, char *s} rename temporary variable number
\kbd{n} to \kbd{s}; mostly useful for nicer printout. Error when trying to
rename a user variable: use \kbd{fetch\_named\_var} to get a user variable of
the right name in the first place.

\section{Adding functions to PARI}
\subsec{Nota Bene}
%
As mentioned in the \kbd{COPYING} file, modified versions of the PARI package
can be distributed under the conditions of the GNU General Public License. If
you do modify PARI, however, it is certainly for a good reason, and we
would like to know about it, so that everyone can benefit from your changes.
There is then a good chance that your improvements are incorporated into the
next release.

We classify changes to PARI into four rough classes, where changes of the
first three types are almost certain to be accepted. The first type includes
all improvements to the documentation, in a broad sense. This includes
correcting typos or inaccuracies of course, but also items which are not
really covered in this document, e.g.~if you happen to write a tutorial,
or pieces of code exemplifying fine points unduly omitted in the present
manual.

The second type is to expand or modify the configuration routines and skeleton
files (the \kbd{Configure} script and anything in the \kbd{config/}
subdirectory) so that compilation is possible (or easier, or more efficient)
on an operating system previously not catered for. This includes discovering
and removing idiosyncrasies in the code that would hinder its portability.

The third type is to modify existing (mathematical) code, either to correct
bugs, to add new functionality to existing functions, or to improve their
efficiency.

Finally the last type is to add new functions to PARI. We explain here how
to do this, so that in particular the new function can be called from \kbd{gp}.

\subsec{Coding guidelines}\label{se:coding_guidelines}
\noindent
Code your function in a file of its own, using as a guide other functions
in the PARI sources. One important thing to remember is to clean the stack
before exiting your main function, since otherwise successive calls to
the function clutters the stack with unnecessary garbage, and stack
overflow occurs sooner. Also, if it returns a \kbd{GEN} and you want it
to be accessible to \kbd{gp}, you have to make sure this \kbd{GEN} is
suitable for \kbd{gerepileupto} (see \secref{se:garbage}).

If error messages or warnings are to be generated in your function, use
\kbd{pari\_err} and \kbd{pari\_warn} respectively.
Recall that \kbd{pari\_err} does not return but ends with a \kbd{longjmp}
statement. As well, instead of explicit \kbd{printf}~/ \kbd{fprintf}
statements, use the following encapsulated variants:

\fun{void}{pari_putc}{char c}: write character \kbd{c} to the output stream.

\fun{void}{pari_puts}{char *s}: write \kbd{s} to the output stream.

\fun{void}{pari_printf}{const char *fmt, ...}: write following arguments to the
output stream, according to the conversion specifications in format \kbd{fmt}
(see \tet{printf}).

\fun{void}{err_printf}{char *s}: as \tet{pari_printf}, writing to PARI's
current error stream.

\fun{void}{err_flush}{void} flush error stream.

Declare all public functions in an appropriate header file, if you
want to access them from C. The other functions should be declared
\kbd{static} in your file.

Your function is now ready to be used in library mode after compilation and
creation of the library. If possible, compile it as a shared library (see
the \kbd{Makefile} coming with the \kbd{extgcd} example in the
distribution). It is however still inaccessible from \kbd{gp}.\smallskip

\subsec{Interlude: parser codes}
\label{se:gp.interface}
A \idx{parser code} is a character string describing all the GP parser
needs to know about the function prototype. It contains a sequence of the
following atoms:

\settabs\+\indent&\kbd{Dxxx}\quad&\cr

\noindent $\bullet$ Return type: \kbd{GEN} by default (must be valid for
\kbd{gerepileupto}), otherwise the following can appear as the \emph{first}
char of the code string:
%
\+& \kbd{i} & return \kbd{int}\cr
\+& \kbd{l} & return \kbd{long}\cr
\+& \kbd{v} & return \kbd{void}\cr
\+& \kbd{m} & return \kbd{GEN}. Here it is allowed to directly return
a component of the input (obviously \cr
\+&&\quad  not suitable for \kbd{gerepileupto}). Used for member functions, to avoid costly copies.\cr

\noindent$\bullet$ Mandatory arguments, appearing in the same order as the
input arguments they describe:
%
\+& \kbd{G} & \kbd{GEN}\cr
\+& \kbd{\&}& \kbd{*GEN}\cr
\+& \kbd{L} & long {\rm (we implicitly typecast \kbd{int} to \kbd{long})}\cr
\+& \kbd{V} & loop variable\cr
\+& \kbd{n} & variable, expects a \idx{variable number} (a \kbd{long}, not an
\kbd{*entree})\cr
\+& \kbd{r} & raw input (treated as a string without quotes). Quoted %
 args are copied as strings\cr
\+&&\quad Stops at first unquoted \kbd{')'} or \kbd{','}. Special chars can
be quoted using '\kbd{\bs}'\cr
\+&&\quad Example: \kbd{aa"b\bs n)"c} yields the string \kbd{"aab\bs{n})c"}\cr
\+& \kbd{s} & expanded string. Example: \kbd{Pi"x"2} yields \kbd{"3.142x2"}\cr
\+&&\quad Unquoted components can be of any PARI type, converted to string
          following\cr
\+&&\quad current output format\cr
\+& \kbd{I} & closure whose value is ignored, as in \kbd{for} loops,\cr
\+&&\quad to be processed by \fun{void}{closure_evalvoid}{GEN C}\cr
\+& \kbd{E} & closure whose value is used, as in \kbd{sum} loops,\cr
\+&&\quad to be processed by \fun{void}{closure_evalgen}{GEN C}\cr

\noindent A \tev{closure} is a GP function in compiled (bytecode) form. It
can be efficiently evaluated using the \kbd{closure\_eval}$xxx$ functions.

\noindent$\bullet$ Automatic arguments:
%
\+& \kbd{f} &  Fake \kbd{*long}. C function requires a pointer but we
do not use the resulting \kbd{long}\cr
\+& \kbd{p} &  real precision (default \kbd{realprecision})\cr
\+& \kbd{P} &  series precision (default \kbd{seriesprecision},
 global variable \kbd{precdl} for the library)\cr

\noindent $\bullet$ Syntax requirements, used by functions like
 \kbd{for}, \kbd{sum}, etc.:
%
\+& \kbd{=} & separator \kbd{=} required at this point (between two
arguments)\cr

\noindent$\bullet$ Optional arguments and default values:
%
\+& \kbd{s*} & any number of strings, possibly 0 (see \kbd{s})\cr
\+& \kbd{D\var{xxx}} &  argument can be omitted and has a default value\cr

The \kbd{s*} code reads all remaining arguments in
\tev{string context} (see \secref{se:strings}), and sends a
(\kbd{NULL}-terminated) list of \kbd{GEN*} pointing to these. The automatic
concatenation rules in string context are implemented so that adjacent strings
are read as different arguments, as if they had been comma-separated. For
instance, if the remaining argument sequence is: \kbd{"xx" 1, "yy"}, the
\kbd{s*} atom sends a \kbd{GEN *g = \obr \&a, \&b, \&c, NULL\cbr}, where
$a$, $b$, $c$ are \kbd{GEN}s of type \typ{STR} (content \kbd{"xx"}),
\typ{INT} (equal to $1$) and \typ{STR} (content \kbd{"yy"}).

The format to indicate a default value (atom starts with a \kbd{D}) is
``\kbd{D\var{value},\var{type},}'', where \var{type} is the code for any
mandatory atom (previous group), \var{value} is any valid GP expression
which is converted according to \var{type}, and the ending comma is
mandatory. For instance \kbd{D0,L,} stands for ``this optional argument is
converted to a \kbd{long}, and is \kbd{0} by default''. So if the
user-given argument reads \kbd{1 + 3} at this point, \kbd{4L} is sent to
the function; and \kbd{0L} if the argument is omitted. The following
special notations are available:

\settabs\+\indent\indent&\kbd{Dxxx}\quad& optional \kbd{*GEN},&\cr
\+&\kbd{DG}& optional \kbd{GEN}, & send \kbd{NULL} if argument omitted.\cr

\+&\kbd{D\&}& optional \kbd{*GEN}, send \kbd{NULL} if argument omitted.\cr

\+&\kbd{Dr}& optional raw string, send \kbd{NULL} if argument omitted.\cr

\+&\kbd{Ds}& optional \kbd{char *}, send \kbd{NULL} if argument omitted.\cr

\+&\kbd{DV}& optional \kbd{*entree}, send \kbd{NULL} if argument omitted.\cr

\+&\kbd{DI}& optional closure, send \kbd{NULL} if argument omitted.\cr

\+&\kbd{Dn}& optional variable number, $-1$ if omitted.\cr

\misctitle{Hardcoded limit} C functions using more than 20 arguments are not
supported. Use vectors if you really need that many parameters.

When the function is called under \kbd{gp}, the prototype is scanned and each
time an atom corresponding to a mandatory argument is met, a user-given
argument is read (\kbd{gp} outputs an error message it the argument was
missing). Each time an optional atom is met, a default value is inserted if the
user omits the argument. The ``automatic'' atoms fill in the argument list
transparently, supplying the current value of the corresponding variable (or a
dummy pointer).

For instance, here is how you would code the following prototypes, which
do not involve default values:
\bprog
GEN f(GEN x, GEN y, long prec)   ----> "GGp"
void f(GEN x, GEN y, long prec)  ----> "vGGp"
void f(GEN x, long y, long prec) ----> "vGLp"
long f(GEN x)                    ----> "lG"
int f(long x)                    ----> "iL"
@eprog\noindent
If you want more examples, \kbd{gp} gives you easy access to the parser codes
associated to all GP functions: just type \kbd{\b{h} \var{function}}. You
can then compare with the C prototypes as they stand in \kbd{paridecl.h}.

\misctitle{Remark} If you need to implement complicated control statements
(probably for some improved summation functions), you need to know
how the parser implements closures and lexicals and how the evaluator lets
you deal with them, in particular the \tet{push_lex} and \tet{pop_lex}
functions. Check their descriptions and adapt the source code in
\kbd{language/sumiter.c} and \kbd{language/intnum.c}.

\subsec{Integration with \kbd{gp} as a shared module}

In this section we assume that your Operating System is supported by
\tet{install}. You have written a function in C following the guidelines is
\secref{se:coding_guidelines}; in case the function returns a \kbd{GEN}, it
must satisfy \kbd{gerepileupto} assumptions (see \secref{se:garbage}).

You then succeeded in building it as part of a shared library and want to
finally tell \kbd{gp} about your function. First, find a name for it. It does
not have to match the one used in library mode, but consistency is nice. It
has to be a valid GP identifier, i.e.~use only alphabetic characters, digits
and the underscore character (\kbd{\_}), the first character being
alphabetic.

Then figure out the correct \idx{parser code} corresponding to the function
prototype (as explained in~\secref{se:gp.interface}) and write a GP script
like the following:
\bprog
install(libname, code, gpname, library)
addhelp(gpname, "some help text")
@eprog
\noindent(see \secref{se:addhelp} and~\ref{se:install}). The \idx{addhelp}
part is not mandatory, but very useful if you want others to use your
module. \kbd{libname} is how the function is named in the library,
usually the same name as one visible from C.

Read that file from your \kbd{gp} session, for instance from your
\idx{preferences file} (\secref{se:gprc}), and that's it. You
can now use the new function \var{gpname} under \kbd{gp}, and we would very
much like to hear about it! \smallskip

\misctitle{Example}
A complete description could look like this:
\bprog
{
  install(bnfinit0, "GD0,L,DGp", ClassGroupInit, "libpari.so");
  addhelp(ClassGroupInit, "ClassGroupInit(P,{flag=0},{data=[]}):
    compute the necessary data for ...");
}
@eprog\noindent which means we have a function \kbd{ClassGroupInit} under
\kbd{gp}, which calls the library function \kbd{bnfinit0} . The function has
one mandatory argument, and possibly two more (two \kbd{'D'} in the code),
plus the current real precision. More precisely, the first argument is a
\kbd{GEN}, the second one is converted to a \kbd{long} using \kbd{itos}
(\kbd{0} is passed if it is omitted), and the third one is also a \kbd{GEN},
but we pass \kbd{NULL} if no argument was supplied by the user. This matches
the C prototype (from \kbd{paridecl.h}):
%
\bprog
  GEN bnfinit0(GEN P, long flag, GEN data, long prec)
@eprog\noindent
This function is in fact coded in \kbd{basemath/buch2.c}, and is in this case
completely identical to the GP function \kbd{bnfinit} but \kbd{gp} does not
need to know about this, only that it can be found somewhere in the shared
library \kbd{libpari.so}.

\misctitle{Important note} You see in this example that it is the
function's responsibility to correctly interpret its operands: \kbd{data =
NULL} is interpreted \emph{by the function} as an empty vector. Note that
since \kbd{NULL} is never a valid \kbd{GEN} pointer, this trick always
enables you to distinguish between a default value and actual input: the
user could explicitly supply an empty vector!

\subsec{Library interface for \kbd{install}}

There is a corresponding library interface for this \kbd{install}
functionality, letting you expand the GP parser/evaluator available in the
library with new functions from your C source code. Functions such as
\tet{gp_read_str} may then evaluate a GP expression sequence involving calls
to these new function!

\fun{entree *}{install}{void *f, char *gpname, char *code}

\noindent where \kbd{f} is the (address of the) function (cast to
\kbd{void*}), \kbd{gpname} is the name by which you want to access your
function from within your GP expressions, and \kbd{code} is as above.


\subsec{Integration by patching \kbd{gp}}

If \tet{install} is not available, and installing Linux or a BSD operating
system is not an option (why?), you have to hardcode your function in the
\kbd{gp} binary. Here is what needs to be done:

\item Fetch the complete sources of the PARI distribution.

\item Drop the function source code module in an appropriate directory
(a priori \kbd{src/modules}), and declare all public functions
in \kbd{src/headers/paridecl.h}.

\item Choose a help section and add a file
\kbd{src/functions/\var{section}/\var{gpname}}
containing the following, keeping the notation above:
\bprog
Function:  @com\var{gpname}
Section:   @com\var{section}
C-Name:    @com\var{libname}
Prototype: @com\var{code}
Help:      @com\var{some help text}
@eprog\noindent
(If the help text does not fit on a single line, continuation lines must
start by a whitespace character.) Two GP2C-related fields (\kbd{Description}
and \kbd{Wrapper}) are also available to improve the code GP2C generates when
compiling scripts involving your function. See the GP2C documentation for details.

\item Launch \kbd{Configure}, which should pick up your C files and build an
appropriate \kbd{Makefile}. At this point you can recompile \kbd{gp}, which
will first rebuild the functions database.

\misctitle{Example} We reuse the \kbd{ClassGroupInit} / \kbd{bnfinit0}
from the preceding section. Since the C source code is already part
of PARI, we only need to add a file

 \kbd{functions/number\_fields/ClassGroupInit}

\noindent containing the following:
\bprog
Function: ClassGroupInit
Section: number_fields
C-Name: bnfinit0
Prototype: GD0,L,DGp
Help: ClassGroupInit(P,{flag=0},{tech=[]}): this routine does @com\dots
@eprog\noindent
and recompile \kbd{gp}.

\section{Globals related to PARI configuration}
\subsec{PARI version numbers}

\noindent \tet{paricfg_version_code} encodes in a single \kbd{long}, the Major
and minor version numbers as well as the patchlevel.

\fun{long}{PARI_VERSION}{long M, long m, long p} produces the version code
associated to release $M.m.p$. Each code identifies a unique PARI release,
and corresponds to the natural total order on the set of releases (bigger
code number means more recent release).

\noindent \tet{PARI_VERSION_SHIFT} is the number of bits used to store each of
the integers $M$, $m$, $p$ in the version code.

\noindent \tet{paricfg_vcsversion} is a version string related to the
revision control system used to handle your sources, if any. For instance
\kbd{git-}\emph{commit hash} if compiled from a git repository.

The two character strings \tet{paricfg_version} and \tet{paricfg_buildinfo},
correspond to the first two lines printed by \kbd{gp} just before the
Copyright message.

\fun{GEN}{pari_version}{} returns the version number as a PARI object, a
\typ{VEC} with three \typ{INT} and one \typ{STR} components.

\subsec{Miscellaneous}

\tet{paricfg_datadir}: character string. The location of PARI's \tet{datadir}.

\newpage
\chapter{Arithmetic kernel: Level 0 and 1}

\section{Level 0 kernel (operations on ulongs)}

\subsec{Micro-kernel}
The Level 0 kernel simulates basic operations of the 68020 processor on which
PARI was originally implemented. They need ``global'' \kbd{ulong} variables
\kbd{overflow} (which will contain only 0 or 1) and \kbd{hiremainder} to
function properly. A routine using one of these lowest-level functions
where the description mentions either \kbd{hiremainder} or \kbd{overflow}
must declare the corresponding
\bprog
  LOCAL_HIREMAINDER;  /* provides 'hiremainder' */
  LOCAL_OVERFLOW;     /* provides 'overflow' */
@eprog\noindent
in a declaration block. Variables \kbd{hiremainder} and \kbd{overflow} then
become available in the enclosing block. For instance a loop over the powers
of an \kbd{ulong}~\kbd{p} protected from overflows could read
\bprog
 while (pk < lim)
 {
   LOCAL_HIREMAINDER;
   ...
   pk = mulll(pk, p); if (hiremainder) break;
 }
@eprog\noindent
For most architectures, the functions mentioned below are really chunks of
inlined assembler code, and the above `global' variables are actually
local register values.

\fun{ulong}{addll}{ulong x, ulong y} adds \kbd{x} and \kbd{y}, returns the
lower \B\ bits and puts the carry bit into \kbd{overflow}.

\fun{ulong}{addllx}{ulong x, ulong y} adds \kbd{overflow} to the sum of the
\kbd{x} and \kbd{y}, returns the lower \B\ bits and puts the carry bit into
\kbd{overflow}.

\fun{ulong}{subll}{ulong x, ulong y} subtracts \kbd{x} and \kbd{y}, returns
the lower \B\ bits and put the carry (borrow) bit into \kbd{overflow}.

\fun{ulong}{subllx}{ulong x, ulong y} subtracts \kbd{overflow} from the
difference of \kbd{x} and \kbd{y}, returns the lower \B\ bits and puts the
carry (borrow) bit into \kbd{overflow}.

\fun{int}{bfffo}{ulong x} returns the number of leading zero bits in \kbd{x}.
That is, the number of bit positions by which it would have to be shifted
left until its leftmost bit first becomes equal to~1, which can be between 0
and $\B-1$ for nonzero \kbd{x}. When \kbd{x} is~0, the result is undefined.

\fun{ulong}{mulll}{ulong x, ulong y} multiplies \kbd{x} by \kbd{y}, returns
the lower \B\ bits and stores the high-order \B\ bits into \kbd{hiremainder}.

\fun{ulong}{addmul}{ulong x, ulong y} adds \kbd{hiremainder} to the product
of \kbd{x} and \kbd{y}, returns the lower \B\ bits and stores the high-order
\B\ bits into \kbd{hiremainder}.

\fun{ulong}{divll}{ulong x, ulong y} returns the quotient of
$  \left(\kbd{hiremainder} * 2^{\B}\right) + \kbd{x} $
by \kbd{y} and stores the remainder into \kbd{hiremainder}. An error occurs
if the quotient cannot be represented by an \kbd{ulong}, i.e.~if initially
$\kbd{hiremainder}\ge\kbd{y}$.

\misctitle{Obsolete routines} Those functions are awkward and no longer used; they
are only provided for backward compatibility:

\fun{ulong}{shiftl}{ulong x, ulong y} returns $x$ shifted left by $y$ bits,
i.e.~\kbd{$x$ << $y$}, where we assume that $0\leq y\leq\B$. The global variable
\kbd{hiremainder} receives the bits that were shifted out,
i.e.~\kbd{$x$ >> $(\B - y)$}.

\fun{ulong}{shiftlr}{ulong x, ulong y} returns $x$ shifted right by $y$ bits,
i.e.~\kbd{$x$ >> $y$}, where we assume that $0\leq y\leq\B$. The global variable
\kbd{hiremainder} receives the bits that were shifted out,
i.e.~\kbd{$x$ << $(\B - y)$}.

\subsec{Modular kernel}
The following routines are not part of the level 0 kernel per se, but
implement modular operations on words in terms of the above. They are written
so that no overflow may occur. Let $m \geq 1$ be the modulus; all operands
representing classes modulo $m$ are assumed to belong to $[0,m-1]$. The
result may be wrong for a number of reasons otherwise: it may not be reduced,
overflow can occur, etc.

\fun{int}{odd}{ulong x} returns 1 if $x$ is odd, and 0 otherwise.

\fun{int}{both_odd}{ulong x, ulong y} returns 1 if $x$ and $y$ are both odd,
and 0 otherwise.

\fun{ulong}{invmod2BIL}{ulong x} returns the smallest
positive representative of $x^{-1}$ mod $2^\B$, assuming $x$ is odd.

\fun{ulong}{Fl_add}{ulong x, ulong y, ulong m} returns the smallest
positive representative of $x + y$ modulo $m$.

\fun{ulong}{Fl_neg}{ulong x, ulong m} returns the smallest
positive representative of $-x$ modulo $m$.

\fun{ulong}{Fl_sub}{ulong x, ulong y, ulong m} returns the smallest
positive representative of $x - y$ modulo $m$.

\fun{long}{Fl_center}{ulong x, ulong m, ulong mo2} returns the representative
in $]-m/2,m/2]$ of $x$ modulo $m$. Assume $0 \leq x < m$ and
$\kbd{mo2}  = m >> 1$.

\fun{ulong}{Fl_mul}{ulong x, ulong y, ulong m} returns the smallest positive
representative of $x y$ modulo $m$.

\fun{ulong}{Fl_sqr}{ulong x, ulong m} returns the smallest positive
representative of $x^2$ modulo $m$.

\fun{ulong}{Fl_inv}{ulong x, ulong m} returns the smallest
positive representative of $x^{-1}$ modulo $m$. If $x$ is not invertible
mod~$m$, raise an exception.

\fun{ulong}{Fl_div}{ulong x, ulong y, ulong m} returns the smallest
positive representative of $x y^{-1}$ modulo $m$. If $y$ is not invertible
mod $m$, raise an exception.

\fun{ulong}{Fl_powu}{ulong x, ulong n, ulong m} returns the smallest
positive representative of $x^n$ modulo $m$.

\fun{ulong}{Fl_sqrt}{ulong x, ulong p} returns the square root of \kbd{x}
modulo \kbd{p} (smallest positive representative). Assumes \kbd{p} to be
prime, and \kbd{x} to be a square modulo \kbd{p}.

\fun{ulong}{Fl_order}{ulong a, ulong o, ulong p} returns the order of the
\typ{Fp} \kbd{a}. It is assumed that \kbd{o} is a multiple of the order of
\kbd{a}, $0$ being allowed (no non-trivial information).

\fun{ulong}{random_Fl}{ulong p} returns a pseudo-random integer uniformly
distributed in $0, 1, \dots p-1$.

\fun{ulong}{pgener_Fl}{ulong p} returns a \idx{primitive root} modulo \kbd{p},
assuming \kbd{p} is prime.

\fun{ulong}{pgener_Zl}{ulong p} returns a primitive root modulo $p^k$, $k
> 1$, assuming $p$ is an odd prime. On a 64-bit machine,
this function may fail and raise an exception, if $p > 2^{63}$; namely
when $g := \kbd{pgener\_Fl}(p)$ is not a primitive element and $g + p$ no
longer fits in an \kbd{ulong}. (It turns out that this cannot happen on a
32-bit architecture.) Use \kbd{gener\_Fp} if this is a problem.

\fun{ulong}{pgener_Fl_local}{ulong p, GEN L}, see \kbd{gener\_Fp\_local},
\kbd{L} is an \kbd{Flv}.

\subsec{Switching between Fl\_xxx and standard operators}

Even though the \kbd{Fl\_xxx} routines are efficient, they are slower than
ordinary \kbd{long} operations, using the standard \kbd{+}, \kbd{\%}, etc.
operators.
The following macro is used to choose in a portable way the most efficient
functions for given operands:

\fun{int}{SMALL_ULONG}{ulong p} true if $2p^2 <2^\B$. In that case, it is
possible to use ordinary operators efficiently. If $p < 2^\B$, one
may still use the \kbd{Fl\_xxx} routines. Otherwise, one must use generic
routines. For instance, the scalar product of the \kbd{GEN}s $x$ and $y$ mod
$p$ could be computed as follows.
\bprog
    long i, l = lg(x);
    if (lgefint(p) > 3)
    { /* arbitrary */
      GEN s = gen_0;
      for (i = 1; i < l; i++) s = addii(s, mulii(gel(x,i), gel(y,i)));
      return modii(s, p).
    }
    else
    {
      ulong s = 0, pp = itou(p);
      x = ZV_to_Flv(x, pp);
      y = ZV_to_Flv(y, pp);
      if (SMALL_ULONG(pp))
      { /* very small */
        for (i = 1; i < l; i++)
        {
          s += x[i] * y[i];
          if (s & HIGHBIT) s %= pp;
        }
        s %= pp;
      }
      else
      { /* small */
        for (i = 1; i < l; i++)
          s = Fl_add(s, Fl_mul(x[i], y[i], pp), pp);
      }
      return utoi(s);
    }
@eprog\noindent
In effect, we have three versions of the same code: very small, small, and
arbitrary inputs. The very small and arbitrary variants use lazy reduction
and reduce only when it becomes necessary: when overflow might occur (very
small), and at the very end (very small, arbitrary).

\section{Level 1 kernel (operations on longs, integers and reals)}

\misctitle{Note} Some functions consist of an elementary operation,
immediately followed by an assignment statement. They will be introduced as
in the following example:

\fun{GEN}{gadd[z]}{GEN x, GEN y[, GEN z]} followed by the explicit
description of the function

\fun{GEN}{gadd}{GEN x, GEN y}

\noindent which creates its result on the stack, returning a \kbd{GEN} pointer
to it, and the parts in brackets indicate that there exists also a function

\fun{void}{gaddz}{GEN x, GEN y, GEN z}

\noindent which assigns its result to the pre-existing object
\kbd{z}, leaving the stack unchanged. These assignment variants are kept for
backward compatibility but are inefficient: don't use them.

\subsec{Creation}

\fun{GEN}{cgeti}{long n} allocates memory on the PARI stack for a \typ{INT}
of length~\kbd{n}, and initializes its first codeword. Identical to
\kbd{cgetg(n,\typ{INT})}.

\fun{GEN}{cgetipos}{long n} allocates memory on the PARI stack for a
\typ{INT} of length~\kbd{n}, and initializes its two codewords. The sign
of \kbd{n} is set to $1$.

\fun{GEN}{cgetineg}{long n} allocates memory on the PARI stack for a negative
\typ{INT} of length~\kbd{n}, and initializes its two codewords. The sign
of \kbd{n} is set to $-1$.

\fun{GEN}{cgetr}{long n} allocates memory on the PARI stack for a \typ{REAL}
of length~\kbd{n}, and initializes its first codeword. Identical to
\kbd{cgetg(n,\typ{REAL})}.

\fun{GEN}{cgetc}{long n} allocates memory on the PARI stack for a
\typ{COMPLEX}, whose real and imaginary parts are \typ{REAL}s
of length~\kbd{n}.

\fun{GEN}{real_1}{long prec} create a \typ{REAL} equal to $1$ to \kbd{prec}
words of accuracy.

\fun{GEN}{real_m1}{long prec} create a \typ{REAL} equal to $-1$ to \kbd{prec}
words of accuracy.

\fun{GEN}{real_0_bit}{long bit} create a \typ{REAL} equal to $0$ with
exponent $-\kbd{bit}$.

\fun{GEN}{real_0}{long prec} is a shorthand for
\bprog
  real_0_bit( -bit_accuracy(prec) )
@eprog

\fun{GEN}{int2n}{long n} creates a \typ{INT} equal to \kbd{1<<n} (i.e
$2^n$ if $n \geq 0$, and $0$ otherwise).

\fun{GEN}{int2u}{ulong n} creates a \typ{INT} equal to $2^n$.

\fun{GEN}{real2n}{long n, long prec} create a \typ{REAL} equal to $2^n$
to \kbd{prec} words of accuracy.

\fun{GEN}{strtoi}{char *s} convert the character string \kbd{s} to a
non-negative \typ{INT}. The string \kbd{s} consists exclusively of digits (no
leading sign).

\fun{GEN}{strtor}{char *s, long prec} convert the character string \kbd{s}
to a non-negative \typ{REAL} of precision \kbd{prec}.
The string \kbd{s} consists exclusively of digits and optional decimal
point and exponent (no leading sign).

\subsec{Assignment}
In this section, the \kbd{z} argument in the \kbd{z}-functions must be of type
\typ{INT} or~\typ{REAL}.

\fun{void}{mpaff}{GEN x, GEN z} assigns \kbd{x} into~\kbd{z} (where \kbd{x}
and \kbd{z} are \typ{INT} or \typ{REAL}).
Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affii}{GEN x, GEN z} assigns the \typ{INT} \kbd{x} into the
\typ{INT}~\kbd{z}.

\fun{void}{affir}{GEN x, GEN z} assigns the \typ{INT} \kbd{x} into the
\typ{REAL}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affiz}{GEN x, GEN z} assigns \typ{INT}~\kbd{x} into \typ{INT} or
\typ{REAL}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affsi}{long s, GEN z} assigns the \kbd{long}~\kbd{s} into the
\typ{INT}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affsr}{long s, GEN z} assigns the \kbd{long}~\kbd{s} into the
\typ{REAL}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affsz}{long s, GEN z} assigns the \kbd{long}~\kbd{s} into the
\typ{INT} or \typ{REAL}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affui}{ulong u, GEN z} assigns the \kbd{ulong}~\kbd{u} into the
\typ{INT}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affur}{ulong u, GEN z} assigns the \kbd{ulong}~\kbd{u} into the
\typ{REAL}~\kbd{z}. Assumes that $\kbd{lg(z)} > 2$.

\fun{void}{affrr}{GEN x, GEN z} assigns the \typ{REAL}~\kbd{x} into the
\typ{REAL}~\kbd{z}.

\fun{void}{affgr}{GEN x, GEN z} assigns the scalar \kbd{x} into the
\typ{REAL}~\kbd{z}, if possible.

\noindent The function \kbd{affrs} and \kbd{affri} do not exist. So don't use
them.

\fun{void}{affrr_fixlg}{GEN y, GEN z} a variant of \kbd{affrr}. First shorten
$z$ so that it is no longer than $y$, then assigns $y$ to $z$. This is used
in the following scenario: room is reserved for the result but, due to
cancellation, fewer words of accuracy are available than had been
anticipated; instead of appending meaningless $0$s to the mantissa, we store
what was actually computed.

Note that shortening $z$ is not quite straightforward, since \kbd{setlg(z, ly)}
would leave garbage on the stack, which \kbd{gerepile} might later inspect.
It is done using

\fun{void}{fixlg}{GEN z, long ly} see \tet{stackdummy} and the examples that
follow.

\subsec{Copy}

\fun{GEN}{icopy}{GEN x} copy relevant words of the \typ{INT}~\kbd{x} on the
stack: the length and effective length of the copy are equal.

\fun{GEN}{rcopy}{GEN x} copy the \typ{REAL}~\kbd{x} on the stack.

\fun{GEN}{leafcopy}{GEN x} copy the leaf~\kbd{x} on the
stack (works in particular for \typ{INT}s and \typ{REAL}s).
Contrary to \kbd{icopy}, \kbd{leafcopy} preserves the original
length of a \typ{INT}. The obsolete form \fun{GEN}{mpcopy}{GEN x}
is still provided for backward compatibility.

This function also works on recursive types, copying them as if they were leaves,
i.e.~making a shallow copy in that case: the components of the copy point to the
same data as the component of the source; see also \kbd{shallowcopy}.

\subsec{Conversions}

\fun{GEN}{itor}{GEN x, long prec} converts the \typ{INT}~\kbd{x} to a
\typ{REAL} of length \kbd{prec} and return the latter.
Assumes that $\kbd{prec} > 2$.

\fun{long}{itos}{GEN x} converts the \typ{INT}~\kbd{x} to a \kbd{long} if
possible, otherwise raise an exception.

\fun{long}{itos_or_0}{GEN x} converts the \typ{INT}~\kbd{x} to a \kbd{long} if
possible, otherwise return $0$.

\fun{int}{is_bigint}{GEN n} true if \kbd{itos(n)} would succeed.

\fun{int}{is_bigint_lg}{GEN n, long l} true if \kbd{itos(n)} would succeed.
Assumes \kbd{lgefint(n)} is equal to \kbd{l}.

\fun{ulong}{itou}{GEN x} converts the \typ{INT}~\kbd{|x|} to an \kbd{ulong} if
possible, otherwise raise an exception.

\fun{long}{itou_or_0}{GEN x} converts the \typ{INT}~\kbd{|x|} to an
\kbd{ulong} if possible, otherwise return $0$.

\fun{GEN}{stoi}{long s} creates the \typ{INT} corresponding to the
\kbd{long}~\kbd{s}.

\fun{GEN}{stor}{long s, long prec} converts the \kbd{long}~\kbd{s} into a
\typ{REAL} of length \kbd{prec} and return the latter. Assumes that
$\kbd{prec} > 2$.

\fun{GEN}{utoi}{ulong s} converts the \kbd{ulong}~\kbd{s} into a \typ{INT}
and return the latter.

\fun{GEN}{utoipos}{ulong s} converts the \emph{non-zero} \kbd{ulong}~\kbd{s}
into a \typ{INT} and return the latter.

\fun{GEN}{utoineg}{ulong s} converts the \emph{non-zero} \kbd{ulong}~\kbd{s}
into the \typ{INT} $-s$ and return the latter.

\fun{GEN}{utor}{ulong s, long prec} converts the \kbd{ulong}~\kbd{s} into a
\typ{REAL} of length \kbd{prec} and return the latter. Assumes that
$\kbd{prec} > 2$.

\fun{GEN}{rtor}{GEN x, long prec} converts the \typ{REAL}~\kbd{x} to a
\typ{REAL} of length \kbd{prec} and return the latter. If
$\kbd{prec} < \kbd{lg(x)}$, round properly. If $\kbd{prec} > \kbd{lg(x)}$,
pad with zeroes. Assumes that $\kbd{prec} > 2$.

\noindent The following function is also available as a special case of
\tet{mkintn}:

\fun{GEN}{uu32toi}{ulong a, ulong b} returns the \kbd{GEN} equal to $2^{32} a +
b$, \emph{assuming} that $a,b < 2^{32}$. This does not depend on
\kbd{sizeof(long)}: the behavior is as above on both $32$ and $64$-bit
machines.

\fun{GEN}{uutoi}{ulong a, ulong b} returns the \kbd{GEN} equal to
$2^{\B} a + b$.

\fun{GEN}{uutoineg}{ulong a, ulong b} returns the \kbd{GEN} equal to
$-(2^{\B} a + b)$.

\subsec{Integer parts}
The following four functions implement the conversion from \typ{REAL} to
\typ{INT} using standard rounding modes. Contrary to usual semantics
(complement the mantissa with an infinite number of 0), they will raise an
error \emph{precision loss in truncation} if the \typ{REAL} represents a
range containing more than one integer.

\fun{GEN}{ceilr}{GEN x} smallest integer larger or equal
to the \typ{REAL}~\kbd{x} (i.e.~the \kbd{ceil} function).

\fun{GEN}{floorr}{GEN x} largest integer smaller or equal to the
\typ{REAL}~\kbd{x} (i.e.~the \kbd{floor} function).

\fun{GEN}{roundr}{GEN x} rounds the \typ{REAL} \kbd{x} to the nearest integer
(towards~$+\infty$ in case of tie).

\fun{GEN}{truncr}{GEN x} truncates the \typ{REAL}~\kbd{x} (not the same as
\kbd{floorr} if \kbd{x} is negative).

The following four function are analogous, but can also treat the trivial
case when the argument is a \typ{INT}:

\fun{GEN}{mpceil}{GEN x}
as \kbd{ceilr} except that \kbd{x} may be a \typ{INT}.

\fun{GEN}{mpfloor}{GEN x}
as \kbd{floorr} except that \kbd{x} may be a \typ{INT}.

\fun{GEN}{mpround}{GEN x}
as \kbd{roundr} except that \kbd{x} may be a \typ{INT}.

\fun{GEN}{mptrunc}{GEN x}
as \kbd{truncr} except that \kbd{x} may be a \typ{INT}.

\fun{GEN}{diviiround}{GEN x, GEN y} if \kbd{x} and \kbd{y} are \typ{INT}s,
returns the quotient $\kbd{x}/\kbd{y}$ of \kbd{x} and~\kbd{y}, rounded to
the nearest integer. If $\kbd{x}/\kbd{y}$ falls exactly halfway between
two consecutive integers, then it is rounded towards~$+\infty$ (as for
\tet{roundr}).

\fun{GEN}{ceil_safe}{GEN x}, \kbd{x} being a real number (not necessarily a
\typ{REAL}) returns the smallest integer which is larger than any possible
incarnation of \kbd{x}. (Recall that a \typ{REAL} represents an interval of
possible values.) Note that \kbd{gceil} raises an exception if the input accuracy
is too low compared to its magnitude.

\fun{GEN}{floor_safe}{GEN x}, \kbd{x} being a real number (not necessarily a
\typ{REAL}) returns the largest integer which is smaller than any possible
incarnation of \kbd{x}. (Recall that a \typ{REAL} represents an interval of
possible values.) Note that \kbd{gfloor} raises an exception if the input
accuracy is too low compared to its magnitude.

\fun{GEN}{trunc_safe}{GEN x}, \kbd{x} being a real number (not necessarily a
\typ{REAL}) returns the integer with the largest absolute value, which is closer
to $0$ than any possible incarnation of \kbd{x}. (Recall that a \typ{REAL}
represents an interval of possible values.)

\fun{GEN}{roundr_safe}{GEN x} rounds the \typ{REAL} \kbd{x} to the nearest
integer (towards~$+\infty$). Complement the mantissa with an infinite number
of $0$ before rounding, hence never raise an exception.

\subsec{$2$-adic valuations and shifts}

\fun{long}{vals}{long s} 2-adic valuation of the \kbd{long}~\kbd{s}. Returns
$-1$ if \kbd{s} is equal to 0.

\fun{long}{vali}{GEN x} 2-adic valuation of the \typ{INT}~\kbd{x}. Returns $-1$
if \kbd{x} is equal to 0.

\fun{GEN}{mpshift}{GEN x, long n} shifts the~\typ{INT} or
\typ{REAL} \kbd{x} by~\kbd{n}. If \kbd{n} is positive, this is a left shift,
i.e.~multiplication by $2^{\kbd{n}}$. If \kbd{n} is negative, it is a right
shift by~$-\kbd{n}$, which amounts to the truncation of the quotient of \kbd{x}
by~$2^{-\kbd{n}}$.

\fun{GEN}{shifti}{GEN x, long n} shifts the \typ{INT}~$x$ by~$n$.

\fun{GEN}{shiftr}{GEN x, long n} shifts the \typ{REAL}~$x$ by~$n$.

\fun{GEN}{trunc2nr}{GEN x, long n} given a \typ{REAL} $x$, returns
\kbd{truncr(shiftr(x,n))}, but faster, without leaving garbage on the stack
and never raising a \emph{precision loss in truncation} error.
Called by \tet{gtrunc2n}.

\fun{GEN}{trunc2nr_lg}{GEN x, long lx, long n} given a \typ{REAL} $x$, returns
\kbd{trunc2nr(x,n)}, pretending that the length of $x$ is \kbd{lx}, which must be
$\leq \kbd{lg}(x)$.

\misctitle{Low-level} In the following two functions, $s$(ource) and $t$(arget)
need not be valid \kbd{GEN}s (in practice, they usually point to some part of a
\typ{REAL} mantissa): they are considered as arrays of words representing some
mantissa, and we shift globally $s$ by $n > 0$ bits, storing the result in
$t$. We assume that $m\leq M$ and only access $s[m], s[m+1],\ldots s[M]$
(read) and likewise for $t$ (write); we may have $s = t$ but more general
overlaps are not allowed. The word $f$ is concatenated to $s$ to supply extra
bits.

\fun{void}{shift_left}{GEN t, GEN s, long m, long M, ulong f, ulong n}
shifts the mantissa
$$s[m], s[m+1],\ldots s[M], f$$
left by $n$ bits.

\fun{void}{shift_right}{GEN t, GEN s, long m, long M, ulong f, ulong n}
shifts the mantissa
$$f, s[m], s[m+1],\ldots s[M]$$
right by $n$ bits.

\subsec{Valuations}
\fun{long}{Z_pvalrem}{GEN x, GEN p, GEN *r} applied to \typ{INT}s
$\kbd{x}\neq 0$ and~\kbd{p}, $|\kbd{p}| > 1$, returns the highest
exponent $e$ such that $\kbd{p}^{e}$ divides~\kbd{x}. The quotient
$\kbd{x}/\kbd{p}^{e}$ is returned in~\kbd{*r}. In particular, if \kbd{p} is a
prime, this returns the valuation at \kbd{p} of~\kbd{x}, and \kbd{*r} is
the prime-to-\kbd{p} part of~\kbd{x}.

\fun{long}{Z_pval}{GEN x, GEN p} as \kbd{Z\_pvalrem} but only returns the
``valuation''.

\fun{long}{Z_lvalrem}{GEN x, ulong p, GEN *r} as \kbd{Z\_pvalrem},
except that \kbd{p} is an \kbd{ulong} ($\kbd{p} > 1$).

\fun{long}{Z_lval}{GEN x, ulong p} as \kbd{Z\_pval},
except that \kbd{p} is an \kbd{ulong} ($\kbd{p} > 1$).

\fun{long}{u_lvalrem}{ulong x, ulong p, ulong *r} as \kbd{Z\_pvalrem},
except the inputs/outputs are now \kbd{ulong}s.

\fun{long}{u_pvalrem}{ulong x, GEN p, ulong *r} as \kbd{Z\_pvalrem},
except \kbd{x} and \kbd{r} are now \kbd{ulong}s.

\fun{long}{u_lval}{ulong x, ulong p} as \kbd{Z\_pval},
except the inputs are now \kbd{ulong}s.

\fun{long}{u_pval}{ulong x, GEN p} as \kbd{Z\_pval},
except \kbd{x} is now an \kbd{ulong}.

\fun{long}{z_lval}{long x, ulong p} as \kbd{u\_lval}, for signed \kbd{x}.

\fun{long}{z_lvalrem}{long x, ulong p} as \kbd{u\_lvalrem}, for signed \kbd{x}.

\fun{long}{z_pval}{long x, GEN p} as \kbd{Z\_pval},
except \kbd{x} is now a \kbd{long}.

\fun{long}{z_pvalrem}{long x, GEN p} as \kbd{Z\_pvalrem},
except \kbd{x} is now a \kbd{long}.

\fun{long}{Q_pval}{GEN x, GEN p} valuation at the \typ{INT} \kbd{p}
of the \typ{INT} or \typ{FRAC}~\kbd{x}.

\fun{long}{factorial_lval}{ulong n, ulong p} returns $v_p(n!)$, assuming
$p$ is prime.


The following convenience functions generalize \kbd{Z\_pval} and its variants
to ``containers'' (\kbd{ZV} and \kbd{ZX}):


\fun{long}{ZV_pvalrem}{GEN x, GEN p, GEN *r} $x$ being a \kbd{ZV} (a vector
of \typ{INT}s), return the min $v$ of the valuations of its components and
set \kbd{*r} to $x/p^v$. Infinite loop if $x$ is the zero vector.
This function is not stack clean.

\fun{long}{ZV_pval}{GEN x, GEN p} as \kbd{ZV\_pvalrem} but only returns the
``valuation''.

\fun{long}{ZV_lvalrem}{GEN x, ulong p, GEN *px} as \kbd{ZV\_pvalrem},
except that \kbd{p} is an \kbd{ulong} ($\kbd{p} > 1$).
This function is not stack-clean.

\fun{long}{ZV_lval}{GEN x, ulong p} as \kbd{ZV\_pval},
except that \kbd{p} is an \kbd{ulong} ($\kbd{p} > 1$).


\fun{long}{ZX_pvalrem}{GEN x, GEN p, GEN *r} as \kbd{ZV\_pvalrem}, for
a \kbd{ZX} $x$ (a \typ{POL} with \typ{INT} coefficients).
This function is not stack-clean.

\fun{long}{ZX_pval}{GEN x, GEN p} as \kbd{ZV\_pval} for a \kbd{ZX} $x$.

\fun{long}{ZX_lvalrem}{GEN x, ulong p, GEN *px} as \kbd{ZV\_lvalrem},
a \kbd{ZX} $x$.
This function is not stack-clean.

\fun{long}{ZX_lval}{GEN x, ulong p} as \kbd{ZX\_pval},
except that \kbd{p} is an \kbd{ulong} ($\kbd{p} > 1$).

\subsec{Generic unary operators} Let ``\op'' be a unary operation among

\item \key{neg}: negation ($-x$).

\item \key{abs}: absolute value ($|x|$).

\item \key{sqr}: square ($x^2$).

\noindent The names and prototypes of the low-level functions corresponding
to \op\ are as follows. The result is of the same type as~\kbd{x}.

\funno{GEN}{\op i}{GEN x} creates the result of \op\ applied to the
\typ{INT}~\kbd{x}.

\funno{GEN}{\op r}{GEN x} creates the result of \op\ applied to the
\typ{REAL}~\kbd{x}.

\funno{GEN}{mp\op}{GEN x} creates the result of \op\ applied to the
\typ{INT} or \typ{REAL}~\kbd{x}.

\noindent Complete list of available functions:

\fun{GEN}{absi}{GEN x}, \fun{GEN}{absr}{GEN x}, \fun{GEN}{mpabs}{GEN x}

\fun{GEN}{negi}{GEN x}, \fun{GEN}{negr}{GEN x}, \fun{GEN}{mpneg}{GEN x}

\fun{GEN}{sqri}{GEN x}, \fun{GEN}{sqrr}{GEN x}, \fun{GEN}{mpsqr}{GEN x}

\noindent Some miscellaneous routines:

\fun{GEN}{sqrs}{long x} returns $x^2$.

\fun{GEN}{sqru}{ulong x} returns $x^2$.

\subsec{Comparison operators}

\fun{long}{minss}{long x, long y}

\fun{ulong}{minuu}{ulong x, ulong y}

\fun{double}{mindd}{double x, double y} returns the \kbd{min} of $x$ and $y$.


\fun{long}{maxss}{long x, long y}

\fun{ulong}{maxuu}{ulong x, ulong y}

\fun{double}{maxdd}{double x, double y} returns the \kbd{max} of $x$ and $y$.

\smallskip

\fun{int}{mpcmp}{GEN x, GEN y} compares the \typ{INT} or \typ{REAL}~\kbd{x}
to the \typ{INT} or \typ{REAL}~\kbd{y}. The result is the sign of
$\kbd{x}-\kbd{y}$.

\fun{int}{cmpii}{GEN x, GEN y} compares the \typ{INT} \kbd{x} to the
\typ{INT}~\kbd{y}.

\fun{int}{cmpir}{GEN x, GEN y} compares the \typ{INT} \kbd{x} to the
\typ{REAL}~\kbd{y}.

\fun{int}{cmpis}{GEN x, long s} compares the \typ{INT}~\kbd{x} to the
\kbd{long}~\kbd{s}.

\fun{int}{cmpsi}{long s, GEN x} compares the \kbd{long}~\kbd{s} to the
\typ{INT}~\kbd{x}.

\fun{int}{cmpsr}{long s, GEN x} compares the \kbd{long}~\kbd{s} to the
\typ{REAL}~\kbd{x}.

\fun{int}{cmpri}{GEN x, GEN y} compares the \typ{REAL}~\kbd{x} to the
\typ{INT}~\kbd{y}.

\fun{int}{cmprr}{GEN x, GEN y} compares the \typ{REAL}~\kbd{x} to the
\typ{REAL}~\kbd{y}.

\fun{int}{cmprs}{GEN x, long s} compares the \typ{REAL}~\kbd{x} to the
\kbd{long}~\kbd{s}.

\fun{int}{equalii}{GEN x, GEN y} compares the \typ{INT}s \kbd{x} and~\kbd{y}.
The result is $1$ if $\kbd{x} = \kbd{y}$, $0$ otherwise.

\fun{int}{equalrr}{GEN x, GEN y} compares the \typ{REAL}s \kbd{x} and~\kbd{y}.
The result is $1$ if $\kbd{x} = \kbd{y}$, $0$ otherwise. Equality is decided
according to the following rules: all real zeroes are equal, and
different from a non-zero real; two non-zero reals are equal if all their
digits coincide up to the length of the shortest of the two, and the
remaining words in the mantissa of the longest are all $0$.

\fun{int}{equalsi}{long s, GEN x}

\fun{int}{equalis}{GEN x, long s} compare the \typ{INT} \kbd{x} and
the \kbd{long}~\kbd{s}. The result is $1$ if $\kbd{x} = \kbd{y}$, $0$ otherwise.

The remaining comparison operators disregard the sign of their operands:

\fun{int}{equalui}{ulong s, GEN x}

\fun{int}{equaliu}{GEN x, ulong s} compare the absolute value of the
\typ{INT} \kbd{x} and the \kbd{ulong}~\kbd{s}. The result is $1$ if
$|\kbd{x}| = \kbd{y}$, $0$ otherwise.

\fun{int}{cmpui}{ulong u, GEN x}

\fun{int}{cmpiu}{GEN x, ulong u} compare the absolute value of the
\typ{INT} \kbd{x} and the \kbd{ulong}~\kbd{s}.

\fun{int}{absi_cmp}{GEN x, GEN y} compares the \typ{INT}s \kbd{x} and~\kbd{y}.
The result is the sign of $|\kbd{x}| - |\kbd{y}|$.

\fun{int}{absi_equal}{GEN x, GEN y} compares the \typ{INT}s \kbd{x}
and~\kbd{y}. The result is $1$ if $|\kbd{x}| = |\kbd{y}|$, $0$ otherwise.

\fun{int}{absr_cmp}{GEN x, GEN y} compares the \typ{REAL}s \kbd{x} and~\kbd{y}.
The result is the sign of $|\kbd{x}| - |\kbd{y}|$.

\fun{int}{absrnz_equal2n}{GEN x} tests whether a non-zero \typ{REAL} \kbd{x}
is equal to $\pm 2^e$ for some integer $e$.

\fun{int}{absrnz_equal1}{GEN x} tests whether a non-zero \typ{REAL} \kbd{x}
is equal to $\pm 1$.

\subsec{Generic binary operators}\label{se:genbinop} The operators in this
section have arguments of C-type \kbd{GEN}, \kbd{long}, and \kbd{ulong}, and
only \typ{INT} and \typ{REAL} \kbd{GEN}s are allowed. We say an argument is a
real type if it is a \typ{REAL} \kbd{GEN}, and an integer type otherwise. The
result is always a \typ{REAL} unless both \kbd{x} and \kbd{y} are integer
types.

Let ``\op'' be a binary operation among

\item \key{add}: addition (\kbd{x + y}).

\item \key{sub}: subtraction (\kbd{x - y}).

\item \key{mul}: multiplication (\kbd{x * y}).

\item \key{div}: division (\kbd{x / y}). In the case where \kbd{x} and \kbd{y}
are both integer types, the result is the Euclidean quotient, where the
remainder has the same sign as the dividend~\kbd{x}. It is the ordinary
division otherwise. A division-by-$0$ error occurs if \kbd{y} is equal to
$0$.

The last two generic operations are defined only when arguments have integer
types; and the result is a \typ{INT}:

\item \key{rem}: remainder (``\kbd{x \% y}''). The result is the Euclidean
remainder corresponding to \kbd{div},~i.e. its sign is that of the
dividend~\kbd{x}.

\item \key{mod}: true remainder (\kbd{x \% y}). The result is the true
Euclidean remainder, i.e.~non-negative and less than the absolute value
of~\kbd{y}.

\misctitle{Important technical note} The rules given above fixing the output
type (to \typ{REAL} unless both inputs are integer types) are subtly
incompatible with the general rules obeyed by PARI's generic functions, such
as \kbd{gmul} or \kbd{gdiv} for instance: the latter return a result
containing as much information as could be deduced from the inputs, so it is
not true that if $x$ is a \typ{INT} and $y$ a \typ{REAL}, then
\kbd{gmul(x,y)} is always the same as \kbd{mulir(x,y)}. The exception
is $x = 0$, in that case we can deduce that the result is an exact $0$,
so \kbd{gmul} returns \kbd{gen\_0}, while \kbd{mulir} returns a
\typ{REAL} $0$. Specifically, the one resulting from the conversion of
\kbd{gen\_0} to a \typ{REAL} of precision \kbd{precision(y)}, multiplied by
$y$; this determines the exponent of the real $0$ we obtain.

The reason for the discrepancy between the two rules is that we use the two
sets of functions in different contexts: generic functions allow to write
high-level code forgetting about types, letting PARI return results which are
sensible and as simple as possible; type specific functions are used in
kernel programming, where we do care about types and need to maintain strict
consistency: it is much easier to compute the types of results when they are
determined from the types of the inputs only (without taking into account
further arithmetic properties, like being non-0).
\smallskip

The names and prototypes of the low-level functions corresponding
to \op\ are as follows. In this section, the \kbd{z} argument in the
\kbd{z}-functions must be of type \typ{INT} when no \kbd{r} or \kbd{mp}
appears in the argument code (no \typ{REAL} operand is involved, only integer
types), and of type \typ{REAL} otherwise.

\funno{GEN}{mp\op[z]}{GEN x, GEN y[, GEN z]} applies \op\ to
the \typ{INT} or \typ{REAL} \kbd{x} and~\kbd{y}. The function
\kbd{mpdivz} does not exist (its semantic would change drastically
depending on the type of the \kbd{z} argument), and neither do
\kbd{mprem[z]} nor \kbd{mpmod[z]} (specific to integers).

\funno{GEN}{\op si[z]}{long s, GEN x[, GEN z]} applies \op\ to the
\kbd{long}~\kbd{s} and the \typ{INT}~\kbd{x}.
 These functions always return the global constant
\kbd{gen\_0} (not a copy) when the sign of the result is $0$.

\funno{GEN}{\op sr[z]}{long s, GEN x[, GEN z]} applies \op\ to the
\kbd{long}~\kbd{s} and the \typ{REAL}~\kbd{x}.

\funno{GEN}{\op ss[z]}{long s, long t[, GEN z]} applies \op\ to the longs
\kbd{s} and~\kbd{t}. These functions always return the global constant
\kbd{gen\_0} (not a copy) when the sign of the result is $0$.

\funno{GEN}{\op ii[z]}{GEN x, GEN y[, GEN z]} applies \op\ to the
\typ{INT}s \kbd{x} and~\kbd{y}. These functions always return the global
constant \kbd{gen\_0} (not a copy) when the sign of the result is $0$.

\funno{GEN}{\op ir[z]}{GEN x, GEN y[, GEN z]} applies \op\ to the
\typ{INT} \kbd{x} and the \typ{REAL}~\kbd{y}.

\funno{GEN}{\op is[z]}{GEN x, long s[, GEN z]} applies \op\ to the
\typ{INT}~\kbd{x} and the \kbd{long}~\kbd{s}. These functions always return
the global constant \kbd{gen\_0} (not a copy) when the sign of the result
is $0$.

\funno{GEN}{\op ri[z]}{GEN x, GEN y[, GEN z]} applies \op\ to the
\typ{REAL}~\kbd{x} and the \typ{INT}~\kbd{y}.

\funno{GEN}{\op rr[z]}{GEN x, GEN y[, GEN z]} applies \op\ to the
\typ{REAL}s~\kbd{x} and~\kbd{y}.

\funno{GEN}{\op rs[z]}{GEN x, long s[, GEN z]} applies \op\ to the
\typ{REAL}~\kbd{x} and the \kbd{long}~\kbd{s}.

\noindent Some miscellaneous routines:

\fun{long}{expu}{ulong x} assuming $x > 0$, returns the binary exponent of
the real number equal to $x$. This is a special case of \kbd{gexpo}.

\fun{GEN}{adduu}{ulong x, ulong y} adds \kbd{x} by \kbd{y}.

\fun{GEN}{subuu}{ulong x, ulong y} subtracts \kbd{x} by \kbd{y}.

\fun{GEN}{muluu}{ulong x, ulong y} multiplies \kbd{x} by \kbd{y}.

\fun{GEN}{mului}{ulong x, GEN y} multiplies \kbd{x} by \kbd{y}.

\fun{GEN}{muliu}{GEN x, ulong y} multiplies \kbd{x} by \kbd{y}.

\fun{void}{addumului}{ulong a, ulong b, GEN x} return $a + b|X|$.

\fun{GEN}{mulu_interval}{ulong a, ulong b} returns $a(a+1)\cdots b$, assuming
that $a \leq b$. Very inefficient when $a = 0$.

\fun{GEN}{invr}{GEN x} returns the inverse of the non-zero \typ{REAL}~$x$.

\fun{GEN}{truedivii}{GEN x, GEN y} returns the true Euclidean quotient
(with non-negative remainder less than $|y|$).

\fun{GEN}{truedivis}{GEN x, long y} returns the true Euclidean quotient
(with non-negative remainder less than $|y|$).

\fun{GEN}{truedivsi}{long x, GEN y} returns the true Euclidean quotient
(with non-negative remainder less than $|y|$).

\fun{GEN}{centermodii}{GEN x, GEN y, GEN y2}, given
\typ{INT}s \kbd{x}, \kbd{y}, returns $z$ congruent to \kbd{x} modulo \kbd{y},
such that $-\kbd{y}/2 \leq z < \kbd{y}/2$. The function requires an extra
argument \kbd{y2}, such that \kbd{y2 = shifti(y, -1)}. (In most cases, \kbd{y}
is constant for many reductions and \kbd{y2} need only be computed once.)

\fun{GEN}{remi2n}{GEN x, long n} returns \kbd{x} mod $2^n$.

\fun{GEN}{addii_sign}{GEN x, long sx, GEN y, long sy} add the \typ{INT}s
$x$ and $y$ as if their signs were \kbd{sx} and \kbd{sy}.

\fun{GEN}{addir_sign}{GEN x, long sx, GEN y, long sy}
add the \typ{INT} $x$ and the \typ{REAL} $y$ as if their signs were \kbd{sx}
and \kbd{sy}.

\fun{GEN}{addrr_sign}{GEN x, long sx, GEN y, long sy} add the \typ{REAL}s $x$
and $y$ as if their signs were \kbd{sx} and \kbd{sy}.

\fun{GEN}{addsi_sign}{long x, GEN y, long sy} add $x$ and the \typ{INT} $y$
as if its sign was \kbd{sy}.

\subsec{Exact division and divisibility}

\fun{void}{diviiexact}{GEN x, GEN y} returns the Euclidean quotient
$\kbd{x} / \kbd{y}$, assuming $\kbd{y}$ divides $\kbd{x}$. Uses Jebelean
algorithm (Jebelean-Krandick bidirectional exact division is not
implemented).

\fun{void}{diviuexact}{GEN x, ulong y} returns the Euclidean quotient
$\kbd{x} / \kbd{y}$, assuming $\kbd{y}$ divides
$\kbd{x}$ and $\kbd{y}$ is non-zero.

The following routines return 1 (true) if \kbd{y} divides \kbd{x}, and
0 otherwise. (Error if $y$ is $0$, even if $x$ is $0$.) All \kbd{GEN} are assumed
to be \typ{INT}s:

\fun{int}{dvdii}{GEN x, GEN y},
\fun{int}{dvdis}{GEN x, long y},
\fun{int}{dvdiu}{GEN x, ulong y},

\fun{int}{dvdsi}{long x, GEN y},
\fun{int}{dvdui}{ulong x, GEN y}.

The following routines return 1 (true) if \kbd{y} divides \kbd{x}, and in
that case assign the quotient to \kbd{z}; otherwise they return 0. All
\kbd{GEN} are assumed to be \typ{INT}s:

\fun{int}{dvdiiz}{GEN x, GEN y, GEN z},
\fun{int}{dvdisz}{GEN x, long y, GEN z}.

\fun{int}{dvdiuz}{GEN x, ulong y, GEN z} if \kbd{y} divides \kbd{x}, assigns
the quotient $|\kbd{x}|/\kbd{y}$ to \kbd{z} and returns 1 (true), otherwise
returns 0 (false).

\subsec{Division with integral operands and \typ{REAL} result}

\fun{GEN}{rdivii}{GEN x, GEN y, long prec}, assuming $x$ and $y$
are both of type \typ{INT}, return the quotient $x/y$ as a \typ{REAL} of
precision \kbd{prec}.

\fun{GEN}{rdiviiz}{GEN x, GEN y, GEN z}, assuming $x$ and $y$
are both of type \typ{INT}, and $z$ is a \typ{REAL},
assign the quotient $x/y$ to $z$.

\fun{GEN}{rdivis}{GEN x, long y, long prec}, assuming \kbd{x}
is of type \typ{INT}, return the quotient x/y as a \typ{REAL} of
precision \kbd{prec}.

\fun{GEN}{rdivsi}{long x, GEN y, long prec}, assuming \kbd{y}
is of type \typ{INT}, return the quotient x/y as a \typ{REAL} of
precision \kbd{prec}.

\fun{GEN}{rdivss}{long x, long y, long prec}, return the quotient x/y as a
\typ{REAL} of precision \kbd{prec}.


\subsec{Division with remainder} The following functions return two objects,
unless specifically asked for only one of them~--- a quotient and a remainder.
The quotient is returned and the remainder is returned through the variable
whose address is passed as the \kbd{r} argument. The term \emph{true
Euclidean remainder} refers to the non-negative one (\kbd{mod}), and
\emph{Euclidean remainder} by itself to the one with the same sign as the
dividend (\kbd{rem}). All \kbd{GEN}s, whether returned directly or through a
pointer, are created on the stack.

\fun{GEN}{dvmdii}{GEN x, GEN y, GEN *r} returns the Euclidean quotient of the
\typ{INT}~\kbd{x} by a \typ{INT}~\kbd{y} and puts the remainder
into~\kbd{*r}. If \kbd{r} is equal to \kbd{NULL}, the remainder is not
created, and if \kbd{r} is equal to  \kbd{ONLY\_REM}, only the remainder is
created and returned. In the generic case, the remainder is created after the
quotient and can be disposed of individually with a \kbd{cgiv(r)}. The
remainder is always of the sign of the dividend~\kbd{x}. If the remainder
is $0$ set \kbd{r = gen\_0}.

\fun{void}{dvmdiiz}{GEN x, GEN y, GEN z, GEN t} assigns the Euclidean
quotient of the \typ{INT}s \kbd{x} and \kbd{y} into the \typ{INT}~\kbd{z},
and the Euclidean remainder into the \typ{INT}~\kbd{t}.

\noindent Analogous routines \tet{dvmdis}\kbd{[z]}, \tet{dvmdsi}\kbd{[z]},
\tet{dvmdss}\kbd{[z]} are available, where \kbd{s} denotes a \kbd{long}
argument. But the following routines are in general more flexible:

\fun{long}{sdivss_rem}{long s, long t, long *r} computes the Euclidean
quotient and remainder of the longs \kbd{s} and~\kbd{t}. Puts the remainder
into \kbd{*r}, and returns the quotient. The remainder is of the sign of the
dividend~\kbd{s}, and has strictly smaller absolute value than~\kbd{t}.

\fun{long}{sdivsi_rem}{long s, GEN x, long *r} computes the Euclidean
quotient and remainder of the \kbd{long}~\kbd{s} by the \typ{INT}~\kbd{x}. As
\kbd{sdivss\_rem} otherwise.

\fun{long}{sdivsi}{long s, GEN x} as \kbd{sdivsi\_rem}, without
remainder.

\fun{GEN}{divis_rem}{GEN x, long s, long *r} computes the Euclidean quotient
and remainder of the \typ{INT}~\kbd{x} by the \kbd{long}~\kbd{s}. As
\kbd{sdivss\_rem} otherwise.

\fun{GEN}{diviu_rem}{GEN x, ulong s, long *r} computes the Euclidean quotient
and remainder of \emph{absolute value} of the \typ{INT}~\kbd{x} by the
\kbd{ulong}~\kbd{s}. As \kbd{sdivss\_rem} otherwise.

\fun{ulong}{udivui_rem}{ulong s, GEN y, ulong *rem}
computes the Euclidean quotient and remainder of the $x$ by $y$. As
\kbd{sdivss\_rem} otherwise.

\fun{GEN}{divsi_rem}{long s, GEN y, long *r} computes the Euclidean quotient
and remainder of the \typ{long}~\kbd{s} by the \kbd{GEN}~\kbd{y}. As
\kbd{sdivss\_rem} otherwise.

\fun{GEN}{divss_rem}{long x, long y, long *r} computes the Euclidean quotient
and remainder of the \typ{long}~\kbd{x} by the \kbd{long}~\kbd{y}. As
\kbd{sdivss\_rem} otherwise.
\smallskip
\fun{GEN}{truedvmdii}{GEN x, GEN y, GEN *r}, as \kbd{dvmdii} but with a
non-negative remainder.

\fun{GEN}{truedvmdis}{GEN x, long y, GEN *z}, as \kbd{dvmdis} but with a
non-negative remainder.

\fun{GEN}{truedvmdsi}{long x, GEN y, GEN *z}, as \kbd{dvmdsi} but with a
non-negative remainder.

\subsec{Modulo to longs} The following variants of \kbd{modii} do not
clutter the stack:

\fun{long}{smodis}{GEN x, long y} computes the true Euclidean
remainder of the \typ{INT}~\kbd{x} by the \kbd{long}~\kbd{y}. This is the
non-negative remainder, not the one whose sign is the sign of \kbd{x}
as in the \kbd{div} functions.

\fun{long}{smodss}{long x, long y} computes the true Euclidean
remainder of the \kbd{long}~\kbd{x} by a \kbd{long}~\kbd{y}.

\fun{ulong}{umodiu}{GEN x, ulong y} computes the true Euclidean
remainder of the \typ{INT}~\kbd{x} by the \kbd{ulong}~\kbd{y}.

\fun{ulong}{umodui}{ulong x, GEN y} computes the true Euclidean
remainder of the \kbd{ulong}~\kbd{x} by the \typ{INT}~\kbd{|y|}.

The routine \tet{smodsi} does not exist, since it would not always be
defined: for a \emph{negative} \kbd{x}, if the quotient is $\pm1$, the result
\kbd{x + |y|} would in general not fit into a \kbd{long}. Use either
\kbd{umodui} or \kbd{modsi}.

\subsec{Powering, Square root}

\fun{GEN}{powii}{GEN x, GEN n}, assumes $x$ and $n$ are \typ{INT}s and
returns $x^n$.

\fun{GEN}{powuu}{ulong x, ulong n}, returns $x^n$.

\fun{GEN}{powiu}{GEN x, ulong n}, assumes $x$ is a \typ{INT} and returns $x^n$.

\fun{GEN}{powis}{GEN x, long n}, assumes $x$ is a \typ{INT} and returns $x^n$
(possibly a \typ{FRAC} if $n < 0$).

\fun{GEN}{powrs}{GEN x, long n}, assumes $x$ is a \typ{REAL} and returns
$x^n$. This is considered as a sequence of \kbd{mulrr}, possibly empty:
as such the result has type \typ{REAL}, even if $n = 0$.
Note that the generic function \kbd{gpowgs(x,0)} would return \kbd{gen\_1},
see the technical note in \secref{se:genbinop}.

\fun{GEN}{powru}{GEN x, ulong n}, assumes $x$ is a \typ{REAL} and returns $x^n$
(always a \typ{REAL}, even if $n = 0$).

\fun{GEN}{powrshalf}{GEN x, long n}, assumes $x$ is a \typ{REAL} and returns
$x^{n/2}$ (always a \typ{REAL}, even if $n = 0$).

\fun{GEN}{powruhalf}{GEN x, ulong n}, assumes $x$ is a \typ{REAL} and returns
$x^{n/2}$ (always a \typ{REAL}, even if $n = 0$).

\fun{GEN}{powrfrac}{GEN x, long n, long d}, assumes $x$ is a \typ{REAL} and
returns $x^{n/d}$ (always a \typ{REAL}, even if $n = 0$).

\fun{GEN}{powIs}{long n} returns $I^n\in\{1,I,-1,-I\}$ (\typ{INT} for even $n$,
\typ{COMPLEX} otherwise).

\fun{ulong}{upowuu}{ulong x, ulong n}, returns $x^n$ modulo $2^\B$. This is
meant to be used for tiny $n$, where in fact $x^n$ fits into an \kbd{ulong}.

\fun{GEN}{sqrtremi}{GEN N, GEN *r}, returns the integer square root $S$ of
the non-negative \typ{INT}~\kbd{N} (rounded towards 0) and puts the remainder
$R$ into~\kbd{*r}. Precisely, $N = S^2 + R$ with $0\leq R \leq 2S$. If
\kbd{r} is equal to \kbd{NULL}, the remainder is not created. In the generic
case, the remainder is created after the quotient and can be disposed of
individually with \kbd{cgiv(R)}. If the remainder is $0$ set \kbd{R = gen\_0}.

Uses a divide and conquer algorithm (discrete variant of Newton iteration)
due to Paul Zimmermann (``Karatsuba Square Root'', INRIA Research Report 3805
(1999)).

\fun{GEN}{sqrti}{GEN N}, returns the integer square root $S$ of
the non-negative \typ{INT}~\kbd{N} (rounded towards 0). This is identical
to \kbd{sqrtremi(N, NULL)}.

\subsec{GCD, extended GCD and LCM}

\fun{long}{cgcd}{long x, long y} returns the GCD of \kbd{x} and \kbd{y}.

\fun{ulong}{ugcd}{ulong x, ulong y} returns the GCD of \kbd{x} and \kbd{y}.

\fun{long}{clcm}{long x, long y} returns the LCM of \kbd{x} and \kbd{y},
provided it fits into a \kbd{long}. Silently overflows otherwise.

\fun{GEN}{gcdii}{GEN x, GEN y}, returns the GCD of the \typ{INT}s \kbd{x} and
\kbd{y}.

\fun{GEN}{lcmii}{GEN x, GEN y}, returns the LCM of the \typ{INT}s \kbd{x} and
\kbd{y}.

\fun{GEN}{bezout}{GEN a,GEN b, GEN *u,GEN *v}, returns the GCD $d$ of
\typ{INT}s \kbd{a} and \kbd{b} and sets \kbd{u}, \kbd{v} to the Bezout
coefficients such that $\kbd{au} + \kbd{bv} = d$.

\fun{long}{cbezout}{long a,long b, long *u,long *v}, returns the GCD
$d$ of \kbd{a} and \kbd{b} and sets \kbd{u}, \kbd{v} to the Bezout coefficients
such that $\kbd{au} + \kbd{bv} = d$.

\subsec{Pure powers}

\fun{long}{Z_issquare}{GEN n} returns $1$ if the \typ{INT} $n$ is
a square, and $0$ otherwise. This is tested first modulo small prime
powers, then \kbd{sqrtremi} is called.

\fun{long}{Z_issquareall}{GEN n, GEN *sqrtn} as \kbd{Z\_issquare}. If
$n$ is indeed a square, set \kbd{sqrtn} to its integer square root.
Uses a fast congruence test mod $64\times 63\times 65\times 11$ before
computing an integer square root.

\fun{long}{uissquareall}{ulong n, ulong *sqrtn} as \kbd{Z\_issquareall},
for an \kbd{ulong} operand \kbd{n}.

\fun{long}{Z_ispower}{GEN x, ulong k} returns $1$ if the \typ{INT} $n$ is a
$k$-th power, and $0$ otherwise; assume that $k > 1$.

\fun{long}{Z_ispowerall}{GEN x, ulong k, GEN *pt} as \kbd{Z\_ispower}. If
$n$ is indeed a $k$-th power, set \kbd{*pt} to its integer $k$-th root.

\fun{long}{Z_isanypower}{GEN x, GEN *ptn} returns the maximal $k\geq 2$  such
that the \typ{INT} $x = n^k$ is a perfect power, or $0$ if no such $k$ exist;
in particular \kbd{ispower(1)}, \kbd{ispower(0)}, \kbd{ispower(-1)} all
return 0. If the return value $k$ is not $0$ (so that $x = n^k$) and
\kbd{ptn} is not \kbd{NULL}, set \kbd{*ptn} to $n$.

The following low-level functions are called by \tet{Z_isanypower} but can
be directly useful:

\fun{int}{is_357_power}{GEN x, GEN *ptn, ulong *pmask} tests whether the
integer $x > 0$ is a $3$-rd, $5$-th or $7$-th power. The bits of \kbd{*mask}
initially indicate which test is to be performed;
bit $0$: $3$-rd,
bit $1$: $5$-th,
bit $2$: $7$-th (e.g.~$\kbd{*pmask} = 7$ performs all tests). They are
updated during the call: if the ``$i$-th power'' bit is set to $0$
then $x$ is not a $k$-th power. The function returns $0$
(not a
$3$-rd,
$5$-th or
$7$-th power),
$3$
($3$-rd power,
not a $5$-th or
$7$-th power),
$5$
($5$-th power,
not a $7$-th power),
or $7$
($7$-th power); if an $i$-th power bit is initially set to $0$, we take it
at face value and assume $x$ is not an $i$-th power without performing any
test. If the return value $k$ is non-zero, set \kbd{*ptn} to $n$ such that $x
= n^k$.

\fun{int}{is_pth_power}{GEN x, GEN *ptn, ulong *pminp, ulong cutoff}
$x > 0$ is an integer and we look for the smallest prime
$p \geq \max(11,\kbd{*pminp})$ such that $x = n^p$. (The $11$ is due to the
fact that \tet{is_357_power} and \kbd{issquare} are faster than
the generic version for $p < 11$.) Fail and return $0$ when the existence
of $p$ would imply $2^{\kbd{cutoff}} > x^{1/p}$, meaning that a possible $n$
is so small that it should have been found by trial division; for maximal
speed, you should start by a round of trial division, but the cut-off may
also be set to $1$ for a rigorous result without any trial division.

Otherwise returns the smallest suitable prime $p$ and set \kbd{*ptn} to $n$.
\kbd{*pminp} is updated to $p$, so that we may immediately recall the
function with the same parameters after setting $x = \kbd{*ptn}$.

\subsec{Factorization}

\fun{GEN}{Z_factor}{GEN n} factors the \typ{INT} \kbd{n}. The ``primes''
in the factorization are actually strong pseudoprimes.

\fun{int}{is_Z_factor}{GEN f} returns $1$ if $f$ looks like the factorization
of a positive integer, and $0$ otherwise. Useful for sanity checks but not
100\% foolproof. Specifically, this routine checks that $f$ is a two-column
matrix all of whose entries are positive integers.

\fun{long}{Z_issquarefree}{GEN x} returns $1$ if the \typ{INT} \kbd{n}
is square-free, and $0$ otherwise.

\fun{long}{Z_isfundamental}{GEN x} returns $1$ if the \typ{INT} \kbd{x}
is a fundamental discriminant, and $0$ otherwise.

\fun{GEN}{Z_factor_until}{GEN n, GEN lim} as \kbd{Z\_factor}, but stop the
factorization process as soon as the unfactored part is smaller than \kbd{lim}.
The resulting factorization matrix only contains the factors found. No other
assumptions can be made on the remaining factors.

\fun{GEN}{Z_factor_limit}{GEN n, ulong lim} trial divide $n$ by all primes $p
< \kbd{lim}$ in the precomputed list of prime numbers and return the
corresponding factorization matrix. In this case, the last ``prime'' divisor
in the first column of the factorization matrix may well be a proven
composite.

If $\kbd{lim} = 0$, the effect is the same as setting $\kbd{lim} =
\kbd{maxprime()} + 1$: use all precomputed primes.

\fun{GEN}{boundfact}{GEN x, ulong lim} as \tet{Z_factor_limit}, applying to
\typ{INT} or \typ{FRAC} inputs.

\fun{GEN}{Z_smoothen}{GEN n, GEN L, GEN *pP, GEN *pE} given a \typ{VECSMALL}
$L$ containing a list of small primes and a \typ{INT} $n$, trial divide
$n$ by the elements of $L$ and return the cofactor. Return \kbd{NULL} if the
cofactor is $\pm 1$. \kbd{*P} and \kbd{*E} contain the list of prime divisors
found and their exponents, as \typ{VECSMALL}s. Neither memory-clean, nor
suitable for \tet{gerepileupto}.

\fun{GEN}{core}{GEN n} unique squarefree integer $d$ dividing $n$ such that
$n/d$ is a square.

\fun{GEN}{core2}{GEN n} return $[d,f]$ with $d$ squarefree and $n = df^2$.

\fun{GEN}{corepartial}{GEN n, long lim} as \kbd{core}, using
\kbd{boundfact(n,lim)} to partially factor \kbd{n}. The result is not
necessarily squarefree, but $p^2 \mid n$ implies $p > \kbd{lim}$.

\fun{GEN}{core2partial}{GEN n, long lim} as \kbd{core2}, using
\kbd{boundfact(n,lim)} to partially factor \kbd{n}. The resulting $d$ is not
necessarily squarefree, but $p^2 \mid n$ implies $p > \kbd{lim}$.

\fun{GEN}{factor_pn_1}{GEN p, long n} returns the factorization of $p^n-1$,
where $p$ is prime and $n$ is a positive integer.

\fun{GEN}{factor_Aurifeuille_prime}{GEN p, long n} an Aurifeuillian factor
of $\phi_n(p)$, assuming $p$ prime and an Aurifeuillian factor exists
($p \zeta_n$ is a square in $\Q(\zeta_n)$).

\fun{GEN}{factor_Aurifeuille}{GEN a, long d} an Aurifeuillian factor of
$\phi_n(a)$, assuming $a$ is a non-zero integer and $n > 2$. Returns $1$
if no Aurifeuillian factor exists.

\fun{GEN}{factoru}{ulong n}, returns the factorization of $n$. The result
is a $2$-component vector $[P,E]$, where $P$ and $E$ are \typ{VECSMALL}
containing the prime divisors of $n$, and the $v_p(n)$.


\fun{GEN}{factoru_pow}{ulong n}, returns the factorization of $n$. The result
is a $3$-component vector $[P,E,C]$, where $P$, $E$ and $C$ are
\typ{VECSMALL} containing the prime divisors of $n$, the $v_p(n)$
and the $p^{v_p(n)}$.

\subsec{Primality and compositeness tests}

\fun{int}{uisprime}{ulong p}, returns $1$ if \kbd{p} is a prime number and
$0$ otherwise.

\fun{ulong}{uprimepi}{ulong n}, returns the number of primes $p\leq n$.

\fun{ulong}{unextprime}{ulong n}, returns the smallest prime $\geq n$. Return
$0$ if it cannot be represented as an \kbd{ulong} (bigger than $2^{64} - 59$
or $2^{32} - 5$ depending on the word size).

\fun{ulong}{uprime}{long n} returns the $n$-th prime, assuming it belongs to
the precomputed prime table. Error otherwise.

\fun{GEN}{prime}{long n} same as \kbd{utoi(uprime(n))}.

\fun{GEN}{primes_zv}{long m} returns the $m$-th first primes, in a
\typ{VECSMALL}, assuming they belong to the precomputed prime table.
Error otherwise.

\fun{int}{isprime}{GEN n}, returns $1$ if the \typ{INT} \kbd{n} is a
(fully proven) prime number and $0$ otherwise.

\fun{long}{isprimeAPRCL}{GEN n}, returns $1$ if the \typ{INT} \kbd{n} is a
prime number and $0$ otherwise, using only the APRCL test --- not even trial
division or compositeness tests. The workhorse \kbd{isprime} should be
faster on average, especially if non-primes are included!

\fun{long}{BPSW_psp}{GEN n}, returns $1$ if the \typ{INT} \kbd{n} is a
Baillie-Pomerance-Selfridge-Wagstaff pseudoprime, and $0$ otherwise (proven
composite).

\fun{int}{BPSW_isprime}{GEN x} assuming $x$ is a BPSW-pseudoprime, rigorously
prove its primality. The function \tet{isprime} is currently implemented
as
\bprog
 BPSW_psp(x) && BPSW_isprime(x)
@eprog

\fun{long}{millerrabin}{GEN n, long k} performs $k$ strong Rabin-Miller
compositeness tests on the \typ{INT} $n$, using $k$ random bases. This
function also caches square roots of $-1$ that are encountered during the
successive tests and stops as soon as three distinct square roots have been
produced; we have in principle factored $n$ at this point, but
unfortunately, there is currently no way for the factoring machinery to
become aware of it. (It is highly implausible that hard to find factors
would be exhibited in this way, though.) This should be slower than
\tet{BPSW_psp} for $k\geq 4$ and we would expect it to be less reliable.

\subsec{Pseudo-random integers}
These routine return pseudo-random integers uniformly distributed in some
interval. The all use the same underlying generator which can be seeded and
restarted using \tet{getrand} and \tet{setrand}.

\fun{void}{setrand}{GEN seed} reseeds the random number generator using the
seed $n$. The seed is either a technical array output by \kbd{getrand}
or a small positive integer, used to generate deterministically a suitable
state array. For instance, running a randomized computation starting by
\kbd{setrand(1)} twice will generate the exact same output.

\fun{GEN}{getrand}{void} returns the current value of the seed used by the
pseudo-random number generator \tet{random}. Useful mainly for debugging
purposes, to reproduce a specific chain of computations. The returned value
is technical (reproduces an internal state array of type \typ{VECSMALL}),
and can only be used as an argument to \tet{setrand}.

\fun{ulong}{pari_rand}{void} returns a random $0 \leq x < 2^\B$.

\fun{long}{random_bits}{long k} returns a random $0 \leq x < 2^k$. Assumes
that $0 \leq k \leq \B$.

\fun{ulong}{random_Fl}{ulong p} returns a pseudo-random integer
in $0, 1, \dots p-1$.

\fun{GEN}{randomi}{GEN n} returns a random \typ{INT} between $0$ and $\kbd{n}
- 1$.

\fun{GEN}{randomr}{long prec} returns a random \typ{REAL} in $[0,1[$, with
precision \kbd{prec}.

\subsec{Modular operations} In this subsection, all \kbd{GEN}s are \typ{INT}

\fun{GEN}{Fp_red}{GEN a, GEN m} returns \kbd{a} modulo \kbd{m} (smallest
non-negative residue). (This is identical to modii).

\fun{GEN}{Fp_neg}{GEN a, GEN m} returns $-$\kbd{a} modulo \kbd{m} (smallest
non-negative residue).

\fun{GEN}{Fp_add}{GEN a, GEN b, GEN m} returns the sum of \kbd{a} and
\kbd{b} modulo \kbd{m} (smallest non-negative residue).

\fun{GEN}{Fp_sub}{GEN a, GEN b, GEN m} returns the difference of \kbd{a} and
\kbd{b} modulo \kbd{m} (smallest non-negative residue).

\fun{GEN}{Fp_center}{GEN a, GEN p, GEN pov2} assuming that \kbd{pov2} is
\kbd{shifti(p,-1)} and that \kbd{a} is between $0$ and $\kbd{p} - 1$ and,
returns the representative of \kbd{a} in the symmetric residue system.

\fun{GEN}{Fp_mul}{GEN a, GEN b, GEN m} returns the product of \kbd{a} by
\kbd{b} modulo \kbd{m} (smallest non-negative residue).

\fun{GEN}{Fp_mulu}{GEN a, ulong b, GEN m} returns the product of \kbd{a} by
\kbd{b} modulo \kbd{m} (smallest non-negative residue).

\fun{GEN}{Fp_sqr}{GEN a, GEN m} returns $\kbd{a}^2$ modulo \kbd{m} (smallest
non-negative residue).

\fun{ulong}{Fp_powu}{GEN x, ulong n, GEN m} raises \kbd{x} to the \kbd{n}-th
power modulo \kbd{m} (smallest non-negative residue). Not memory-clean, but
suitable for \kbd{gerepileupto}.

\fun{ulong}{Fp_pows}{GEN x, long n, GEN m} raises \kbd{x} to the \kbd{n}-th
power modulo \kbd{m} (smallest non-negative residue). A negative \kbd{n} is
allowed Not memory-clean, but suitable for \kbd{gerepileupto}.

\fun{GEN}{Fp_pow}{GEN x, GEN n, GEN m} returns $\kbd{x}^\kbd{n}$
modulo \kbd{m} (smallest non-negative residue).

\fun{GEN}{Fp_inv}{GEN a, GEN m} returns an inverse of \kbd{a} modulo \kbd{m}
(smallest non-negative residue). Raise an error if \kbd{a} is not invertible.

\fun{GEN}{Fp_invsafe}{GEN a, GEN m} as \kbd{Fp\_inv}, but return
\kbd{NULL} if \kbd{a} is not invertible.

\fun{GEN}{FpV_inv}{GEN x, GEN m} $x$ being a vector of \typ{INT}s, return
the vector of inverses of the $x[i]$ mod $m$. The routine uses Montgomery's
trick, and involves a single inversion mod $m$, plus $3(N-1)$ multiplications
for $N$ entries. The routine is not stack-clean: $2N$ integers mod $m$
are left on stack, besides the $N$ in the result.

\fun{GEN}{Fp_div}{GEN a, GEN b, GEN m} returns the quotient of \kbd{a} by
\kbd{b} modulo \kbd{m} (smallest non-negative residue). Raise an error if
\kbd{b} is not invertible.

\fun{int}{invmod}{GEN a, GEN m, GEN *g},  return $1$ if \kbd{a}
modulo \kbd{m} is invertible, else return $0$ and set
$\kbd{g} = \gcd(\kbd{a},\kbd{m})$.

\fun{GEN}{Fp_log}{GEN a, GEN g, GEN ord, GEN p} Let $g$ such that $g^ord=1
\pmod{p}$. Return an integer $e$ such that $a^e=g \pmod{p}$. If $e$ does not
exists, the result is currently undefined.

\fun{GEN}{Fp_order}{GEN a, GEN ord, GEN p} returns the order of the
\typ{Fp} \kbd{a}. If \kbd{ord} is non-\kbd{NULL}, it is assumed that \kbd{ord}
is a multiple of the order of \kbd{a}, either as a \typ{INT} or a
factorization matrix.

\fun{GEN}{Fp_sqrt}{GEN x, GEN p} returns a square root of \kbd{x} modulo
\kbd{p} (the smallest non-negative residue), where \kbd{x}, \kbd{p} are
\typ{INT}s, and \kbd{p} is assumed to be prime. Return \kbd{NULL}
if \kbd{x} is not a quadratic residue modulo \kbd{p}.

\fun{GEN}{Fp_sqrtn}{GEN x, GEN n, GEN p, GEN *zn} returns an \kbd{n}-th
root of $\kbd{x}$ modulo \kbd{p} (smallest non-negative residue), where
\kbd{x}, \kbd{n}, \kbd{p} are \typ{INT}s, and \kbd{p} is assumed to be prime.
Return \kbd{NULL} if \kbd{x} is not an \kbd{n}-th power residue. Otherwise,
if \kbd{zn} is non-\kbd{NULL} set it to a primitive \kbd{n}-th root of $1$.

\fun{GEN}{Zn_sqrt}{GEN x, GEN n} returns one of the square roots of \kbd{x}
modulo \kbd{n} (possibly not prime), where \kbd{x} is a \typ{INT} and \kbd{n}
is either a \typ{INT} or is given by its factorisation matrix.  Return
\kbd{NULL} if no such square root exist.

\fun{long}{kross}{long x, long y} returns the \idx{Kronecker symbol} $(x|y)$,
i.e.$-1$, $0$ or $1$. If \kbd{y} is an odd prime, this is the \idx{Legendre
symbol}. (Contrary to \kbd{krouu}, \kbd{kross} also supports $\kbd{y} = 0$)

\fun{long}{krouu}{ulong x, ulong y} returns the \idx{Kronecker symbol}
$(x|y)$, i.e.~$-1$, $0$ or $1$. Assumes \kbd{y} is non-zero. If \kbd{y} is an
odd prime, this is the \idx{Legendre symbol}.

\fun{long}{krois}{GEN x, long y} returns the \idx{Kronecker symbol} $(x|y)$
of \typ{INT}~x and \kbd{long}~\kbd{y}. As \kbd{kross} otherwise.

\fun{long}{krosi}{long x, GEN y} returns the \idx{Kronecker symbol} $(x|y)$
of \kbd{long}~x and \typ{INT}~\kbd{y}. As \kbd{kross} otherwise.

\fun{long}{kronecker}{GEN x, GEN y} returns the \idx{Kronecker symbol} $(x|y)$
of \typ{INT}s~x and~\kbd{y}. As \kbd{kross} otherwise.

\fun{GEN}{pgener_Fp}{GEN p} returns a primitive root modulo \kbd{p}, assuming
\kbd{p} is prime.

\fun{GEN}{pgener_Zp}{GEN p} returns a primitive root modulo $p^k$, $k > 1$,
assuming \kbd{p} is an odd prime.

\fun{long}{Zp_issquare}{GEN x, GEN p} returns 1 if the \typ{INT} $x$ is
a $p$-adic square, $0$ otherwise.

\fun{long}{Zn_issquare}{GEN x, GEN n} returns 1 if \typ{INT} $x$ is
a square modulo \kbd{n} (possibly not prime), where $n$ is either a \typ{INT}
or is given by its factorisation matrix. Return $0$ otherwise.

\fun{GEN}{pgener_Fp_local}{GEN p, GEN L}, \kbd{L} being a vector of
primes dividing $p - 1$, returns an integer $x$ which is a generator of the
$\ell$-Sylow of $\F_p^*$ for every $\ell$ in \kbd{L}. In other words,
$x^{(p-1)/\ell} \neq 1$ for all such $\ell$. In particular, returns
\kbd{pgener\_Fp(p)} if \kbd{L} contains all primes dividing $p - 1$.
It is not necessary, and in fact slightly inefficient, to include $\ell=2$,
since 2 is treated separately in any case, i.e. the generator
obtained is never a square.

\subsec{Extending functions to vector inputs}

The following functions apply $f$ to the given arguments, recursively
if they are of vector / matrix type:

\fun{GEN}{map_proto_G}{GEN (*f)(GEN), GEN x} For instance, if $x$ is a
\typ{VEC}, return a \typ{VEC} whose components are the $f(x[i])$.

\fun{GEN}{map_proto_lG}{long (*f)(GEN), GEN x} As above, applying the
function \kbd{stoi( f() )}.

\fun{GEN}{map_proto_GG}{GEN (*f)(GEN,GEN), GEN x, GEN n} If $x$ and $n$
are both vector types, expand $x$ first, then $n$.

\fun{GEN}{map_proto_lGG}{long (*f)(GEN,GEN), GEN x, GEN n}

\fun{GEN}{map_proto_GL}{GEN (*f)(GEN,long), GEN x, long y}

\fun{GEN}{map_proto_lGL}{long (*f)(GEN,long), GEN x, long y}

In the last function, $f$ implements an associative binary operator, which we
extend naturally to an $n$-ary operator $f_n$ for any $n$ : by convention,
$f_0() = 1$, $f_1(x) = x$, and
$$ f_n(x_1,\dots,x_n) = f( f_{n-1}(x_1,\dots,x_{n-1}), x_n)),$$
for $n \geq 2$.

\fun{GEN}{gassoc_proto}{GEN (*f)(GEN,GEN),GEN x, GEN y} If $y$ is not
\kbd{NULL}, return $f(x,y)$. Otherwise, $x$ must be of vector type, and we
return the result of $f$ applied to its components, computed using a
divide-and-conquer algorithm. More precisely, return
$$f( f(x_1,\kbd{NULL}), f(x_2,\kbd{NULL}) ),$$
where $x_1$, $x_2$ are the two halves of $x$.

\subsec{Miscellaneous arithmetic functions}

\fun{ulong}{eulerphiu}{ulong n}, Euler's totient function of $n$.

\fun{GEN}{divisorsu}{ulong n}, returns the divisors of $n$ in a
\typ{VECSMALL}, sorted by increasing order.

\fun{GEN}{hilbertii}{GEN x, GEN y, GEN p}, returns the Hilbert symbol
$(x,y)$ at the prime $p$ (\kbd{NULL} for the place at infinity); $x$ and $y$
are \typ{INT}s.

\fun{GEN}{sumdedekind}{GEN h, GEN k} returns the Dedekind sum associated to
the \typ{INT} $h$ and $k$, $k > 0$.

\fun{GEN}{sumdedekind_coprime}{GEN h, GEN k} as \kbd{sumdedekind}, except
that $h$ and $k$ are assumed to be coprime \typ{INT}s.

\newpage
\chapter{Level 2 kernel}

These functions deal with modular arithmetic, linear algebra and polynomials
where assumptions can be made about the types of the coefficients.

\section{Naming scheme}\label{se:level2names}
A function name is built in the following way:
$A_1\kbd{\_}\dots\kbd{\_}A_n\var{fun}$ for an operation \var{fun} with $n$
arguments of class $A_1$,\dots, $A_n$. A class name is given by a base ring
followed by a number of code letters. Base rings are among

  \kbd{Fl}: $\Z/l\Z$ where $l < 2^{\B}$ is not necessarily prime. Implemented
            using \kbd{ulong}s

  \kbd{Fp}: $\Z/p\Z$ where $p$ is a \typ{INT}, not necessarily prime.
Implemented as \typ{INT}s $z$, preferably satisfying $0 \leq z < p$.
More precisely, any \typ{INT} can be used as an \kbd{Fp}, but reduced
inputs are treated more efficiently. Outputs from \kbd{Fp}xxx routines are
reduced.

  \kbd{Fq}: $\Z[X]/(p,T(X))$, $p$ a \typ{INT}, $T$ a \typ{POL} with \kbd{Fp}
coefficients or \kbd{NULL} (in which case no reduction modulo \kbd{T} is
performed). Implemented as \typ{POL}s $z$ with \kbd{Fp} coefficients,
$\deg(z) < \deg \kbd{T}$, although $z$ a \typ{INT} is allowed for elements in
the prime field.

  \kbd{Z}:  the integers $\Z$, implemented as \typ{INT}s.

  \kbd{z}:  the integers $\Z$, implemented using (signed) \kbd{long}s.

  \kbd{Q}:  the rational numbers $\Q$, implemented as \typ{INT}s and
\typ{FRAC}s.

  \kbd{Rg}:  a commutative ring, whose elements can be
\kbd{gadd}-ed, \kbd{gmul}-ed, etc.

\noindent Possible letters are:

  \kbd{X}: polynomial in $X$ (\typ{POL} in a fixed variable), e.g. \kbd{FpX}
           means $\Z/p\Z[X]$

  \kbd{Y}: polynomial in $Y\neq X$. This is used to resolve ambiguities.
           E.g. \kbd{FpXY} means $((\Z/p\Z)[X])[Y]$.

  \kbd{V}: vector (\typ{VEC} or \typ{COL}), treated as a line vector
  (independently of the actual type). E.g. \kbd{ZV} means $\Z^k$ for some $k$.

  \kbd{C}: vector (\typ{VEC} or \typ{COL}), treated as a column vector
  (independently of the actual type). The difference with \kbd{V} is purely
  semantic: if the result is a vector, it will be of type \typ{COL} unless
  mentioned otherwise. For instance the function \kbd{ZC\_add} receives two
  integral vectors (\typ{COL} or \typ{VEC}, possibly different types) of the
  same length and returns a \typ{COL} whose entries are the sums of the input
  coefficients.

  \kbd{M}: matrix (\typ{MAT}). E.g. \kbd{QM} means a matrix with rational
  entries

  \kbd{E}: point over an elliptic curve, represented
  as two-component vectors \kbd{[x,y]}, except for the  represented by the
  one-component vector \kbd{[0]}. Not all curve models are supported.

  \kbd{Q}: representative (\typ{POL}) of a class in a polynomial quotient ring.
  E.g.~an \kbd{FpXQ} belongs to $(\Z/p\Z)[X]/(T(X))$, \kbd{FpXQV} means a
  vector of such elements, etc.

  \kbd{x}, \kbd{y}, \kbd{m}, \kbd{v}, \kbd{c}, \kbd{q}: as their uppercase
  counterpart, but coefficient arrays are implemented using \typ{VECSMALL}s,
  which coefficient understood as \kbd{ulong}s.

  \kbd{x} and \kbd{y} (and \kbd{q}) are implemented by a \typ{VECSMALL} whose
  first coefficient is used as a code-word and the following are the
  coefficients , similarly to a \typ{POL}. This is known as a 'POLSMALL'.

  \kbd{m} are implemented by a \typ{MAT} whose components (columns) are
  \typ{VECSMALL}s. This is know as a 'MATSMALL'.

  \kbd{v} and \kbd{c} are regular \typ{VECSMALL}s. Difference between the
  two is purely semantic.

\noindent Omitting the letter means the argument is a scalar in the base
ring. Standard functions \var{fun} are

  \kbd{add}: add

  \kbd{sub}: subtract

  \kbd{mul}: multiply

  \kbd{sqr}: square

  \kbd{div}: divide (Euclidean quotient)

  \kbd{rem}: Euclidean remainder

  \kbd{divrem}: return Euclidean quotient, store remainder in a pointer
argument. Three special values of that pointer argument modify the default
behavior: \kbd{NULL} (do not store the remainder, used to implement
\kbd{div}), \tet{ONLY_REM} (return the remainder, used to implement
\kbd{rem}), \tet{ONLY_DIVIDES} (return the quotient if the division is exact,
and \kbd{NULL} otherwise).

  \kbd{gcd}: GCD

  \kbd{extgcd}: return GCD, store Bezout coefficients in pointer arguments

  \kbd{pow}: exponentiate

  \kbd{eval}: evaluation / composition


\section{Modular arithmetic}

\noindent These routines implement univariate polynomial arithmetic and
linear algebra over finite fields, in fact over finite rings of the form
$(\Z/p\Z)[X]/(T)$, where $p$ is not necessarily prime and $T\in(\Z/p\Z)[X]$ is
possibly reducible; and finite extensions thereof. All this can be emulated
with \typ{INTMOD} and \typ{POLMOD} coefficients and using generic routines,
at a considerable loss of efficiency. Also, specialized routines are
available that have no obvious generic equivalent.

\subsec{\kbd{FpC} / \kbd{FpV}, \kbd{FpM}, \kbd{FqM}} A \kbd{ZV}
(resp.~a~\kbd{ZM}) is a \typ{VEC} or \typ{COL} (resp.~\typ{MAT}) with
\typ{INT} coefficients. An \kbd{FpV} or \kbd{FpM}, with respect to a given
\typ{INT}~\kbd{p}, is the same with \kbd{Fp} coordinates; operations are
understood over $\Z/p\Z$. An \kbd{FqM} is a matrix with \kbd{Fq} coefficients
(with respect to given \kbd{T}, \kbd{p}), not necessarily reduced (i.e
arbitrary \typ{INT}s and \kbd{ZX}s in the same variable as \kbd{T}).

\subsubsec{Conversions}

\fun{int}{Rg_is_Fp}{GEN z, GEN *p}, checks if \kbd{z} can be mapped to
$\Z/p\Z$: a \typ{INT} or a \typ{INTMOD} whose modulus is equal to \kbd{*p},
(if \kbd{*p} not \kbd{NULL}), in that case return $1$, else $0$. If a modulus
is found it is put in \kbd{*p}, else \kbd{*p} is left unchanged.

\fun{int}{RgV_is_FpV}{GEN z, GEN *p}, \kbd{z} a \typ{VEC} (resp. \typ{COL}),
checks if it can be mapped to a \kbd{FpV} (resp. \kbd{FpC}), by checking
\kbd{Rg\_is\_Fp} coefficientwise.

\fun{int}{RgM_is_FpM}{GEN z, GEN *p}, \kbd{z} a \typ{MAT},
checks if it can be mapped to a \kbd{FpM}, by checking \kbd{RgV\_is\_FpV}
columnwise.

\fun{GEN}{Rg_to_Fp}{GEN z, GEN p}, \kbd{z} a scalar which can be mapped to
$\Z/p\Z$: a \typ{INT}, a \typ{INTMOD} whose modulus is divisible by $p$,
a \typ{FRAC} whose denominator is coprime to $p$, or a \typ{PADIC} with
underlying prime $\ell$ satisfying $p = \ell^n$ for some $n$ (less than the
accuracy of the input). Returns \kbd{lift(z * Mod(1,p))}, normalized.

\fun{GEN}{padic_to_Fp}{GEN x, GEN p} special case of \tet{Rg_to_Fp},
for a $x$ a \typ{PADIC}.

\fun{GEN}{RgV_to_FpV}{GEN z, GEN p}, \kbd{z} a \typ{VEC} or \typ{COL},
returns the \kbd{FpV} (as a \typ{VEC}) obtained by applying \kbd{Rg\_to\_Fp}
coefficientwise.

\fun{GEN}{RgC_to_FpC}{GEN z, GEN p}, \kbd{z} a \typ{VEC} or \typ{COL},
returns the \kbd{FpC} (as a \typ{COL}) obtained by applying \kbd{Rg\_to\_Fp}
coefficientwise.

\fun{GEN}{RgM_to_FpM}{GEN z, GEN p}, \kbd{z} a \typ{MAT},
returns the \kbd{FpM} obtained by applying \kbd{RgC\_to\_FpC}
columnwise.

The functions above are generally used as follow:
\bprog
GEN add(GEN x, GEN y)
{
  GEN p = NULL;
  if (Rg_is_Fp(x, &p) && Rg_is_Fp(y, &p) && p)
  {
    x = Rg_to_Fp(x, p); y = Rg_to_Fp(y, p);
    z = Fp_add(x, y, p);
    return Fp_to_mod(z);
  }
  else return gadd(x, y);
}
@eprog

\fun{GEN}{FpC_red}{GEN z, GEN p}, \kbd{z} a \kbd{ZC}. Returns \kbd{lift(Col(z) *
Mod(1,p))}, hence a \typ{COL}.

\fun{GEN}{FpV_red}{GEN z, GEN p}, \kbd{z} a \kbd{ZV}. Returns \kbd{lift(Vec(z) *
Mod(1,p))}, hence a \typ{VEC}

\fun{GEN}{FpM_red}{GEN z, GEN p}, \kbd{z} a \kbd{ZM}. Returns \kbd{lift(z *
Mod(1,p))}, which is an \kbd{FpM}.

\subsubsec{Basic operations}

\fun{GEN}{FpC_center}{GEN z, GEN p, GEN pov2} returns a \typ{COL} whose
entries are the \kbd{Fp\_center} of the \kbd{gel(z,i)}.

\fun{GEN}{FpM_center}{GEN z, GEN p, GEN pov2} returns a matrix whose
entries are the \kbd{Fp\_center} of the \kbd{gcoeff(z,i,j)}.

\fun{GEN}{FpC_add}{GEN x, GEN y, GEN p} adds the \kbd{ZC} $x$ and $y$
and reduce modulo $p$ to obtain an \kbd{FpC}.

\fun{GEN}{FpV_add}{GEN x, GEN y, GEN p} same as \kbd{FpC\_add}, returning and
\kbd{FpV}.

\fun{GEN}{FpC_sub}{GEN x, GEN y, GEN p} subtracts the \kbd{ZC} $y$ to
the \kbd{ZC} $x$ and reduce modulo $p$ to obtain an \kbd{FpC}.

\fun{GEN}{FpV_sub}{GEN x, GEN y, GEN p} same as \kbd{FpC\_sub}, returning and
\kbd{FpV}.

\fun{GEN}{FpC_Fp_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{ZC}~\kbd{x}
(seen as a column vector) by the \typ{INT}~\kbd{y} and reduce modulo \kbd{p} to
obtain an \kbd{FpC}.

\fun{GEN}{FpC_FpV_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{ZC}~\kbd{x}
(seen as a column vector) by the \kbd{ZV}~\kbd{y} (seen as a row vector,
assumed to have compatible dimensions), and reduce modulo \kbd{p} to obtain
an \kbd{FpM}.

\fun{GEN}{FpM_mul}{GEN x, GEN y, GEN p} multiplies the two \kbd{ZM}s~\kbd{x}
and \kbd{y} (assumed to have compatible dimensions), and reduce modulo
\kbd{p} to obtain an \kbd{FpM}.

\fun{GEN}{FpM_FpC_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{ZM}~\kbd{x}
by the \kbd{ZC}~\kbd{y} (seen as a column vector, assumed to have compatible
dimensions), and reduce modulo \kbd{p} to obtain an \kbd{FpC}.

\fun{GEN}{FpM_FpC_mul_FpX}{GEN x, GEN y, GEN p, long v} is a memory-clean
version of
\bprog
  GEN tmp = FpM_FpC_mul(x,y,p);
  return RgV_to_RgX(tmp, v);
@eprog

\fun{GEN}{FpV_FpC_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{ZV}~\kbd{x}
(seen as a row vector) by the \kbd{ZC}~\kbd{y} (seen as a column vector,
assumed to have compatible dimensions), and reduce modulo \kbd{p} to obtain
an \kbd{Fp}.

\fun{GEN}{FpV_dotproduct}{GEN x,GEN y,GEN p} scalar product of
$x$ and $y$ (assumed to have the same length).

\fun{GEN}{FpV_dotsquare}{GEN x, GEN p} scalar product of $x$ with itself.
has \typ{INT} entries.

\subsubsec{\kbd{Fp}-linear algebra} The implementations are not
asymptotically efficient ($O(n^3)$ standard algorithms).

\fun{GEN}{FpM_deplin}{GEN x, GEN p} returns a non-trivial kernel vector,
or \kbd{NULL} if none exist.

\fun{GEN}{FpM_det}{GEN x, GEN p} as \kbd{det}

\fun{GEN}{FpM_gauss}{GEN a, GEN b, GEN p} as \kbd{gauss}

\fun{GEN}{FpM_image}{GEN x, GEN p} as \kbd{image}

\fun{GEN}{FpM_intersect}{GEN x, GEN y, GEN p} as \kbd{intersect}

\fun{GEN}{FpM_inv}{GEN x, GEN p} returns the inverse of \kbd{x}, or
\kbd{NULL} if \kbd{x} is not invertible.

\fun{GEN}{FpM_invimage}{GEN m, GEN v, GEN p} as \kbd{inverseimage}

\fun{GEN}{FpM_ker}{GEN x, GEN p} as \kbd{ker}

\fun{long}{FpM_rank}{GEN x, GEN p} as \kbd{rank}

\fun{GEN}{FpM_indexrank}{GEN x, GEN p} as \kbd{indexrank} but returns a
\typ{VECSMALL}

\fun{GEN}{FpM_suppl}{GEN x, GEN p} as \kbd{suppl}

\subsubsec{\kbd{Fq}-linear algebra}

\fun{GEN}{FqM_gauss}{GEN a, GEN b, GEN T, GEN p} as \kbd{gauss}

\fun{GEN}{FqM_ker}{GEN x, GEN T, GEN p} as \kbd{ker}

\fun{GEN}{FqM_suppl}{GEN x, GEN T, GEN p} as \kbd{suppl}

\subsec{\kbd{Flc} / \kbd{Flv}, \kbd{Flm}} See \kbd{FpV}, \kbd{FpM}
operations.

\fun{GEN}{Flv_copy}{GEN x} returns a copy of \kbd{x}.

\fun{GEN}{Flm_copy}{GEN x} returns a copy of \kbd{x}.

\fun{GEN}{Flm_Flc_mul}{GEN x, GEN y, ulong p} multiplies  \kbd{x} and \kbd{y}
(assumed to have compatible dimensions).

\fun{GEN}{Flm_Fl_mul}{GEN x, ulong y, ulong p} multiplies the \kbd{Flm}
\kbd{x} by \kbd{y}.

\fun{void}{Flm_Fl_mul_inplace}{GEN x, ulong y, ulong p} replaces
the \kbd{Flm} \kbd{x} by $\kbd{x}*\kbd{y}$.

\fun{GEN}{Flc_Fl_mul}{GEN x, ulong y, ulong p} multiplies the \kbd{Flv}
\kbd{x} by \kbd{y}.

\fun{void}{Flc_Fl_mul_inplace}{GEN x, ulong y, ulong p} replaces
the \kbd{Flc} \kbd{x} by $\kbd{x}*\kbd{y}$.

\fun{GEN}{Flc_Fl_div}{GEN x, ulong y, ulong p} divides the \kbd{Flv}
\kbd{x} by \kbd{y}.

\fun{void}{Flc_Fl_div_inplace}{GEN x, ulong y, ulong p} replaces
the \kbd{Flv} \kbd{x} by $\kbd{x}/\kbd{y}$.

\fun{GEN}{Flv_add}{GEN x, GEN y, ulong p} adds two \kbd{Flv}.

\fun{void}{Flv_add_inplace}{GEN x, GEN y, ulong p} replaces
$x$ by $x+y$.

\fun{GEN}{Flv_sub}{GEN x, GEN y, ulong p} subtracts \kbd{y} to \kbd{x}.

\fun{void}{Flv_sub_inplace}{GEN x, GEN y, ulong p} replaces
$x$ by $x-y$.

\fun{ulong}{Flv_dotproduct}{GEN x, GEN y, ulong p} returns the scalar product
of \kbd{x} and \kbd{y}

\fun{ulong}{Flv_sum}{GEN x, ulong p} returns the sums of the components of $x$.

\fun{GEN}{zero_Flm}{long m, long n} creates a \kbd{Flm} with \kbd{m} x \kbd{n}
components set to $0$. Note that the result allocates a
\emph{single} column, so modifying an entry in one column modifies it in
all columns.

\fun{GEN}{zero_Flm_copy}{long m, long n} creates a \kbd{Flm} with \kbd{m} x
\kbd{n} components set to $0$.

\fun{GEN}{zero_Flv}{long n} creates a \kbd{Flv} with \kbd{n} components set to
$0$.

\fun{GEN}{row_Flm}{GEN A, long x0} return $A[i,]$, the $i$-th row of the
\kbd{Flm} (or \kbd{zm}) $A$.

\fun{GEN}{Flm_mul}{GEN x, GEN y, ulong p} multiplies  \kbd{x} and \kbd{y}
(assumed to have compatible dimensions).

\fun{GEN}{Flm_charpoly}{GEN x, ulong p} return the characteristic polynomial of
the square \kbd{Flm} $x$, as a \kbd{Flx}.

\fun{GEN}{Flm_deplin}{GEN x, ulong p}

\fun{ulong}{Flm_det}{GEN x, ulong p}

\fun{ulong}{Flm_det_sp}{GEN x, ulong p}, as \kbd{Flm\_det}, in place (destroys~\kbd{x}).

\fun{GEN}{Flm_gauss}{GEN a, GEN b, ulong p}

\fun{GEN}{Flm_indexrank}{GEN x, ulong p}

\fun{GEN}{Flm_inv}{GEN x, ulong p}

\fun{GEN}{Flm_ker}{GEN x, ulong p}

\fun{GEN}{Flm_ker_sp}{GEN x, ulong p, long deplin}, as \kbd{Flm\_ker} (if
\kbd{deplin=0}) or \kbd{Flm\_deplin} (if \kbd{deplin=1}) , in place
(destroys~\kbd{x}).

\fun{long}{Flm_rank}{GEN x, ulong p}

\fun{GEN}{Flm_image}{GEN x, ulong p}

\fun{GEN}{Flm_transpose}{GEN x}

\fun{GEN}{Flm_hess}{GEN x, ulong p} upper Hessenberg form of $x$ over $\F_p$.

\subsec{\kbd{F2c} / \kbd{F2v}, \kbd{F2m}}  An \kbd{F2v}~\kbd{v} is a
\typ{VECSMALL} representing a vector over $\F_2$. Specifically \kbd{z[0]} is
the usual codeword, \kbd{z[1]} is the number of components of $v$ and the
coefficients are given by the bits of remaining words by increasing indices.

\fun{ulong}{F2v_coeff}{GEN x, long i} returns the coefficient $i\ge 1$ of $x$.

\fun{void}{F2v_clear}{GEN x, long i} sets the coefficient $i\ge 1$ of $x$ to $0$.

\fun{void}{F2v_flip}{GEN x, long i} adds $1$ to the coefficient $i\ge 1$ of $x$.

\fun{void}{F2v_set}{GEN x, long i} sets the coefficient $i\ge 1$ of $x$ to $1$.

\fun{ulong}{F2m_coeff}{GEN x, long i, long j} returns the coefficient $(i,j)$
of $x$.

\fun{void}{F2m_clear}{GEN x, long i, long j} sets the coefficient $(i,j)$ of $x$
to $0$.

\fun{void}{F2m_flip}{GEN x, long i, long j} adds $1$ to the coefficient $(i,j)$
of $x$.

\fun{void}{F2m_set}{GEN x, long i, long j} sets the coefficient $(i,j)$ of $x$
to $1$.

\fun{void}{F2m_copy}{GEN x} returns a copy of $x$.

\fun{GEN}{zero_F2v}{long n} creates a \kbd{F2v} with \kbd{n} components set to
$0$.

\fun{GEN}{zero_F2m}{long m, long n} creates a \kbd{Flm} with \kbd{m} x \kbd{n}
components set to $0$. Note that the result allocates a
\emph{single} column, so modifying an entry in one column modifies it in
all columns.

\fun{GEN}{zero_F2m_copy}{long m, long n} creates a \kbd{F2m} with \kbd{m} x
\kbd{n} components set to $0$.

\fun{GEN}{F2c_to_ZC}{GEN x}

\fun{GEN}{ZV_to_F2v}{GEN x}

\fun{GEN}{F2m_to_ZM}{GEN x}

\fun{GEN}{Flv_to_F2v}{GEN x}

\fun{GEN}{Flm_to_F2m}{GEN x}

\fun{GEN}{ZM_to_F2m}{GEN x}

\fun{void}{F2v_add_inplace}{GEN x, GEN y} replaces $x$ by $x+y$. It is
allowed for $y$ to be shorter than $x$.

\fun{ulong}{F2m_det}{GEN x}

\fun{ulong}{F2m_det_sp}{GEN x}, as \kbd{F2m\_det}, in place (destroys~\kbd{x}).

\fun{GEN}{F2m_deplin}{GEN x}

\fun{GEN}{F2m_ker}{GEN x}

\fun{GEN}{F2m_ker_sp}{GEN x, long deplin}, as \kbd{F2m\_ker} (if
\kbd{deplin=0}) or \kbd{F2m\_deplin} (if \kbd{deplin=1}) , in place
(destroys~\kbd{x}).

\subsec{\kbd{FlxqV}, \kbd{FlxqM}} See \kbd{FqV}, \kbd{FqM} operations.

\fun{GEN}{FlxqM_ker}{GEN x, GEN T, ulong p}

\subsec{\kbd{FpX}} Let \kbd{p} an understood \typ{INT}, to be given in
the function arguments; in practice \kbd{p} is not assumed to be prime, but
be wary. Recall than an \kbd{Fp} object is a \typ{INT}, preferrably belonging
to $[0, \kbd{p}-1]$; an \kbd{FpX} is a \typ{POL} in a fixed variable whose
coefficients are \kbd{Fp} objects. Unless mentioned otherwise, all outputs in
this section are \kbd{FpX}s. All operations are understood to take place in
$(\Z/\kbd{p}\Z)[X]$.

\subsubsec{Conversions} In what follows \kbd{p} is always a \typ{INT},
not necessarily prime.

\fun{int}{RgX_is_FpX}{GEN z, GEN *p}, \kbd{z} a \typ{POL},
checks if it can be mapped to a \kbd{FpX}, by checking \kbd{Rg\_is\_Fp}
coefficientwise.

\fun{GEN}{RgX_to_FpX}{GEN z, GEN p}, \kbd{z} a \typ{POL}, returns the
\kbd{FpX} obtained by applying \kbd{Rg\_to\_Fp} coefficientwise.

\fun{GEN}{FpX_red}{GEN z, GEN p}, \kbd{z} a \kbd{ZX}, returns \kbd{lift(z *
Mod(1,p))}, normalized.

\fun{GEN}{FpXV_red}{GEN z, GEN p}, \kbd{z} a \typ{VEC} of \kbd{ZX}. Applies
\kbd{FpX\_red} componentwise and returns the result (and we obtain a vector
of \kbd{FpX}s).

\subsubsec{Basic operations} In what follows \kbd{p} is always a \typ{INT},
not necessarily prime.

\noindent Now, except for \kbd{p}, the operands and outputs are all \kbd{FpX}
objects. Results are undefined on other inputs.

\fun{GEN}{FpX_add}{GEN x,GEN y, GEN p} adds \kbd{x} and \kbd{y}.

\fun{GEN}{FpX_neg}{GEN x,GEN p} returns $-\kbd{x}$, the components are
between $0$ and $p$ if this is the case for the components of $x$.

\fun{GEN}{FpX_renormalize}{GEN x, long l}, as \kbd{normalizepol}, where
$\kbd{l} = \kbd{lg(x)}$, in place.

\fun{GEN}{FpX_sub}{GEN x,GEN y,GEN p} returns $x - y$.

\fun{GEN}{FpX_mul}{GEN x,GEN y,GEN p} returns $x y$.

\fun{GEN}{FpX_sqr}{GEN x,GEN p} returns $\kbd{x}^2$.

\fun{GEN}{FpX_divrem}{GEN x, GEN y, GEN p, GEN *pr} returns the quotient
of \kbd{x} by \kbd{y}, and sets \kbd{pr} to the remainder.

\fun{GEN}{FpX_div}{GEN x, GEN y, GEN p} returns the quotient of \kbd{x} by
\kbd{y}.

\fun{GEN}{FpX_div_by_X_x}{GEN A, GEN a, GEN p, GEN *r} returns the
quotient of the \kbd{FpX}~\kbd{A} by $(X - \kbd{a})$, and sets \kbd{r} to the
remainder $\kbd{A}(\kbd{a})$.

\fun{GEN}{FpX_rem}{GEN x, GEN y, GEN p} returns the remainder \kbd{x} mod
\kbd{y}.

\fun{long}{FpX_valrem}{GEN x, GEN t, GEN p, GEN *r} The arguments \kbd{x} and
\kbd{e} being non-zero \kbd{FpX} returns the highest exponent $e$ such that
$\kbd{t}^{e}$ divides~\kbd{x}. The quotient $\kbd{x}/\kbd{t}^{e}$ is returned
in~\kbd{*r}. In particular, if \kbd{t} is irreducible, this returns the
valuation at \kbd{t} of~\kbd{x}, and \kbd{*r} is the prime-to-\kbd{t} part
of~\kbd{x}.

\fun{GEN}{FpX_deriv}{GEN x, GEN p} returns the derivative of \kbd{x}.
This function is not memory-clean, but nevertheless suitable for
\kbd{gerepileupto}.

\fun{GEN}{FpX_gcd}{GEN x, GEN y, GEN p} returns a (not necessarily monic)
greatest common divisor of $x$  and $y$.

\fun{GEN}{FpX_halfgcd}{GEN x, GEN y, GEN p} returns a two-by-two \kbd{FpXM} $M$ with determinant
$\pm 1$ such that the image $(a,b)$ of $(x,y)$ by $M$ has the property that
$\deg a \geq {\deg x \over 2} > \deg b$.

\fun{GEN}{FpX_extgcd}{GEN x, GEN y, GEN p, GEN *u, GEN *v} returns
$d = \text{GCD}(\kbd{x},\kbd{y})$ (not necessarily monic), and sets \kbd{*u},
\kbd{*v} to the Bezout coefficients such that $\kbd{*ux} + \kbd{*vy} = d$.
If \kbd{*u} is set to \kbd{NULL}, it is not computed which is a bit faster.
This is useful when computing the inverse of $y$ modulo $x$.

\fun{GEN}{FpX_center}{GEN z, GEN p, GEN pov2} returns the polynomial whose
coefficient belong to the symmetric residue system. Assumes the coefficients
already belong to $[0,\kbd{p}-1]$) and \kbd{pov2} is \kbd{shifti(p,-1)}.


\subsubsec{Mixed operations}
The following functions implement arithmetic operations between \kbd{FpX}
and \kbd{Fp} operands, the result being of type \kbd{FpX}. The integer
\kbd{p} need not be prime.

\fun{GEN}{FpX_Fp_add}{GEN y, GEN x, GEN p} add the \kbd{Fp}~\kbd{x} to the
\kbd{FpX}~\kbd{y}.

\fun{GEN}{FpX_Fp_add_shallow}{GEN y, GEN x, GEN p} add the \kbd{Fp}~\kbd{x}
to the \kbd{FpX}~\kbd{y}, using a shallow copy (result not suitable for
\kbd{gerepileupto})

\fun{GEN}{FpX_Fp_sub}{GEN y, GEN x, GEN p} subtract the \kbd{Fp}~\kbd{x} from
the \kbd{FpX}~\kbd{y}.

\fun{GEN}{FpX_Fp_sub_shallow}{GEN y, GEN x, GEN p} subtract the
\kbd{Fp}~\kbd{x} from the \kbd{FpX}~\kbd{y}, using a shallow copy (result not
suitable for \kbd{gerepileupto})

\fun{GEN}{Fp_FpX_sub}{GEN x,GEN y,GEN p} returns $x - y$, where $x$ is
a \typ{INT} and $y$ an \kbd{FpX}.

\fun{GEN}{FpX_Fp_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{FpX}~\kbd{x}
by the \kbd{Fp}~\kbd{y}.

\fun{GEN}{FpX_Fp_mul_to_monic}{GEN y,GEN x,GEN p} returns $y*x$ assuming the
result is monic of the same degree as $y$ (in particular $x\neq 0$).

\subsubsec{Miscellaneous operations}

\fun{GEN}{FpX_normalize}{GEN z, GEN p} divides the \kbd{FpX}~\kbd{z} by its
leading coefficient. If the latter is~$1$, \kbd{z} itself is returned, not a
copy. If not, the inverse remains uncollected on the stack.

\fun{GEN}{FpX_invMontgomery}{GEN T, GEN p}, returns the Montgomery inverse
$M$ of $T$ defined by $M(x)\*x^n\*T(1/x)\equiv 1\pmod{x^{n-1}}$ where $n$ is
the degree of $T$.

\fun{GEN}{FpX_rem_Montgomery}{GEN x, GEN mg, GEN T, GEN p}, returns
\kbd{x} modulo \kbd{T}, assuming that $\deg x\leq 2\*(\deg{T} - 1)$ where
\kbd{mg} is the Montgomery inverse of \kbd{T}.

\fun{GEN}{FpX_rescale}{GEN P, GEN h, GEN p} returns $h^{\deg(P)} P(x/h)$.
\kbd{P} is an \kbd{FpX} and \kbd{h} is a non-zero \kbd{Fp} (the routine would
work with any non-zero \typ{INT} but is not efficient in this case).

\fun{GEN}{FpX_eval}{GEN x, GEN y, GEN p} evaluates the \kbd{FpX}~\kbd{x}
at the \kbd{Fp}~\kbd{y}. The result is an~\kbd{Fp}.

\fun{GEN}{FpXY_eval}{GEN Q, GEN y, GEN x, GEN p} $Q$ an \kbd{FpXY}, i.e.~a
\typ{POL} with \kbd{Fp} or \kbd{FpX} coefficients representing an element of
$\F_p[X][Y]$. Returns the \kbd{Fp} $Q(x,y)$.

\fun{GEN}{FpXY_evalx}{GEN Q, GEN x, GEN p} $Q$ an \kbd{FpXY}, i.e.~a
\typ{POL} with \kbd{Fp} or \kbd{FpX} coefficients representing an element of
$\F_p[X][Y]$. Returns the \kbd{FpY} $Q(x,Y)$.

\fun{GEN}{FpXY_evaly}{GEN Q, GEN y, GEN p, long vy} $Q$ an \kbd{FpXY}, i.e.~a
\typ{POL} with \kbd{Fp} or \kbd{FpX} coefficients representing an element of
$\F_p[X][Y]$. Returns the \kbd{FpX} $Q(X,y)$.

\fun{GEN}{FpXV_FpC_mul}{GEN V, GEN W, GEN p} multiplies a non-empty line
vector of\kbd{FpX} by a column vector of \kbd{Fp} of compatible dimensions.
The result is an~\kbd{FpX}.

\fun{GEN}{FpXV_prod}{GEN V, GEN p}, \kbd{V} being a vector of \kbd{FpX},
returns their product.

\fun{GEN}{FpV_roots_to_pol}{GEN V, GEN p, long v}, \kbd{V} being a vector
of \kbd{INT}s, returns the monic \kbd{FpX}
$\prod_i (\kbd{pol\_x[v]} - \kbd{V[i]})$.

\fun{GEN}{FpX_chinese_coprime}{GEN x,GEN y, GEN Tx,GEN Ty, GEN Tz, GEN p}:
returns an \kbd{FpX}, congruent to \kbd{x} mod \kbd{Tx} and to \kbd{y} mod
\kbd{Ty}. Assumes \kbd{Tx} and \kbd{Ty} are coprime, and \kbd{Tz = Tx * Ty}
or \kbd{NULL} (in which case it is computed within).

\fun{GEN}{FpV_polint}{GEN x, GEN y, GEN p} returns the \kbd{FpX}
interpolation polynomial with value \kbd{y[i]} at \kbd{x[i]}. Assumes lengths
are the same, components are \typ{INT}s, and the \kbd{x[i]} are distinct
modulo \kbd{p}.

\fun{int}{FpX_is_squarefree}{GEN f, GEN p} returns $1$ if the
\kbd{FpX}~\kbd{f} is squarefree, $0$ otherwise.

\fun{int}{FpX_is_irred}{GEN f, GEN p} returns $1$ if the \kbd{FpX}~\kbd{f}
is irreducible, $0$ otherwise. Assumes that \kbd{p} is prime. If~\kbd{f} has
few factors, \kbd{FpX\_nbfact(f,p) == 1} is much faster.

\fun{int}{FpX_is_totally_split}{GEN f, GEN p} returns $1$ if the
\kbd{FpX}~\kbd{f} splits into a product of distinct linear factors, $0$
otherwise. Assumes that \kbd{p} is prime.

\fun{GEN}{FpX_factor}{GEN f, GEN p}, factors the \kbd{FpX}~\kbd{f}. Assumes
that \kbd{p} is prime. The returned value \kbd{v} is a \typ{VEC} with two
components: \kbd{v[1]} is a vector of distinct irreducible (\kbd{FpX})
factors, and \kbd{v[2]} is a \typ{VECSMALL} of corresponding exponents. The
order of the factors is deterministic (the computation is not).

\fun{long}{FpX_nbfact}{GEN f, GEN p}, assuming the \kbd{FpX}~f is squarefree,
returns the number of its irreducible factors. Assumes that \kbd{p} is prime.

\fun{long}{FpX_degfact}{GEN f, GEN p}, as \kbd{FpX\_factor}, but the
degrees of the irreducible factors are returned instead of the factors
themselves (as a \typ{VECSMALL}). Assumes that \kbd{p} is prime.

\fun{long}{FpX_nbroots}{GEN f, GEN p} returns the number of distinct
roots in \kbd{\Z/p\Z} of the \kbd{FpX}~\kbd{f}. Assumes that \kbd{p} is prime.

\fun{GEN}{FpX_oneroot}{GEN f, GEN p} returns one root in \kbd{\Z/p\Z} of
the \kbd{FpX}~\kbd{f}. Return \kbd{NULL} if no root exists.
Assumes that \kbd{p} is prime.

\fun{GEN}{FpX_roots}{GEN f, GEN p} returns the roots in \kbd{\Z/p\Z} of
the \kbd{FpX}~\kbd{f} (without multiplicity, as a vector of \kbd{Fp}s).
Assumes that \kbd{p} is prime.

\fun{GEN}{random_FpX}{long d, long v, GEN p} returns a random \kbd{FpX}
in variable \kbd{v}, of degree less than~\kbd{d}.

\fun{GEN}{FpX_resultant}{GEN x, GEN y, GEN p} returns the resultant
of \kbd{x} and \kbd{y}, both \kbd{FpX}. The result is a \typ{INT}
belonging to $[0,p-1]$.

\fun{GEN}{FpX_FpXY_resultant}{GEN a, GEN b, GEN p}, \kbd{a} a \typ{POL} of
\typ{INT}s (say in variable $X$), \kbd{b} a \typ{POL} (say in variable $X$)
whose coefficients are either \typ{POL}s in $\Z[Y]$ or \typ{INT}s.
Returns $\text{Res}_X(a, b)$ in $\F_p[Y]$ as an \kbd{FpY}. The function
assumes that $X$ has lower priority than $Y$.

\subsec{\kbd{FpXQ}, \kbd{Fq}} Let \kbd{p} a \typ{INT} and \kbd{T} an
\kbd{FpX} for \kbd{p}, both to be given in the function arguments; an \kbd{FpXQ}
object is an \kbd{FpX} whose degree is strictly less than the degree of
\kbd{T}. An \kbd{Fq} is either an \kbd{FpXQ} or an \kbd{Fp}. Both represent
a class in $(\Z/\kbd{p}\Z)[X] / (T)$, in which all operations below take
place. In addition, \kbd{Fq} routines also allow $\kbd{T} = \kbd{NULL}$, in
which case no reduction mod \kbd{T} is performed on the result.

For efficiency, the routines in this section may leave small unused objects
behind on the stack (their output is still suitable for \kbd{gerepileupto}).
Besides \kbd{T} and \kbd{p}, arguments are either \kbd{FpXQ} or \kbd{Fq}
depending on the function name. (All \kbd{Fq} routines accept \kbd{FpXQ}s by
definition, not the other way round.)

\fun{GEN}{Rg_is_FpXQ}{GEN z, GEN *T, GEN *p}, checks if \kbd{z} is a \kbd{GEN}
which can be mapped to $\F_p[X]/(T)$: anything for which \kbd{Rg\_is\_Fp} return
$1$, a \typ{POL} for which \kbd{RgX\_to\_FpX} return $1$, a \typ{POLMOD}
whose modulus is equal to \kbd{*T} if \kbd{*T} is not \kbd{NULL} (once mapped
to a \kbd{FpX}).
If an integer modulus is found it is put in \kbd{*p}, else \kbd{*p} is left
unchanged. If a polynomial modulus is found it is put in \kbd{*T}, else
\kbd{*T} is left unchanged.

\fun{int}{RgX_is_FpXQX}{GEN z, GEN *T, GEN *p}, \kbd{z} a \typ{POL},
checks if it can be mapped to a \kbd{FpXQX}, by checking \kbd{Rg\_is\_FpXQ}
coefficientwise.

\fun{GEN}{Rg_to_FpXQ}{GEN z, GEN T, GEN p}, \kbd{z} a \kbd{GEN} which can be
mapped to $\F_p[X]/(T)$: anything \kbd{Rg\_to\_Fp} can be applied to,
a \typ{POL} to which \kbd{RgX\_to\_FpX} can be applied to, a \typ{POLMOD}
whose modulus is divisible by $T$ (once mapped to a \kbd{FpX}), a suitable
\typ{RFRAC}. Returns \kbd{z} as an \kbd{FpXQ}, normalized.

\fun{GEN}{RgX_to_FpXQX}{GEN z, GEN T, GEN p}, \kbd{z} a \typ{POL}, returns the
\kbd{FpXQ} obtained by applying \kbd{Rg\_to\_FpXQ} coefficientwise.

\fun{GEN}{RgX_to_FqX}{GEN z, GEN T, GEN p}: let \kbd{z} be a \typ{POL};
returns the \kbd{FpXQ} obtained by applying \kbd{Rg\_to\_FpXQ}
coefficientwise and simplifying scalars to \typ{INT}s.

\fun{GEN}{Fq_red}{GEN x, GEN T, GEN p}, \kbd{x} a \kbd{ZX} or \typ{INT},
reduce it to an \kbd{Fq} ($\kbd{T} = \kbd{NULL}$ is allowed iff \kbd{x} is a
\typ{INT}).

\fun{GEN}{FqX_red}{GEN x, GEN T, GEN p}, \kbd{x} a \typ{POL}
whose coefficients are \kbd{ZX}s or \typ{INT}s, reduce them to \kbd{Fq}s. (If
$\kbd{T} = \kbd{NULL}$, as \kbd{FpXX\_red(x, p)}.)

\fun{GEN}{FqV_red}{GEN x, GEN T, GEN p}, \kbd{x} a vector of \kbd{ZX}s or
\typ{INT}s, reduce them to \kbd{Fq}s. (If $\kbd{T} = \kbd{NULL}$, only
reduce components mod \kbd{p} to \kbd{FpX}s or \kbd{Fp}s.)

\fun{GEN}{FpXQ_red}{GEN x, GEN T,GEN p} \kbd{x} a \typ{POL}
whose coefficients are \typ{INT}s, reduce them to \kbd{FpXQ}s.

\fun{GEN}{FpXQ_add}{GEN x, GEN y, GEN T,GEN p}

\fun{GEN}{FpXQ_sub}{GEN x, GEN y, GEN T,GEN p}

\fun{GEN}{FpXQ_mul}{GEN x, GEN y, GEN T,GEN p}

\fun{GEN}{FpXQ_sqr}{GEN x, GEN T, GEN p}

\fun{GEN}{FpXQ_div}{GEN x, GEN y, GEN T,GEN p}

\fun{GEN}{FpXQ_inv}{GEN x, GEN T, GEN p} computes the inverse of \kbd{x}

\fun{GEN}{FpXQ_invsafe}{GEN x,GEN T,GEN p}, as \kbd{FpXQ\_inv}, returning
\kbd{NULL} if \kbd{x} is not invertible.

\fun{GEN}{FpXQX_renormalize}{GEN x, long lx}

\fun{GEN}{FpXQ_pow}{GEN x, GEN n, GEN T, GEN p} computes $\kbd{x}^\kbd{n}$.

\fun{GEN}{FpXQ_log}{GEN a, GEN g, GEN ord, GEN T, GEN p} Let \kbd{g} be of
order \kbd{ord} in the finite field $\F_p[X]/(T)$. Return $e$ such that
$a^e=g$. If $e$ does not exists, the result is currently undefined. Assumes
that \kbd{T} is irreducible mod \kbd{p}.

\fun{GEN}{Fp_FpXQ_log}{GEN a, GEN g, GEN ord, GEN T, GEN p} As
\kbd{FpXQ\_log}, \kbd{a} being a \kbd{Fp}.

\fun{int}{FpXQ_issquare}{GEN x, GEN T, GEN p} returns $1$ if $x$ is a square
and $0$ otherwise. Assumes that \kbd{T} is irreducible mod \kbd{p}.

\fun{GEN}{FpXQ_order}{GEN a, GEN ord, GEN T, GEN p} returns the order of the
\typ{FpXQ} \kbd{a}. If \kbd{o} is non-\kbd{NULL}, it is assumed that \kbd{o}
is a multiple of the order of \kbd{a}, either as a \typ{INT} or a
factorization matrix. Assumes that \kbd{T} is irreducible mod \kbd{p}.

\fun{GEN}{FpXQ_sqrtn}{GEN x, GEN n, GEN T, GEN p, GEN *zn} returns an
\kbd{n}-th root of $\kbd{x}$.  Return \kbd{NULL} if \kbd{x} is not an
\kbd{n}-th power residue. Otherwise, if \kbd{zn} is non-\kbd{NULL} set it to a
primitive \kbd{n}-th root of the unity. Assumes that \kbd{T} is irreducible mod \kbd{p}.

\fun{GEN}{Fq_add}{GEN x, GEN y, GEN T/*unused*/, GEN p}

\fun{GEN}{Fq_sub}{GEN x, GEN y, GEN T/*unused*/, GEN p}

\fun{GEN}{Fq_mul}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{Fq_Fp_mul}{GEN x, GEN y, GEN T, GEN p} multiplies the \kbd{Fq} $x$
by the \typ{INT} $y$.

\fun{GEN}{Fq_sqr}{GEN x, GEN T, GEN p}

\fun{GEN}{Fq_neg}{GEN x, GEN T, GEN p}

\fun{GEN}{Fq_neg_inv}{GEN x, GEN T, GEN p} computes $-\kbd{x}^{-1}$

\fun{GEN}{Fq_inv}{GEN x, GEN pol, GEN p} computes $\kbd{x}^{-1}$, raising an
error if \kbd{x} is not invertible.

\fun{GEN}{Fq_invsafe}{GEN x, GEN pol, GEN p} as \kbd{Fq\_inv}, but returns
\kbd{NULL} if \kbd{x} is not invertible.

\fun{GEN}{FqV_inv}{GEN x, GEN T, GEN p} $x$ being a vector of \typ{Fq}s,
return the vector of inverses of the $x[i]$. The routine uses Montgomery's
trick, and involves a single inversion, plus $3(N-1)$ multiplications for
$N$ entries. The routine is not stack-clean: $2N$ \kbd{FpXQ} are left on
stack, besides the $N$ in the result.

\fun{GEN}{Fq_pow}{GEN x, GEN n, GEN pol, GEN p} returns $\kbd{x}^\kbd{n}$.

\fun{GEN}{Fq_sqrt}{GEN x, GEN T, GEN p} returns a square root of \kbd{x}.
Return \kbd{NULL} if \kbd{x} is not a square.

\fun{GEN}{FpXQ_charpoly}{GEN x, GEN T, GEN p} returns the characteristic
polynomial of \kbd{x}

\fun{GEN}{FpXQ_minpoly}{GEN x, GEN T, GEN p} returns the minimal polynomial
of \kbd{x}

\fun{GEN}{FpXQ_norm}{GEN x, GEN T, GEN p} returns the norm of \kbd{x}

\fun{GEN}{FpXQ_trace}{GEN x, GEN T, GEN p} returns the trace of \kbd{x}

\fun{GEN}{FpXQ_conjvec}{GEN x, GEN T, GEN p} returns the vector of conjugates
$[x,x^p,x^{p^2},\ldots,x^{p^{n-1}}]$ where $n$ is the degree of $T$.

\fun{GEN}{gener_FpXQ}{GEN T, GEN p, GEN *po} returns a primitive root modulo
$(T,p)$. $T$ is an \kbd{FpX} assumed to be irreducible modulo the prime
$p$. If \kbd{po} is not \kbd{NULL} it is set to $[o,\var{fa}]$, where $o$ is
the order of the multiplicative group of the finite field, and \var{fa} is
its factorization.

\fun{GEN}{FpXQ_powers}{GEN x, long n, GEN T, GEN p} returns $[\kbd{x}^0,
\dots, \kbd{x}^\kbd{n}]$ as a \typ{VEC} of \kbd{FpXQ}s.

\fun{GEN}{FpXQ_matrix_pow}{GEN x, long m, long n, GEN T, GEN p}, as
\kbd{FpXQ\_powers}$(x, n-1, T, p)$, but returns the powers as a an
$m\times n$ matrix. Usually, we have $m = n = \deg T$.

\fun{GEN}{FpX_FpXQ_eval}{GEN f,GEN x,GEN T,GEN p} returns
$\kbd{f}(\kbd{x})$.

\fun{GEN}{FpX_FpXQV_eval}{GEN f,GEN V,GEN T,GEN p} returns
$\kbd{f}(\kbd{x})$, assuming that \kbd{V} was computed by
$\kbd{FpXQ\_powers}(\kbd{x}, n, \kbd{T}, \kbd{p})$.

\subsec{\kbd{FpXX}}
Contrary to what the name implies, an \kbd{FpXX} is a \typ{POL} whose
coefficients are either \typ{INT}s or \typ{FpX}s. This reduces memory
overhead at the expense of consistency.

\fun{GEN}{FpXX_red}{GEN z, GEN p}, \kbd{z} a \typ{POL} whose coefficients are
either \kbd{ZX}s or \typ{INT}s. Returns the \typ{POL} equal to \kbd{z} with
all components reduced modulo \kbd{p}.

\fun{GEN}{FpXX_renormalize}{GEN x, long l}, as \kbd{normalizepol}, where
$\kbd{l} = \kbd{lg(x)}$, in place.

\fun{GEN}{FpXX_add}{GEN x, GEN y, GEN p} adds \kbd{x} and \kbd{y}.

\fun{GEN}{FpXX_sub}{GEN x, GEN y, GEN p} returns $\kbd{x}-\kbd{y}$.

\fun{GEN}{FpXX_Fp_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{FpXX}~\kbd{x}
by the \kbd{Fp}~\kbd{y}.

\subsec{\kbd{FpXQX}, \kbd{FqX}}
Contrary to what the name implies, an \kbd{FpXQX} is a \typ{POL} whose
coefficients are \kbd{Fq}s. So the only difference between \kbd{FqX} and
\kbd{FpXQX} routines is that $\kbd{T} = \kbd{NULL}$ is not allowed in the
latter. (It was thought more useful to allow \typ{INT} components than to
enforce strict consistency, which would not imply any efficiency gain.)

\subsubsec{Basic operations}

\fun{GEN}{FqX_add}{GEN x,GEN y,GEN T,GEN p}

\fun{GEN}{FqX_sub}{GEN x,GEN y,GEN T,GEN p}

\fun{GEN}{FqX_mul}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FqX_Fq_mul}{GEN x, GEN y, GEN T, GEN p} multiplies the
\kbd{FqX}~\kbd{x} by the \kbd{Fq}~\kbd{y}.

\fun{GEN}{FqX_Fp_mul}{GEN x, GEN y, GEN T, GEN p} multiplies the
\kbd{FqX}~\kbd{x} by the \typ{INT}~\kbd{y}.

\fun{GEN}{FqX_Fq_mul_to_monic}{GEN x, GEN y, GEN T, GEN p}
returns $x*y$ assuming the result is monic of the same degree as $x$ (in
particular $y\neq 0$).

\fun{GEN}{FqX_normalize}{GEN z, GEN T, GEN p} divides the \kbd{FqX}~\kbd{z}
by its leading term.

\fun{GEN}{FqX_sqr}{GEN x, GEN T, GEN p}

\fun{GEN}{FqX_divrem}{GEN x, GEN y, GEN T, GEN p, GEN *z}

\fun{GEN}{FqX_div}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FqX_rem}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FqX_deriv}{GEN x, GEN T, GEN p} returns the derivative of \kbd{x}.
(This function is suitable for \kbd{gerepilupto} but not memory-clean.)

\fun{GEN}{FqX_translate}{GEN P, GEN c, GEN T, GEN p} let $c$ be an \kbd{Fq}
defined modulo $(p, T)$, and let $P$ be an \kbd{FqX}; returns the translated
\kbd{FqX} of $P(X+c)$.

\fun{GEN}{FqX_gcd}{GEN P, GEN Q, GEN T, GEN p} returns a (not necessarily
monic) greatest common divisor of $x$  and $y$.

\fun{GEN}{FqX_extgcd}{GEN x, GEN y, GEN T, GEN p, GEN *ptu, GEN *ptv}
returns $d = \text{GCD}(\kbd{x},\kbd{y})$ (not necessarily monic), and sets
\kbd{*u}, \kbd{*v} to the Bezout coefficients such that $\kbd{*ux} +
\kbd{*vy} = d$.

\fun{GEN}{FqX_eval}{GEN x, GEN y, GEN T, GEN p} evaluates the \kbd{FqX}~\kbd{x}
at the \kbd{Fq}~\kbd{y}. The result is an~\kbd{Fq}.

\fun{GEN}{FpXQX_red}{GEN z, GEN T, GEN p} \kbd{z} a \typ{POL} whose
coefficients are \kbd{ZX}s or \typ{INT}s, reduce them to \kbd{FpXQ}s.

\fun{GEN}{FpXQX_mul}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FpXQX_FpXQ_mul}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FpXQX_sqr}{GEN x, GEN T, GEN p}

\fun{GEN}{FpXQX_divrem}{GEN x, GEN y, GEN T, GEN p, GEN *pr}

\fun{GEN}{FpXQX_div}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FpXQX_rem}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FpXQXV_prod}{GEN V, GEN T, GEN p}, \kbd{V} being a vector of
\kbd{FpXQX}, returns their product.

\fun{GEN}{FpXQX_gcd}{GEN x, GEN y, GEN T, GEN p}

\fun{GEN}{FpXQX_extgcd}{GEN x, GEN y, GEN T, GEN p, GEN *ptu, GEN *ptv}

\fun{GEN}{FpXQXQ_div}{GEN x, GEN y, GEN S, GEN T, GEN p}, \kbd{x}, \kbd{y} and
\kbd{S} being \kbd{FpXQX}s, returns $\kbd{x}*\kbd{y}^{-1}$ modulo \kbd{S}.

\fun{GEN}{FpXQXQ_inv}{GEN x, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FpXQX}s, returns $\kbd{x}^{-1}$ modulo \kbd{S}.

\fun{GEN}{FpXQXQ_invsafe}{GEN x, GEN S, GEN T,GEN p}, as \kbd{FpXQXQ\_inv},
returning \kbd{NULL} if \kbd{x} is not invertible.

\fun{GEN}{FpXQXQ_mul}{GEN x, GEN y, GEN S, GEN T, GEN p}, \kbd{x}, \kbd{y} and
\kbd{S} being \kbd{FpXQX}s, returns $\kbd{x}\*\kbd{y}$ modulo \kbd{S}.

\fun{GEN}{FpXQXQ_sqr}{GEN x, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FpXQX}s, returns $\kbd{x}^2$ modulo \kbd{S}.

\fun{GEN}{FpXQXQ_pow}{GEN x, GEN n, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FpXQX}s, returns $\kbd{x}^\kbd{n}$ modulo \kbd{S}.

\fun{GEN}{FqXQ_add}{GEN x, GEN y, GEN S, GEN T, GEN p}, \kbd{x}, \kbd{y} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x} + \kbd{y}$ modulo \kbd{S}.

\fun{GEN}{FqXQ_sub}{GEN x, GEN y, GEN S, GEN T, GEN p}, \kbd{x}, \kbd{y} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x} - \kbd{y}$ modulo \kbd{S}.

\fun{GEN}{FqXQ_mul}{GEN x, GEN y, GEN S, GEN T, GEN p}, \kbd{x}, \kbd{y} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x}\*\kbd{y}$ modulo \kbd{S}.

\fun{GEN}{FqXQ_div}{GEN x, GEN y, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x}/\kbd{y}$ modulo \kbd{S}.

\fun{GEN}{FqXQ_inv}{GEN x, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x}^{-1}$ modulo \kbd{S}.

\fun{GEN}{FqXQ_invsafe}{GEN x, GEN S, GEN T, GEN p} , as \kbd{FqXQ\_inv},
returning \kbd{NULL} if \kbd{x} is not invertible.

\fun{GEN}{FqXQ_sqr}{GEN x, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x}^2$ modulo \kbd{S}.

\fun{GEN}{FqXQ_pow}{GEN x, GEN n, GEN S, GEN T, GEN p}, \kbd{x} and
\kbd{S} being \kbd{FqX}s, returns $\kbd{x}^\kbd{n}$ modulo \kbd{S}.

\fun{GEN}{FqV_roots_to_pol}{GEN V, GEN T, GEN p, long v},
\kbd{V} being a vector of \kbd{Fq}s, returns the monic \kbd{FqX}
$\prod_i (\kbd{pol\_x[v]} - \kbd{V[i]})$.

\fun{GEN}{FpXYQQ_pow}{GEN x, GEN n, GEN S, GEN T, GEN p}, \kbd{x} being a
\kbd{FpXY}, \kbd{T} being a \kbd{FpX} and \kbd{S} being a \kbd{FpY},
return $x^n \pmod{S,T,p}$.

\subsubsec{Miscellaneous operations}

\fun{GEN}{init_Fq}{GEN p, long n, long v} returns an irreducible polynomial
of degree $\kbd{n} > 0$ over $\F_p$, in variable \kbd{v}.

\fun{int}{FqX_is_squarefree}{GEN P, GEN T, GEN p}

\fun{GEN}{FqX_roots}{GEN x, GEN T, GEN p} return the roots of \kbd{x} in
$\F_p[X]/(T)$. Assumes \kbd{p} is prime and \kbd{T} irreducible in $\F_p[X]$.

\fun{GEN}{FqX_factor}{GEN x, GEN T, GEN p} same output convention as
\kbd{FpX\_factor}. Assumes \kbd{p} is prime and \kbd{T} irreducible
in $\F_p[X]$.

\fun{GEN}{FpX_factorff}{GEN P, GEN p, GEN T}. Assumes \kbd{p} prime
and \kbd{T} irreducible in $\F_p[X]$. Factor the \kbd{FpX} \kbd{P}
over the finite field $\F_p[Y]/(T(Y))$. See \kbd{FpX\_factorff\_irred}
if \kbd{P} is known to be irreducible of $\F_p$.

\fun{GEN}{FpX_rootsff}{GEN P, GEN p, GEN T}. Assumes \kbd{p} prime
and \kbd{T} irreducible in $\F_p[X]$. Returns the roots of the \kbd{FpX}
\kbd{P} belonging to the finite field $\F_p[Y]/(T(Y))$.

\fun{GEN}{FpX_factorff_irred}{GEN P, GEN T, GEN p}. Assumes \kbd{p} prime
and \kbd{T} irreducible in $\F_p[X]$. Factors the \emph{irreducible}
\kbd{FpX} \kbd{P} over the finite field $\F_p[Y]/(T(Y))$ and returns the
vector of irreducible \kbd{FqX}s factors (the exponents, being all equal to
$1$, are not included).

\fun{GEN}{FpX_ffisom}{GEN P, GEN Q, GEN p}. Assumes \kbd{p} prime,
\kbd{P}, \kbd{Q} are \kbd{ZX}s, both irreducible mod \kbd{p}, and
$\deg(P) \mid \deg Q$. Outputs a monomorphism between $\F_p[X]/(P)$ and
$\F_p[X]/(Q)$, as a polynomial $R$ such that $\kbd{Q} \mid \kbd{P}(R)$ in
$\F_p[X]$. If \kbd{P} and \kbd{Q} have the same degree, it is of course an
isomorphism.

\fun{void}{FpX_ffintersect}{GEN P, GEN Q, long n, GEN p, GEN *SP,GEN *SQ, GEN
MA,GEN MB}\hfil\break
Assumes \kbd{p} is prime, \kbd{P}, \kbd{Q} are \kbd{ZX}s, both
irreducible mod \kbd{p}, and \kbd{n} divides both the degree of \kbd{P} and
\kbd{Q}. Compute \kbd{SP} and \kbd{SQ} such that the subfield of
$\F_p[X]/(P)$ generated by \kbd{SP} and the subfield of $\F_p[X]/(Q)$
generated by \kbd{SQ} are isomorphic of degree \kbd{n}. The polynomials
\kbd{P} and \kbd{Q} do not need to be of the same variable. If \kbd{MA}
(resp. \kbd{MB}) is not \kbd{NULL}, it must be the matrix of the Frobenius
map in $\F_p[X]/(P)$ (resp.~$\F_p[X]/(Q)$).

\fun{GEN}{FpXQ_ffisom_inv}{GEN S, GEN T, GEN p}. Assumes \kbd{p} is prime,
\kbd{T} a \kbd{ZX}, which is irreducible modulo \kbd{p}, \kbd{S} a
\kbd{ZX} representing an automorphism of $\F_q := \F_p[X]/(\kbd{T})$.
($\kbd{S}(X)$ is the image of $X$ by the automorphism.) Returns the
inverse automorphism of \kbd{S}, in the same format, i.e.~an \kbd{FpX}~$H$
such that $H(\kbd{S}) \equiv X$ modulo $(\kbd{T}, \kbd{p})$.

\fun{long}{FqX_nbfact}{GEN u, GEN T, GEN p}.
Assumes \kbd{p} is prime and \kbd{T} irreducible in $\F_p[X]$.

\fun{long}{FqX_nbroots}{GEN f, GEN T, GEN p}
Assumes \kbd{p} is prime and \kbd{T} irreducible in $\F_p[X]$.

\subsec{\kbd{Flx}} Let \kbd{p} an understood \kbd{ulong}, assumed to be
prime, to be given the the function arguments; an \kbd{Fl} is an \kbd{ulong}
belonging to $[0,\kbd{p}-1]$, an \kbd{Flx}~\kbd{z} is a \typ{VECSMALL}
representing a polynomial with small integer coefficients. Specifically
\kbd{z[0]} is the usual codeword, \kbd{z[1] = evalvarn($v$)} for some
variable $v$, then the coefficients by increasing degree. An \kbd{FlxX} is a
\typ{POL} whose coefficients are \kbd{Flx}s.

\noindent In the following, an argument called \kbd{sv} is of the form
\kbd{evalvarn}$(v)$ for some variable number~$v$.

\subsubsec{Basic operations}

\fun{ulong}{Rg_to_Fl}{GEN z, ulong p}, \kbd{z} which can be mapped to
$\Z/p\Z$: a \typ{INT}, a \typ{INTMOD} whose modulus is divisible by $p$,
a \typ{FRAC} whose denominator is coprime to $p$, or a \typ{PADIC} with
underlying prime $\ell$ satisfying $p = \ell^n$ for some $n$ (less than the
accuracy of the input). Returns \kbd{lift(z * Mod(1,p))}, normalized, as an
\kbd{Fl}.

\fun{ulong}{padic_to_Fl}{GEN x, ulong p} special case of \tet{Rg_to_Fl},
for a $x$ a \typ{PADIC}.

\fun{GEN}{Flx_red}{GEN z, ulong p} converts from \kbd{zx} with
non-negative coefficients to \kbd{Flx} (by reducing them mod \kbd{p}).

\fun{int}{Flx_equal1}{GEN x} returns 1 (true) if the \kbd{Flx x} is equal to~1,
0~(false) otherwise.

\fun{GEN}{Flx_copy}{GEN x} returns a copy of \kbd{x}.

\fun{GEN}{Flx_add}{GEN x, GEN y, ulong p}

\fun{GEN}{Flx_Fl_add}{GEN y, ulong x, ulong p}

\fun{GEN}{Flx_neg}{GEN x, ulong p}

\fun{GEN}{Flx_neg_inplace}{GEN x, ulong p}, same as \kbd{Flx\_neg}, in place
(\kbd{x} is destroyed).

\fun{GEN}{Flx_sub}{GEN x, GEN y, ulong p}

\fun{GEN}{Flx_mul}{GEN x, GEN y, ulong p}

\fun{GEN}{Flx_Fl_mul}{GEN y, ulong x, ulong p}

\fun{GEN}{Flx_Fl_mul_to_monic}{GEN y, ulong x, ulong p} returns $y*x$
assuming the result is monic of the same degree as $y$ (in particular $x\neq
0$).

\fun{GEN}{Flx_sqr}{GEN x, ulong p}

\fun{GEN}{Flx_divrem}{GEN x, GEN y, ulong p, GEN *pr}

\fun{GEN}{Flx_div}{GEN x, GEN y, ulong p}

\fun{GEN}{Flx_rem}{GEN x, GEN y, ulong p}

\fun{GEN}{Flx_deriv}{GEN z, ulong p}

\fun{GEN}{Flx_gcd}{GEN a, GEN b, ulong p} returns a (not necessarily monic)
greatest common divisor of $x$  and $y$.

\fun{GEN}{Flx_halfgcd}{GEN x, GEN y, GEN p} returns a two-by-two \kbd{FlxM} $M$ with determinant
$\pm 1$ such that the image $(a,b)$ of $(x,y)$ by $M$ has the property that
$\deg a \geq {\deg x \over 2} > \deg b$.

\fun{GEN}{Flx_extgcd}{GEN a, GEN b, ulong p, GEN *ptu, GEN *ptv}

\fun{GEN}{Flx_pow}{GEN x, long n, ulong p}

\fun{GEN}{Flx_roots_naive}{GEN f, ulong p} returns the vector of roots
of $f$ as a \typ{VECSMALL} (multiple roots are not repeated), found
by an exhaustive search. Efficient for small $p$ and small degrees !

\subsubsec{Miscellaneous operations}

\fun{GEN}{pol0_Flx}{long sv} returns a zero \kbd{Flx} in variable $v$.

\fun{GEN}{zero_Flx}{long sv} alias for \kbd{pol0\_Flx}

\fun{GEN}{pol1_Flx}{long sv} returns the unit \kbd{Flx} in variable $v$.

\fun{GEN}{polx_Flx}{long sv} returns the variable $v$ as degree~1~\kbd{Flx}.

\fun{GEN}{Flx_normalize}{GEN z, ulong p}, as \kbd{FpX\_normalize}.

\fun{GEN}{random_Flx}{long d, long sv, ulong p} returns a random \kbd{Flx}
in variable \kbd{v}, of degree less than~\kbd{d}.

\fun{GEN}{Flx_recip}{GEN x}, returns the reciprocal polynomial

\fun{ulong}{Flx_resultant}{GEN a, GEN b, ulong p}, returns the resultant
of \kbd{a} and \kbd{b}

\fun{ulong}{Flx_extresultant}{GEN a, GEN b, ulong p, GEN *ptU, GEN *ptV}
given two \kbd{Flx} \kbd{a} and \kbd{b},
returns their resultant and sets Bezout coefficients (if the resultant is 0,
the latter are not set).

\fun{GEN}{Flx_invMontgomery}{GEN T, ulong p}, returns the Montgomery inverse
$M$ of $T$ defined by $M(x)\*x^n\*T(1/x)\equiv 1\pmod{x^{n-1}}$ where $n$ is
the degree of $T$.

\fun{GEN}{Flx_rem_Montgomery}{GEN x, GEN mg, GEN T, ulong p}, returns \kbd{x}
modulo \kbd{T}, assuming that $\deg x\leq 2\*(\deg{T} - 1)$ where \kbd{mg} is
the Montgomery inverse of \kbd{T}.

\fun{GEN}{Flx_renormalize}{GEN x, long l}, as \kbd{FpX\_renormalize}, where
$\kbd{l} = \kbd{lg(x)}$, in place.

\fun{GEN}{Flx_shift}{GEN T, long n} returns $\kbd{T} * x^n$ if $n\geq 0$,
and $\kbd{T} \bs x^{-n}$ otherwise.

\fun{long}{Flx_val}{GEN x} returns the valuation of \kbd{x}, i.e. the
multiplicity of the $0$ root.

\fun{long}{Flx_valrem}{GEN x, GEN *Z} as \kbd{RgX\_valrem}, returns the
valuation of \kbd{x}. In particular, if the valuation is $0$, set \kbd{*Z}
to $x$, not a copy.

\fun{GEN}{FlxYqQ_pow}{GEN x, GEN n, GEN S, GEN T, ulong p}, as
\kbd{FpXYQQ\_pow}.

\fun{GEN}{Flx_div_by_X_x}{GEN A, ulong a, ulong p, ulong *rem}, returns the
Euclidean quotient of the \kbd{Flx}~\kbd{A} by $X - \kbd{a}$, and sets
\kbd{rem} to the remainder $ \kbd{A}(\kbd{a})$.

\fun{ulong}{Flx_eval}{GEN x, ulong y, ulong p}, as \kbd{FpX\_eval}.

\fun{GEN}{Flx_deflate}{GEN P, long d} assuming $P$ is a polynomial of the
form $Q(X^d)$, return $Q$.

\fun{GEN}{Flx_inflate}{GEN P, long d} returns $P(X^d)$.

\fun{GEN}{FlxV_Flc_mul}{GEN V, GEN W, ulong p}, as \kbd{FpXV\_FpC\_mul}.

\fun{int}{Flx_is_squarefree}{GEN z, ulong p}

\fun{long}{Flx_nbfact}{GEN z, ulong p}, as \kbd{FpX\_nbfact}.

\fun{GEN}{Flx_nbfact_by_degree}{GEN z, long *nb, ulong p} Assume
that the \kbd{Flx} $z$ is squarefree mod the prime $p$. Returns a
\typ{VECSMALL} $D$ with $\deg z$ entries, such that $D[i]$ is the number of
irreducible factors of degree $i$. Set \kbd{nb} to the total number of
irreducible factors (the sum of the $D[i]$).

\fun{long}{FpX_nbfact}{GEN f, GEN p}, assuming the \kbd{FpX}~f is squarefree,
returns the number of its irreducible factors. Assumes that \kbd{p} is prime.

\fun{long}{Flx_nbroots}{GEN f, ulong p}, as \kbd{FpX\_nbroots}.

\fun{GEN}{Flv_polint}{GEN x, GEN y, ulong p, long sv} as \kbd{FpV\_polint},
returning an \kbd{Flx} in variable $v$.

\fun{GEN}{Flv_roots_to_pol}{GEN a, ulong p, long sv} as
\kbd{FpV\_roots\_to\_pol} returning an \kbd{Flx} in variable $v$.

\subsec{\kbd{Flxq}} See \kbd{FpXQ} operations.

\fun{GEN}{Flxq_add}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{Flxq_sub}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{Flxq_mul}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{Flxq_sqr}{GEN y, GEN T, ulong p}

\fun{GEN}{Flxq_inv}{GEN x, GEN T, ulong p}

\fun{GEN}{Flxq_invsafe}{GEN x, GEN T, ulong p}

\fun{GEN}{Flxq_div}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{Flxq_pow}{GEN x, GEN n, GEN T, ulong p}

\fun{GEN}{Flxq_powers}{GEN x, long n, GEN T, ulong p}

\fun{GEN}{Flxq_matrix_pow}{GEN x, long m, long n, GEN T, ulong p},
see \kbd{FpXQ\_matrix\_pow}.

\fun{GEN}{FlxqV_roots_to_pol}{GEN V, GEN T, ulong p, long v} as
\kbd{FqV\_roots\_to\_pol} returning an \kbd{FlxqX} in variable $v$.

\fun{GEN}{Flxq_order}{GEN a, GEN ord, GEN T, ulong p}
returns the order of the \typ{Flxq} \kbd{a}.
If \kbd{o} is non-\kbd{NULL}, it is assumed that \kbd{o} is a multiple of the
order of \kbd{a}, either as a \typ{INT} or a factorization matrix.

\fun{int}{Flxq_issquare}{GEN x, GEN T, ulong p} returns $1$ if $x$ is a square
and $0$ otherwise. Assumes that \kbd{T} is irreducible mod \kbd{p}.

\fun{GEN}{Flxq_log}{GEN a, GEN g, GEN ord, GEN T, ulong p} Let $g$ of exact
order \kbd{ord} in the field $F_p[X]/(T)$. Return $e$ such that $a^e=g$. If
$e$ does not exists, the result is currently undefined. Assumes that \kbd{T}
is irreducible mod \kbd{p}.

\fun{GEN}{Flxq_sqrtn}{GEN x, GEN n, GEN T, ulong p, GEN *zn} returns an
\kbd{n}-th root of $\kbd{x}$.  Return \kbd{NULL} if \kbd{x} is not an
\kbd{n}-th power residue. Otherwise, if \kbd{zn} is non-\kbd{NULL} set it to
a primitive \kbd{n}-th root of $1$. Assumes that \kbd{T} is irreducible mod
\kbd{p}.

\fun{GEN}{Flxq_charpoly}{GEN x, GEN T, ulong p} returns the characteristic
polynomial of \kbd{x}

\fun{GEN}{Flxq_minpoly}{GEN x, GEN T, ulong p} returns the minimal polynomial
of \kbd{x}

\fun{ulong}{Flxq_norm}{GEN x, GEN T, ulong p} returns the norm of \kbd{x}

\fun{ulong}{Flxq_trace}{GEN x, GEN T, ulong p} returns the trace of \kbd{x}

\fun{GEN}{Flxq_conjvec}{GEN x, GEN T, ulong p} returns the conjugates
$[x,x^p,x^{p^2},\ldots,x^{p^{n-1}}]$ where $n$ is the degree of $T$.

\fun{GEN}{gener_Flxq}{GEN T, ulong p, GEN *po} returns a primitive root modulo
$(T,p)$. $T$ is an \kbd{Flx} assumed to be irreducible modulo the prime
$p$. If \kbd{po} is not \kbd{NULL} it is set to $[o,\var{fa}]$, where $o$ is the
order of the multiplicative group of the finite field, and \var{fa} is
its factorization.

\subsec{\kbd{FlxX}} See \kbd{FpXX} operations.

\fun{GEN}{pol1_FlxX}{long vX, long sx} returns the unit \kbd{FlxX} as a
\typ{POL} in variable \kbd{vX} which only coefficient is \kbd{pol1\_Flx(sx)}.

\fun{GEN}{FlxX_add}{GEN P, GEN Q, ulong p}

\fun{GEN}{FlxY_Flx_div}{GEN x, GEN y, ulong p}

\fun{GEN}{FlxX_renormalize}{GEN x, long l}, as \kbd{normalizepol}, where
$\kbd{l} = \kbd{lg(x)}$, in place.

\fun{GEN}{FlxX_resultant}{GEN u, GEN v, ulong p, long sv} Returns
$\text{Res}_X(u, v)$, which is an \kbd{Flx}. The coefficients of \kbd{u}
and \kbd{v} are assumed to be in the variable $v$.

\fun{GEN}{Flx_FlxY_resultant}{GEN a, GEN b, ulong p}
Returns $\text{Res}_x(a, b)$, which is an \kbd{Flx}
in the main variable of \kbd{b}.

\fun{GEN}{FlxX_shift}{GEN a, long n}

\subsec{\kbd{FlxqX}} See \kbd{FpXQX} operations.

\fun{GEN}{FlxqX_mul}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{FlxqX_Flxq_mul}{GEN P, GEN U, GEN T, ulong p}

\fun{GEN}{FlxqX_Flxq_mul_to_monic}{GEN P, GEN U, GEN T, ulong p}
returns $P*U$ assuming the result is monic of the same degree as $P$ (in
particular $U\neq 0$).

\fun{GEN}{FlxqX_red}{GEN z, GEN T, ulong p}

\fun{GEN}{FlxqX_normalize}{GEN z, GEN T, ulong p}

\fun{GEN}{FlxqX_sqr}{GEN x, GEN T, ulong p}

\fun{GEN}{FlxqX_divrem}{GEN x, GEN y, GEN T, ulong p, GEN *pr}

\fun{GEN}{FlxqX_div}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{FlxqX_rem}{GEN x, GEN y, GEN T, ulong p}

\fun{GEN}{FlxqX_gcd}{GEN x, GEN y, ulong p} returns a (not necessarily monic)
greatest common divisor of $x$  and $y$.

\fun{GEN}{FlxqX_extgcd}{GEN x, GEN y, GEN T, ulong p, GEN *ptu, GEN *ptv}

\fun{GEN}{FlxqXV_prod}{GEN V, GEN T, ulong p}


\fun{GEN}{FlxqX_safegcd}{GEN P, GEN Q, GEN T, ulong p} Returns the \emph{monic}
GCD of $P$ and $Q$ if Euclid's algorithm succeeds and \kbd{NULL} otherwise. In
particular, if $p$ is not prime or $T$ is not irreducible over $\F_p[X]$, the
routine may still be used (but will fail if non-invertible leading terms
occur).

\subsec{\kbd{FlxqXQ}} See \kbd{FpXQXQ} operations.

\fun{GEN}{FlxqXQ_mul}{GEN x, GEN y, GEN S, GEN T, ulong p}

\fun{GEN}{FlxqXQ_sqr}{GEN x, GEN S, GEN T, ulong p}

\fun{GEN}{FlxqXQ_inv}{GEN x, GEN S, GEN T, ulong p}

\fun{GEN}{FlxqXQ_invsafe}{GEN x, GEN S, GEN T, ulong p}

\fun{GEN}{FlxqXQ_pow}{GEN x, GEN n, GEN S, GEN T, ulong p}

\subsec{\kbd{F2x}} An \kbd{F2x}~\kbd{z} is a \typ{VECSMALL}
representing a polynomial over $\F_2[X]$. Specifically
\kbd{z[0]} is the usual codeword, \kbd{z[1] = evalvarn($v$)} for some
variable $v$ and the coefficients are given by the bits of remaining
words by increasing degree.

\subsubsec{Basic operations}

\fun{ulong}{F2x_coeff}{GEN x, long i} returns the coefficient $i\ge 0$ of $x$.

\fun{void}{F2x_clear}{GEN x, long i} sets the coefficient $i\ge 0$ of $x$ to $0$.

\fun{void}{F2x_flip}{GEN x, long i} adds $1$ to the coefficient $i\ge 0$ of $x$.

\fun{void}{F2x_set}{GEN x, long i} sets the coefficient $i\ge 0$ of $x$ to $1$.

\fun{GEN}{Flx_to_F2x}{GEN x}

\fun{GEN}{Z_to_F2x}{GEN x, long sv}

\fun{GEN}{ZX_to_F2x}{GEN x}

\fun{GEN}{ZXX_to_F2xX}{GEN x, long v}

\fun{GEN}{F2x_to_Flx}{GEN x}

\fun{GEN}{F2x_to_ZX}{GEN x}

\fun{GEN}{pol0_F2x}{long sv} returns a zero \kbd{F2x} in variable $v$.

\fun{GEN}{zero_F2x}{long sv} alias for \kbd{pol0\_F2x}.

\fun{GEN}{pol1_F2x}{long sv} returns the \kbd{F2x} in variable $v$ constant to
$1$.

\fun{GEN}{polx_F2x}{long sv} returns the variable $v$ as degree~1~\kbd{F2x}.

\fun{GEN}{random_F2x}{long d, long sv} returns a random \kbd{F2x}
in variable \kbd{v}, of degree less than~\kbd{d}.

\fun{long}{F2x_degree}{GEN x} returns the degree of the \kbd{F2x x}. The degree of $0$ is defined as $-1$.

\fun{int}{F2x_equal1}{GEN x}

\fun{GEN}{F2x_1_add}{GEN y} returns \kbd{y+1} where \kbd{y} is a \kbd{Flx}.

\fun{GEN}{F2x_add}{GEN x, GEN y}

\fun{GEN}{F2x_mul}{GEN x, GEN y}

\fun{GEN}{F2x_sqr}{GEN x}

\fun{GEN}{F2x_divrem}{GEN x, GEN y, GEN *pr}

\fun{GEN}{F2x_rem}{GEN x, GEN y}

\fun{GEN}{F2x_div}{GEN x, GEN y}

\fun{GEN}{F2x_renormalize}{GEN x, long lx}

\fun{GEN}{F2x_deriv}{GEN x}

\fun{GEN}{F2x_extgcd}{GEN a, GEN b, GEN *ptu, GEN *ptv}

\fun{GEN}{F2x_gcd}{GEN a, GEN b}

\subsec{\kbd{F2xq}} See \kbd{FpXQ} operations.

\fun{GEN}{F2xq_mul}{GEN x, GEN y, GEN pol}

\fun{GEN}{F2xq_sqr}{GEN x,GEN pol}

\fun{GEN}{F2xq_div}{GEN x,GEN y,GEN T}

\fun{GEN}{F2xq_inv}{GEN x, GEN T}

\fun{GEN}{F2xq_invsafe}{GEN x, GEN T}

\fun{GEN}{F2xq_pow}{GEN x, GEN n, GEN pol}

\fun{ulong}{F2xq_trace}{GEN x, GEN T}

\fun{GEN}{F2xq_conjvec}{GEN x, GEN T} returns the vector of conjugates
$[x,x^2,x^{2^2},\ldots,x^{2^{n-1}}]$ where $n$ is the degree of $T$.

\fun{GEN}{F2xq_log}{GEN a, GEN g, GEN ord, GEN T}

\fun{GEN}{F2xq_order}{GEN a, GEN ord, GEN T}

\fun{GEN}{F2xq_sqrt}{GEN a, GEN T}

\fun{GEN}{F2xq_sqrtn}{GEN a, GEN n, GEN T, GEN *zeta}

\fun{GEN}{gener_F2xq}{GEN T, GEN *po}

\fun{GEN}{F2xq_powers}{GEN x, long n, GEN T}

\fun{GEN}{F2xq_matrix_pow}{GEN x, long m, long n, GEN T}

\subsec{Functions returning objects with \typ{INTMOD} coefficients}

Those functions are mostly needed for interface reasons: \typ{INTMOD}s should
not be used in library mode since the modular kernel is more flexible and more
efficient, but GP users do not have access to the modular kernel.
We document them for completeness:

\fun{GEN}{Fp_to_mod}{GEN z, GEN p}, \kbd{z} a \typ{INT}. Returns \kbd{z *
Mod(1,p)}, normalized. Hence the returned value is a \typ{INTMOD}.

\fun{GEN}{FpX_to_mod}{GEN z, GEN p}, \kbd{z} a \kbd{ZX}. Returns \kbd{z *
Mod(1,p)}, normalized. Hence the returned value has \typ{INTMOD} coefficients.

\fun{GEN}{FpC_to_mod}{GEN z, GEN p}, \kbd{z} a \kbd{ZC}. Returns \kbd{Col(z) *
Mod(1,p)}, a \typ{COL} with \typ{INTMOD} coefficients.

\fun{GEN}{FpV_to_mod}{GEN z, GEN p}, \kbd{z} a \kbd{ZV}. Returns \kbd{Vec(z) *
Mod(1,p)}, a \typ{VEC} with \typ{INTMOD} coefficients.

\fun{GEN}{FpM_to_mod}{GEN z, GEN p}, \kbd{z} a \kbd{ZM}. Returns \kbd{z *
Mod(1,p)}, with \typ{INTMOD} coefficients.

\fun{GEN}{FpXQC_to_mod}{GEN V, GEN T, GEN p} $V$ being a vector of \kbd{FpXQ},
converts each entry to a \typ{POLMOD} with \typ{INTMOD} coefficients, and return
a \typ{COL}.

\fun{GEN}{QXQV_to_mod}{GEN V, GEN T} $V$ a vector of \kbd{QXQ}, which
are lifted representatives of elements of $\Q[X]/(T)$ (number field elements
in most applications) and $T$ is in $\Z[X]$. Return a vector where all
non-rational entries are converted to \typ{POLMOD} modulo $T$; no reduction
mod $T$ is attempted: the representatives should be already reduced. Used to
normalize the output of \kbd{nfroots}.

\fun{GEN}{QXQXV_to_mod}{GEN V, GEN T} $V$ a vector of polynomials whose
coefficients are \kbd{QXQ}. Analogous to \kbd{QXQV\_to\_mod}.
Used to normalize the output of \kbd{nffactor}.

The following functions are obsolete and should not be used: they receive a
polynomial with arbitrary coefficients, apply \kbd{RgX\_to\_FpX}, a function
from the modular kernel, then \kbd{*\_to\_mod}:

\fun{GEN}{rootmod}{GEN f, GEN p}, applies \kbd{FpX\_roots}.

\fun{GEN}{rootmod2}{GEN f, GEN p}, applies \kbd{ZX\_to\_flx} then
\kbd{Flx\_roots\_naive}.

\fun{GEN}{factmod}{GEN f, GEN p} applies \kbd{FpX\_factor}.

\fun{GEN}{simplefactmod}{GEN f, GEN p} applies \kbd{FpX\_degfact}.

\subsec{Chinese remainder theorem over $\Z$}

\fun{GEN}{Z_chinese}{GEN a, GEN b, GEN A, GEN B} returns the integer
in $[0, \lcm(A,B)[$ congruent to $a$ mod $A$ and $b$ mod $B$, assuming it
exists; in other words, that $a$ and $b$ are congruent mod $\gcd(A,B)$.

\fun{GEN}{Z_chinese_all}{GEN a, GEN b, GEN A, GEN B, GEN *pC} as
\kbd{Z\_chinese}, setting \kbd{*pC} to the lcm of $A$ and $B$.

\fun{GEN}{Z_chinese_coprime}{GEN a, GEN b, GEN A, GEN B, GEN C}, as
\kbd{Z\_chinese}, assuming that $\gcd(A,B) = 1$ and that $C = \lcm(A,B) = AB$.

\fun{void}{Z_chinese_pre}{GEN A, GEN B, GEN *pC, GEN *pU, GEN *pd}
initializes chinese remainder computations modulo $A$ and $B$. Sets
\kbd{*pC} to $\lcm(A,B)$, \kbd{*pd} to $\gcd(A,B)$,
\kbd{*pU} to an integer congruent to $0$ mod $(A/d)$ and $1$ mod $(B/d)$.
It is allowed to set \kbd{pd = NULL}, in which case, $d$ is still
computed, but not saved.

\fun{GEN}{Z_chinese_post}{GEN a, GEN b, GEN C, GEN U, GEN d} returns
the solution to the chinese remainder problem $x$ congruent
to $a$ mod $A$ and $b$ mod $B$, where $C, U, d$ were set in
\kbd{Z\_chinese\_pre}. If $d$ is \kbd{NULL}, assume the problem has a
solution. Otherwise, return \kbd{NULL} if it has no solution.

\medskip

The following pair of functions is used in homomorphic imaging schemes,
when reconstructing an integer from its images modulo pairwise coprime
integers. The idea is as follows: we want to discover an integer $H$ which
satisfies $|H| < B$ for some known bound $B$; we are given pairs $(H_p, p)$
with $H$ congruent to $H_p$ mod $p$ and all $p$ pairwise coprime.

Given \kbd{H} congruent to $H_p$ modulo a number of $p$, whose product is
$q$, and a new pair $(\kbd{Hp}, \kbd{p})$, \kbd{p} coprime to $q$, the
following incremental functions use the chinese remainder theorem (CRT) to
find a new \kbd{H}, congruent to the preceding one modulo $q$, but also to
\kbd{Hp} modulo \kbd{p}. It is defined uniquely modulo $qp$, and we choose
the centered representative. When $P$ is larger than $2B$, we have $\kbd{H} =
H$, but of course, the value of \kbd{H} may stabilize sooner. In many
applications it is possible to directly check that such a partial result is
correct.

\fun{GEN}{Z_init_CRT}{ulong Hp, ulong p} given a \kbd{Fl} \kbd{Hp} in
$[0, p-1]$, returns the centered representative \kbd{H} congruent to \kbd{Hp}
modulo \kbd{p}.

\fun{int}{Z_incremental_CRT}{GEN *H, ulong Hp, GEN q, GEN qp, ulong p}
given a \typ{INT} \kbd{*H}, centered modulo \kbd{q}, a new pair $(\kbd{Hp},
\kbd{p})$ with \kbd{p} coprime to \kbd{q}, and the product $\kbd{qp} = \kbd{p}
\cdot \kbd{q}$, this function updates \kbd{*H} so that it also becomes
congruent to $(\kbd{Hp}, \kbd{p})$. It returns $1$ if the new value is equal
to the old one, and $0$ otherwise.

\fun{GEN}{chinese1_coprime_Z}{GEN v} an alternative divide-and-conquer
implementation: $v$ is a vector of \typ{INTMOD} with pairwise coprime moduli.
Return the \typ{INTMOD} solving the corresponding chinese remainder problem.
This is a streamlined version of

\fun{GEN}{chinese1}{GEN v}, which solves a general chinese remainder problem
(not necessarily over $\Z$, moduli not assumed coprime).


As above, for $H$ a \kbd{ZM}: we assume that $H$ and all \kbd{Hp} have
dimension $> 0$. The original \kbd{*H} is destroyed.

\fun{GEN}{ZM_init_CRT}{GEN Hp, ulong p}

\fun{int}{ZM_incremental_CRT}{GEN *H, GEN Hp, GEN q, GEN qp, ulong p}

As above for $H$ a \kbd{ZX}: note that the degree may increase or decrease.
The original \kbd{*H} is destroyed.

\fun{GEN}{ZX_init_CRT}{GEN Hp, ulong p, long v}

\fun{int}{ZX_incremental_CRT}{GEN *H, GEN Hp, GEN q, GEN qp, ulong p}

\subsec{Rational reconstruction}

\fun{int}{Fp_ratlift}{GEN x, GEN m, GEN amax, GEN bmax, GEN *a, GEN *b}.
Assuming that $0 \leq x < m$, $\kbd{amax} \geq 0$, and
$\kbd{bmax} > 0$ are \typ{INT}s, and that $2 \kbd{amax} \kbd{bmax} < m$,
attempts to recognize $x$ as a rational $a/b$, i.e. to find \typ{INT}s $a$
and $b$ such that

\item $a \equiv b x$ modulo $m$,

\item $|a| \leq \kbd{amax}$, $0 < b \leq \kbd{bmax}$,

\item $\gcd(m,b) = \gcd(a,b)$.

\noindent If unsuccessful, the routine returns $0$ and leaves $a$, $b$
unchanged; otherwise it returns $1$ and sets $a$ and $b$.

In almost all applications, we actually know that a solution exists, as well
as a non-zero multiple $B$ of $b$, and $m = p^\ell$ is a prime power, for a
prime $p$ chosen coprime to $B$ hence to $b$. Under the single assumption
$\gcd(m,b) = 1$, if a solution $a,b$ exists satisfying the three conditions
above, then it is unique.

\fun{int}{ratlift}{GEN x, GEN m, GEN amax, GEN bmax, GEN *a, GEN *b}.
Calls \tet{Fp_ratlift} after explicitly checking all preconditions.

\fun{GEN}{FpM_ratlift}{GEN M, GEN m, GEN amax, GEN bmax, GEN denom}
given an \kbd{FpM} modulo $m$ with reduced or \kbd{Fp\_center}-ed entries,
reconstructs a matrix with rational coefficients by applying \kbd{Fp\_ratlift}
to all entries. Assume that all preconditions for \kbd{Fp\_ratlift} are
satisfied, as well $\gcd(m,b) = 1$ (so that the solution is unique if it
exists). Return \kbd{NULL} if the reconstruction fails, and the rational
matrix otherwise. If \kbd{denom} is not \kbd{NULL} check further that all
denominators divide \kbd{denom}.

The functions is not stack clean if one coefficients of $M$ is negative
(centered residues), but still suitable for \kbd{gerepileupto}.

\fun{GEN}{FpX_ratlift}{GEN P, GEN m, GEN amax, GEN bmax, GEN denom} as
\kbd{FpM\_ratlift}, where $P$ is an \kbd{FpX}.

\subsec{Hensel lifts}

\fun{GEN}{Zp_sqrtlift}{GEN a, GEN S, GEN p, long e} let
$a,b,p$ be \typ{INT}s, with $p > 1$ odd, such that $a^2\equiv b\mod p$.
Returns a \typ{INT} $A$ such that $A^2 \equiv b \mod p^e$. Special case
of \tet{Zp_sqrtnlift}.

\fun{GEN}{Zp_sqrtnlift}{GEN b, GEN n, GEN a, GEN p, long e} let
$a,b,n,p$ be \typ{INT}s, with $n,p > 1$, and $p$ coprime to $n$,
such that $a^n \equiv b \mod p$. Returns a \typ{INT} $A$ such that
$A^n \equiv b \mod p^e$. Special case of \tet{ZpX_liftroot}.

\fun{GEN}{ZpXQ_sqrtnlift}{GEN b, GEN n, GEN a, GEN T, GEN p, long e} let
$n,p$ be \typ{INT}s, with $n,p > 1$ and $p$ coprime to $n$, and $a,b$
be \kbd{Fq}s (modulo $T$) such that $a^n \equiv b \mod (p,T)$.
Returns an \kbd{Fq} $A$ such that $A^n \equiv b \mod (p^e, T)$.
Special case of \tet{ZpXQ_liftroot}.

\fun{GEN}{rootpadicfast}{GEN f, GEN p, long e} $f$ a \kbd{ZX} with leading
term prime to $p$, and without multiple roots mod $p$. Return a vector
of \typ{INT}s which are the roots of $f$ mod $p^e$. This is a very important
special case of \kbd{rootpadic}.

\fun{GEN}{ZpX_liftroot}{GEN f, GEN a, GEN p, long e} $f$ a \kbd{ZX} with
leading term prime to $p$, and $a$ a simple root mod $p$. Return a \typ{INT}
which are the root of $f$ mod $p^e$ congruent to $a$ mod $p$.

\fun{GEN}{ZpX_liftroots}{GEN f, GEN S, GEN q, long e} $f$ a \kbd{ZX} with
leading term prime to $p$, and $S$ a vector of simple roots mod $p$. Return a
vector of \typ{INT}s which are the root of $f$ mod $p^e$ congruent to the
$S[i]$ mod $p$.

\fun{GEN}{ZpXQX_liftroot}{GEN f, GEN a, GEN T, GEN p, long e} as
\tet{ZpX_liftroot}, but $f$ is now a polynomial in $\Z[X,Y]$ and we find
roots in the unramified extension of $\Q_p$ with residue field $\F_p[Y]/(T)$.

\fun{GEN}{ZpX_liftfact}{GEN A, GEN B, GEN T, GEN p, long e, GEN pe} is
the routine underlying \tet{polhensellift}. Here, $p$ is prime, $T(Y)$
defines a finite field $\F_q$, either $\F_q = \F_p$ ($T$ is \kbd{NULL})
or a non-prime finite field ($T$ an \kbd{FpX}). $A$ is a polynomial in
$\Z[X]$ ($T$ \kbd{NULL}) or $\Z[X,Y]$, whose leading coefficient
is non-zero in $\F_q$. $B$ is a vector of monic \kbd{FpX} ($T$ \kbd{NULL}) or
\kbd{FqX}, pairwise coprime in $\F_q[X]$, whose product is congruent to
$A/\text{lc}(A)$ in $\F_q[X]$. Lifts the elements of $B$ mod $\kbd{pe} =
p^e$, such that the congruence now holds mod $(T,p^e)$.

The following technical function returns an optimal sequence of $p$-adic
accuracies, for a given target accuracy:

\fun{ulong}{quadratic_prec_mask}{long n} we want to reach accuracy
$n\geq 1$, starting from accuracy 1, using a quadratically convergent,
self-correcting, algorithm; in other words, from inputs correct to accuracy
$l$ one iteration outputs a result correct to accuracy $2l$.
For instance, to reach $n = 9$, we want to use accuracies
$[1,2,3,5,9]$ instead of $[1,2,4,8,9]$. The idea is to essentially double
the accuracy at each step, and not overshoot in the end.

Let $a_0$ = 1, $a_1 = 2, \ldots, a_k = n$, be the desired sequence of
accuracies. To obtain it, we work backwards and set
$$ a_k = n,\quad a_{i-1} = (a_i + 1)\,\bs\, 2.$$
This is in essence what the function returns.
But we do not want to store the $a_i$ explicitly, even as a \typ{VECSMALL},
since this would leave an object on the stack. Instead, we store $a_i$
implicitly in a bitmask \kbd{MASK}: let $a_0 = 1$, if the $i$-th bit of the
mask is set, set $a_{i+1} = 2a_i - 1$, and $2a_i$ otherwise; in short the
bits indicate the places where we do something special and do not quite
double the accuracy (which would be the straightforward thing to do).

In fact, to avoid returning separately the mask and the sequence length
$k+1$, the function returns $\kbd{MASK} + 2^{k+1}$, so the highest bit of
the mask indicates the length of the sequence, and the following ones give
an algorithm to obtain the accuracies. This is much simpler than it sounds,
here is what it looks like in practice:
\bprog
  ulong mask = quadratic_prec_mask(n);
  long l = 1;
  while (mask > 1) {            /* here, the result is known to accuracy l */
    l = 2*l; if (mask & 1) l--; /* new accuracy l for the iteration */
    mask >>= 1;                 /* pop low order bit */
    /* ... lift to the new accuracy ... */
  }
  /* we are done. At this point l = n */
@eprog\noindent We just pop the bits in \kbd{mask} starting from the low
order bits, stop when \kbd{mask} is $1$ (that last bit corresponds to the
$2^{k+1}$ that we added to the mask proper). Note that there is nothing
specific to Hensel lifts in that function: it would work equally well for
an Archimedean Newton iteration.

Note that in practice, we rather use an infinite loop, and insert an
\bprog
  if (mask == 1) break;
@eprog\noindent in the middle of the loop: the loop body usually includes
preparations for the next iterations (e.g. lifting Bezout coefficients
in a quadratic Hensel lift), which are costly and useless in the \emph{last}
iteration.

\subsec{Other $p$-adic functions}

\fun{long}{ZpX_disc_val}{GEN f, GEN p} returns the valuation at $p$ of the
discriminant of $f$. Assume that $f$ is a monic \emph{separable} \kbd{ZX}
and that $p$ is a prime number. Proceeds by dynamically increasing the
$p$-adic accuracy; infinite loop if the discriminant of $f$ is
$0$.

\fun{GEN}{ZpX_gcd}{GEN f,GEN g, GEN pm} $f$ a monic \kbd{ZX}, $g$ a \kbd{ZX},
$\kbd{pm} = p^m$ a prime power. There is a unique integer $r\geq 0$
and a monic $h\in \Q_p[X]$ such that
$$p^rh\Z_p[X] + p^m\Z_p[X] = f\Z_p[X] + g\Z_p[X] + p^m\Z_p[X].$$
Return the $0$ polynomial if $r\geq m$ and a monic $h\in\Z[1/p][X]$ otherwise
(whose valuation at $p$ is $> -m$).

\fun{GEN}{ZpX_reduced_resultant}{GEN f, GEN g, GEN pm} $f$ a monic
\kbd{ZX}, $g$ a \kbd{ZX}, $\kbd{pm} = p^m$ a prime power. The $p$-adic
\emph{reduced resultant}\varsidx{resultant (reduced)} of $f$ and $g$ is
$0$ if $f$, $g$ not coprime in $\Z_p[X]$, and otherwise the generator of the
form $p^d$ of
$$ (f\Z_p[X] + g\Z_p[X])\cap \Z_p. $$
Return the reduced resultant modulo $p^m$.

\fun{GEN}{ZpX_reduced_resultant_fast}{GEN f, GEN g, GEN p, long M} $f$
a monic \kbd{ZX}, $g$ a \kbd{ZX}, $p$ a prime. Returns the
the $p$-adic reduced resultant of $f$ and $g$ modulo $p^M$. This function
computes resultants for a sequence of increasing $p$-adic accuracies
(up to $M$ $p$-adic digits), returning as soon as it obtains a non-zero
result. It is very inefficient when the resultant is $0$, but otherwise
usually more efficient than computations using a priori bounds.

\subsec{Conversions involving single precision objects}

\subsubsec{To single precision}

\fun{GEN}{RgX_to_Flx}{GEN x, ulong p}, \kbd{x} a \typ{POL}, returns the
\kbd{Flx} obtained by applying \kbd{Rg\_to\_Fl} coefficientwise.

\fun{GEN}{ZX_to_Flx}{GEN x, ulong p} reduce \kbd{ZX}~\kbd{x} modulo \kbd{p}
(yielding an \kbd{Flx}). Faster than \kbd{RgX\_to\_Flx}.

\fun{GEN}{ZV_to_Flv}{GEN x, ulong p} reduce \kbd{ZV}~\kbd{x} modulo \kbd{p}
(yielding an \kbd{Flv}).

\fun{GEN}{ZXV_to_FlxV}{GEN v, ulong p}, as \kbd{ZX\_to\_Flx}, repeatedly
called on the vector's coefficients.

\fun{GEN}{ZXX_to_FlxX}{GEN B, ulong p, long v}, as \kbd{ZX\_to\_Flx},
repeatedly called on the polynomial's coefficients.

\fun{GEN}{ZXXV_to_FlxXV}{GEN V, ulong p, long v}, as \kbd{ZXX\_to\_FlxX},
repeatedly called on the vector's coefficients.

\fun{GEN}{ZM_to_Flm}{GEN x, ulong p} reduce \kbd{ZM}~\kbd{x} modulo \kbd{p}
(yielding an \kbd{Flm}).

\fun{GEN}{ZV_to_zv}{GEN z}, converts coefficients using \kbd{itos}

\fun{GEN}{ZV_to_nv}{GEN z}, converts coefficients using \kbd{itou}

\fun{GEN}{ZM_to_zm}{GEN z}, converts coefficients using \kbd{itos}

\fun{GEN}{FqC_to_FlxC}{GEN x, GEN T, GEN p}, converts coefficients in \kbd{Fq}
to coefficient in Flx, result being a column vector.

\fun{GEN}{FqV_to_FlxV}{GEN x, GEN T, GEN p}, converts coefficients in \kbd{Fq}
to coefficient in Flx, result being a line vector.

\fun{GEN}{FqM_to_FlxM}{GEN x, GEN T, GEN p}, converts coefficients in \kbd{Fq}
to coefficient in Flx.

\subsubsec{From single precision}

\fun{GEN}{Flx_to_ZX}{GEN z}, converts to \kbd{ZX} (\typ{POL} of non-negative
\typ{INT}s in this case)

\fun{GEN}{Flx_to_ZX_inplace}{GEN z}, same as \kbd{Flx\_to\_ZX}, in place
(\kbd{z} is destroyed).

\fun{GEN}{FlxX_to_ZXX}{GEN B}, converts an \kbd{FlxX} to a polynomial with
\kbd{ZX} or \typ{INT} coefficients (repeated calls to \kbd{Flx\_to\_ZX}).

\fun{GEN}{FlxC_to_ZXC}{GEN x}, converts a vector of \kbd{Flx} to a column
vector of polynomials with \typ{INT} coefficients (repeated calls to
\kbd{Flx\_to\_ZX}).

\fun{GEN}{FlxM_to_ZXM}{GEN z}, converts a matrix of \kbd{Flx} to a matrix of
polynomials with \typ{INT} coefficients (repeated calls to \kbd{Flx\_to\_ZX}).

\fun{GEN}{zx_to_ZX}{GEN z}, as \kbd{Flx\_to\_ZX}, without assuming
coefficients are non-negative.

\fun{GEN}{Flc_to_ZC}{GEN z}, converts to \kbd{ZC} (\typ{COL} of non-negative
\typ{INT}s in this case)

\fun{GEN}{Flv_to_ZV}{GEN z}, converts to \kbd{ZV} (\typ{VEC} of non-negative
\typ{INT}s in this case)

\fun{GEN}{Flm_to_ZM}{GEN z}, converts to \kbd{ZM} (\typ{MAT} with
non-negative \typ{INT}s coefficients in this case)

\fun{GEN}{zc_to_ZC}{GEN z} as \kbd{Flc\_to\_ZC}, without assuming
coefficients are non-negative.

\fun{GEN}{zv_to_ZV}{GEN z} as \kbd{Flv\_to\_ZV}, without assuming
coefficients are non-negative.

\fun{GEN}{zm_to_ZM}{GEN z} as \kbd{Flm\_to\_ZM}, without assuming
coefficients are non-negative.

\subsubsec{Mixed precision linear algebra} Assumes dimensions are compatible.
Multiply a multiprecision object by a single-precision one.

\fun{GEN}{RgM_zc_mul}{GEN x, GEN y}

\fun{GEN}{RgM_zm_mul}{GEN x, GEN y}

\fun{GEN}{RgV_zc_mul}{GEN x, GEN y}

\fun{GEN}{RgV_zm_mul}{GEN x, GEN y}

\fun{GEN}{ZM_zc_mul}{GEN x, GEN y}

\fun{GEN}{ZM_zm_mul}{GEN x, GEN y}

\fun{GEN}{ZC_z_mul}{GEN x, long y}

\subsubsec{Miscellaneous involving Fl}

\fun{GEN}{Fl_to_Flx}{ulong x, long evx} converts a \kbd{unsigned long} to a
scalar \kbd{Flx}. Assume that \kbd{evx = evalvarn(vx)} for some variable
number \kbd{vx}.

\fun{GEN}{Z_to_Flx}{GEN x, ulong p, long v} converts a \typ{INT} to a scalar
polynomial in variable $v$.

\fun{GEN}{Flx_to_Flv}{GEN x, long n} converts from \kbd{Flx} to \kbd{Flv}
with \kbd{n} components (assumed larger than the number of coefficients of
\kbd{x}).

\fun{GEN}{zx_to_zv}{GEN x, long n} as \kbd{Flx\_to\_Flv}.

\fun{GEN}{Flv_to_Flx}{GEN x, long sv} converts from vector (coefficient
array) to (normalized) polynomial in variable $v$.

\fun{GEN}{zv_to_zx}{GEN x, long n} as \kbd{Flv\_to\_Flx}.

\fun{GEN}{matid_Flm}{long n} returns an \kbd{Flm} which is an $n \times n$
identity matrix.

\fun{GEN}{Flm_to_FlxV}{GEN x, long sv} converts the columns of
\kbd{Flm}~\kbd{x} to an array of \kbd{Flx} in the variable $v$
(repeated calls to \kbd{Flv\_to\_Flx}).

\fun{GEN}{zm_to_zxV}{GEN x, long n} as \kbd{Flm\_to\_FlxV}.

\fun{GEN}{Flm_to_FlxX}{GEN x, long sw, long sv} same as
\kbd{Flm\_to\_FlxV(x,sv)} but returns the result as a (normalized) polynomial
in variable $w$.

\fun{GEN}{FlxV_to_Flm}{GEN v, long n} reverse \kbd{Flm\_to\_FlxV}, to obtain
an \kbd{Flm} with \kbd{n} rows (repeated calls to \kbd{Flx\_to\_Flv}).

\fun{GEN}{FlxX_to_Flm}{GEN v, long n} reverse \kbd{Flm\_to\_FlxX}, to obtain
an \kbd{Flm} with \kbd{n} rows (repeated calls to \kbd{Flx\_to\_Flv}).

\fun{GEN}{Fly_to_FlxY}{GEN a, long sv} convert coefficients of \kbd{a} to
constant \kbd{Flx} in variable $v$.

\subsubsec{Miscellaneous involving F2}

\fun{GEN}{F2x_to_F2v}{GEN x, long n} converts from \kbd{F2x} to \kbd{F2v}
with \kbd{n} components (assumed larger than the number of coefficients of
\kbd{x}).

\fun{GEN}{F2xC_to_ZXC}{GEN x}, converts a vector of \kbd{F2x} to a column
vector of polynomials with \typ{INT} coefficients (repeated calls to
\kbd{F2x\_to\_ZX}).

\fun{GEN}{F2xV_to_F2m}{GEN v, long n} \kbd{F2x\_to\_F2v} to each polynomials
to get an \kbd{F2m} with \kbd{n} rows.

\section{Arithmetic on elliptic curve over a finite field in simple form}
\subsec{\kbd{FpE}}

Let $p$ a prime number and $E$ the elliptic curve given by the equation
$E:y^2=x^3+a_4\*x+a_6$. A \kbd{FpE} is a point of $E(\F_p)$.

\fun{GEN}{FpE_add}{GEN P, GEN Q, GEN a4, GEN p} returns the sum $P+Q$
in the group $E(\F_p)$, where $E$ is defined by $E:y^2=x^3+a_4\*x+a_6$,
for any value of $a_6$ compatible with the points given.

\fun{GEN}{FpE_sub}{GEN P, GEN Q, GEN a4, GEN p} returns $P-Q$.

\fun{GEN}{FpE_dbl}{GEN P, GEN a4, GEN p} returns $2.P$.

\fun{GEN}{FpE_neg}{GEN P, GEN p} returns $-P$.

\fun{GEN}{FpE_mul}{GEN P, GEN n, GEN a4, GEN p} return $n.P$.

\fun{GEN}{random_FpE}{GEN a4, GEN a6, GEN p} returns a random point on
$E(\F_p)$, where $E$ is defined by $E:y^2=x^3+a_4\*x+a_6$.

\fun{GEN}{FpE_order}{GEN P, GEN o, GEN a4, GEN p} returns the order of $P$ in
the group $E(\F_p)$, where $o$ is a multiple of the order of $P$, or its
factorization.

\fun{GEN}{FpE_tatepairing}{GEN P, GEN Q, GEN m, GEN a4, GEN p} returns the
reduced Tate pairing of the point of $m$-torsion $P$ and the point $Q$.

\fun{GEN}{FpE_weilpairing}{GEN Q, GEN Q, GEN m, GEN a4, GEN p} returns the
Weil pairing of the points of $m$-torsion $P$ and $Q$.

\section{Integral, rational and generic linear algebra}
\subsec{\kbd{ZC} / \kbd{ZV}, \kbd{ZM}} A \kbd{ZV} (resp.~a~\kbd{ZM},
resp.~a~\kbd{ZX}) is a \typ{VEC} or \typ{COL} (resp.~\typ{MAT},
resp.~\typ{POL}) with \typ{INT} coefficients.

\subsubsec{\kbd{ZC} / \kbd{ZV}}

\fun{void}{RgV_check_ZV}{GEN A, const char *s} Assuming \kbd{x} is a \typ{VEC}
or \typ{COL} raise an error if it is not a \kbd{ZV} ($s$ should point to the
name of the caller).

\fun{int}{ZV_equal0}{GEN x} returns 1 if all entries of the \kbd{ZV} $x$ are
zero, and $0$ otherwise.

\fun{int}{ZV_cmp}{GEN x, GEN y} compare two \kbd{ZV}, which we assume have
the same length (lexicographic order, comparing absolute values).

\fun{int}{ZV_abscmp}{GEN x, GEN y} compare two \kbd{ZV}, which we assume have
the same length (lexicographic order).

\fun{int}{ZV_equal}{GEN x, GEN y} returns $1$ if the two \kbd{ZV} are equal
and $0$ otherwise. A \typ{COL} and a \typ{VEC} with the same entries are
declared equal.

\fun{GEN}{ZC_add}{GEN x, GEN y} adds \kbd{x} and \kbd{y}.

\fun{GEN}{ZC_sub}{GEN x, GEN y} subtracts \kbd{x} and \kbd{y}.

\fun{GEN}{ZC_Z_add}{GEN x, GEN y} adds \kbd{y} to \kbd{x[1]}.

\fun{GEN}{ZC_Z_sub}{GEN x, GEN y} subtracts \kbd{y} to \kbd{x[1]}.

\fun{GEN}{ZC_copy}{GEN x} returns a (\typ{COL}) copy of \kbd{x}.

\fun{GEN}{ZC_neg}{GEN x} returns $-\kbd{x}$ as a \typ{COL}.

\fun{void}{ZV_neg_inplace}{GEN x} negates the \kbd{ZV} \kbd{x} in place, by
replacing each component by its opposite (the type of \kbd{x} remains the
same, \typ{COL} or \typ{COL}). If you want to save even more memory by
avoiding the implicit component copies, use \kbd{ZV\_togglesign}.

\fun{void}{ZV_togglesign}{GEN x} negates \kbd{x} in place, by toggling the
sign of its integer components. Universal constants \kbd{gen\_1},
\kbd{gen\_m1}, \kbd{gen\_2} and \kbd{gen\_m2} are handled specially and will
not be corrupted. (We use \tet{togglesign_safe}.)

\fun{GEN}{ZC_Z_mul}{GEN x, GEN y} multiplies the \kbd{ZC} or \kbd{ZV}~\kbd{x}
(which can be a column or row vector) by the \typ{INT}~\kbd{y}, returning a
\kbd{ZC}.

\fun{GEN}{ZC_Z_divexact}{GEN x, GEN y} returns $x/y$ assuming all divisions
are exact.

\fun{GEN}{ZV_dotproduct}{GEN x,GEN y} as \kbd{RgV\_dotproduct} assuming $x$
and $y$ have \typ{INT} entries.

\fun{GEN}{ZV_dotsquare}{GEN x} as \kbd{RgV\_dotsquare} assuming $x$
has \typ{INT} entries.

\fun{GEN}{ZC_lincomb}{GEN u, GEN v, GEN x, GEN y} returns $ux + vy$, where
$u$, $v$ are \typ{INT} and $x,y$ are \kbd{ZC} or \kbd{ZV}. Return a \kbd{ZC}

\fun{void}{ZC_lincomb1_inplace}{GEN X, GEN Y, GEN v} sets $X\leftarrow X +
vY$, where $v$ is a \typ{INT} and $X,Y$ are \kbd{ZC} or \kbd{ZV}. (The result
has the type of $X$.) Memory efficient (e.g. no-op if $v = 0$), but not
gerepile-safe.

\fun{GEN}{ZC_ZV_mul}{GEN x, GEN y, GEN p} multiplies the \kbd{ZC}~\kbd{x}
(seen as a column vector) by the \kbd{ZV}~\kbd{y} (seen as a row vector,
assumed to have compatible dimensions).

\fun{GEN}{ZV_content}{GEN x} returns the GCD of all the components
of~\kbd{x}.

\fun{GEN}{ZV_prod}{GEN x} returns the product of all the components
of~\kbd{x} ($1$ for the empty vector).

\fun{GEN}{ZV_sum}{GEN x} returns the sum of all the components
of~\kbd{x} ($0$ for the empty vector).

\fun{long}{ZV_max_lg}{GEN x} returns the effective length of the longest
entry in $x$.

\fun{int}{ZV_dvd}{GEN x, GEN y} assuming $x$, $y$ are two \kbd{ZV}s of the same
length, return $1$ if $y[i]$ divides $x[i]$ for all $i$ and $0$ otherwise.
Error if one of the $y[i]$ is $0$.

\fun{GEN}{ZV_sort}{GEN L} sort the \kbd{ZV} $L$.
Returns a vector with the same type as $L$.

\fun{GEN}{ZV_sort_uniq}{GEN L} sort the \kbd{ZV} $L$, removing duplicate
entries. Returns a vector with the same type as $L$.

\fun{long}{ZV_search}{GEN L, GEN y} look for the \typ{INT} $y$ in the sorted
\kbd{ZV} $L$. Return an index $i$ such that $L[i] = y$, and  $0$ otherwise.

\fun{GEN}{ZV_indexsort}{GEN L} returns the permutation which, applied to the
\kbd{ZV} $L$, would sort the vector. The result is a \typ{VECSMALL}.

\fun{GEN}{ZV_union_shallow}{GEN x, GEN y} given two \emph{sorted} ZV (as per
\tet{ZV_sort}, returns the union of $x$ and $y$. Shallow function. In case two
entries are equal in $x$ and $y$,  include the one from $x$.

\subsubsec{\kbd{ZM}}

\fun{void}{RgM_check_ZM}{GEN A, const char *s} Assuming \kbd{x} is a \typ{MAT}
raise an error if it is not a \kbd{ZM} ($s$ should point to the name of the
caller).

\fun{GEN}{ZM_copy}{GEN x} returns a copy of \kbd{x}.

\fun{int}{ZM_equal}{GEN A, GEN B} returns $1$ if the two \kbd{ZM} are equal
and $0$ otherwise.

\fun{GEN}{ZM_add}{GEN x, GEN y} returns $\kbd{x} + \kbd{y}$ (assumed to have
compatible dimensions).

\fun{GEN}{ZM_sub}{GEN x, GEN y} returns $\kbd{x} - \kbd{y}$ (assumed to have
compatible dimensions).

\fun{GEN}{ZM_neg}{GEN x} returns $-\kbd{x}$.

\fun{GEN}{ZM_mul}{GEN x, GEN y} multiplies \kbd{x} and \kbd{y} (assumed to
have compatible dimensions).

\fun{GEN}{ZM_Z_mul}{GEN x, GEN y} multiplies the \kbd{ZM}~\kbd{x}
by the \typ{INT}~\kbd{y}.

\fun{GEN}{ZM_ZC_mul}{GEN x, GEN y} multiplies the \kbd{ZM}~\kbd{x}
by the \kbd{ZC}~\kbd{y} (seen as a column vector, assumed to have compatible
dimensions).

\fun{GEN}{ZMrow_ZC_mul}{GEN x, GEN y, long i} multiplies the $i$-th row
of \kbd{ZM}~\kbd{x} by the \kbd{ZC}~\kbd{y} (seen as a column vector, assumed
to have compatible dimensions). Assumes that $x$ is non-empty and
$0 < i < \kbd{lg(x[1])}$.

\fun{GEN}{ZV_ZM_mul}{GEN x, GEN y} multiplies the \kbd{ZV}~\kbd{x}
by the \kbd{ZM}~\kbd{y}. Returns a \typ{VEC}.

\fun{GEN}{ZM_Z_divexact}{GEN x, GEN y} returns $x/y$ assuming all divisions
are exact.

\fun{GEN}{ZM_pow}{GEN x, GEN n} returns $\kbd{x}^\kbd{n}$, assuming \kbd{x}
is a square \kbd{ZM} and $\kbd{n}\geq 0$.

\fun{GEN}{ZM_detmult}{GEN M} if \kbd{M} is a \kbd{ZM}, returns a multiple of
the determinant of the lattice generated by its columns. This is the function
underlying \tet{detint}.

\fun{GEN}{ZM_supnorm}{GEN x} return the sup norm of the \kbd{ZM} $x$.

\fun{GEN}{ZM_charpoly}{GEN M} returns the characteristic polynomial (in
variable $0$) of the \kbd{ZM} $M$.

\fun{long}{ZM_max_lg}{GEN x} returns the effective length of the longest
entry in $x$.

\fun{GEN}{ZM_inv}{GEN M, GEN d} if \kbd{M} is a \kbd{ZM} and \kbd{d}
is a \typ{INT} such that $M' := \kbd{d}\kbd{M}^{-1}$ is integral,
return $M'$. It is allowed to set \kbd{d = NULL}, in which case, the
determinant of \kbd{M} is computed and used instead.

\fun{GEN}{QM_inv}{GEN M, GEN d} as above, with \kbd{M} a \kbd{QM}. We
still assume that $M'$ has integer coefficients.

\fun{GEN}{ZM_det_triangular}{GEN x} returns the product of the diagonal
entries of $x$ (its determinant if it is indeed triangular).

\fun{int}{ZM_isidentity}{GEN x} return 1 is the \typ{ZM} $x$ is the
identity matrix, and 0 otherwise.

\fun{int}{ZM_ishnf}{GEN x} return $1$ if $x$ is in HNF form, i.e. is upper
triangular with positive diagonal coefficients, and  for $j>i$,
$x_{i,i}>x_{i,j} \ge 0$.

\subsec{\kbd{zv}, \kbd{zm}}

\fun{GEN}{zv_neg}{GEN x} return $-x$. No check for overflow is done, which
occurs in the fringe case where an entry is equal to $2^{\B-1}$.

\fun{long}{zv_content}{GEN x} returns the gcd of the entries of $x$.

\fun{long}{zv_prod}{GEN x} returns the product of all the components
of~\kbd{x} (assumes no overflow occurs).

\fun{long}{zv_sum}{GEN x} returns the sum of all the components
of~\kbd{x} (assumes no overflow occurs).

\fun{int}{zv_cmp0}{GEN x} returns 1 if all entries of the \kbd{zv} $x$ are $0$,
and $0$ otherwise.

\fun{int}{zv_equal}{GEN x, GEN y} returns $1$ if the two \kbd{zv} are equal
and $0$ otherwise.

\fun{GEN}{zv_copy}{GEN x} as \kbd{Flv\_copy}.

\fun{GEN}{zm_transpose}{GEN x} as \kbd{Flm\_transpose}.

\fun{GEN}{zm_copy}{GEN x} as \kbd{Flm\_copy}.

\fun{GEN}{zero_zm}{long m, long n} as \kbd{zero\_Flm}.

\fun{GEN}{zero_zv}{long n} as \kbd{zero\_Flv}.

\fun{GEN}{row_zm}{GEN A, long x0} as \kbd{row\_Flm}.

\subsec{\kbd{RgC} / \kbd{RgV}, \kbd{RgM}}

\kbd{RgC} and \kbd{RgV} routines assume the inputs are \kbd{VEC} or \kbd{COL}
of the same dimension. \kbd{RgM} assume the inputs are \kbd{MAT} of
compatible dimensions.

\fun{GEN}{RgC_add}{GEN x, GEN y} returns $x + y$ as a \typ{COL}.

\fun{GEN}{RgC_neg}{GEN x} returns $-x$ as a \typ{COL}.

\fun{GEN}{RgC_sub}{GEN x, GEN y} returns $x - y$ as a \typ{COL}.

\fun{GEN}{RgV_add}{GEN x, GEN y} returns $x + y$ as a \typ{VEC}.

\fun{GEN}{RgV_neg}{GEN x} returns $-x$ as a \typ{VEC}.

\fun{GEN}{RgV_sub}{GEN x, GEN y} returns $x - y$ as a \typ{VEC}.

\fun{GEN}{RgM_add}{GEN x, GEN y} return $x+y$.

\fun{GEN}{RgM_neg}{GEN x} returns $-x$.

\fun{GEN}{RgM_sub}{GEN x, GEN y} returns $x-y$.

\fun{GEN}{RgM_Rg_add}{GEN x, GEN y} assuming $x$ is a square matrix
and $y$ a scalar, returns the square matrix $x + y*\text{Id}$.

\fun{GEN}{RgM_Rg_add_shallow}{GEN x, GEN y} as \kbd{RgM\_Rg\_add} with much
fewer copies. Not suitable for \kbd{gerepileupto}.

\fun{GEN}{RgC_Rg_add}{GEN x, GEN y} assuming $x$ is a non-empty column vector
and $y$ a scalar, returns the vector $[x_1 + y, x_2,\dots,x_n]$.

\fun{GEN}{RgC_Rg_div}{GEN x, GEN y}

\fun{GEN}{RgM_Rg_div}{GEN x, GEN y} returns $x/y$ ($y$ treated as a scalar).

\fun{GEN}{RgC_Rg_mul}{GEN x, GEN y}

\fun{GEN}{RgV_Rg_mul}{GEN x, GEN y}

\fun{GEN}{RgM_Rg_mul}{GEN x, GEN y} returns $x\times y$ ($y$ treated as a
scalar).

\fun{GEN}{RgV_RgC_mul}{GEN x, GEN y} returns $x\times y$.

\fun{GEN}{RgV_RgM_mul}{GEN x, GEN y} returns $x\times y$.

\fun{GEN}{RgM_RgC_mul}{GEN x, GEN y} returns $x\times y$.

\fun{GEN}{RgM_mul}{GEN x, GEN y} returns $x\times y$.

\fun{GEN}{RgM_mulreal}{GEN x, GEN y} returns the real part of $x\times y$
(whose entries are \typ{INT}, \typ{FRAC}, \typ{REAL} or \typ{COMPLEX}).

\fun{GEN}{RgM_sqr}{GEN x} returns $x^2$.

\fun{GEN}{RgC_RgV_mul}{GEN x, GEN y} returns $x\times y$ (the square matrix
$(x_iy_j)$).

The following two functions are not well defined in general and only provided
for convenience in specific cases:

\fun{GEN}{RgC_RgM_mul}{GEN x, GEN y} returns $x\times y[1,]$ is $y$ is
a row matrix $1\times n$, error otherwise.

\fun{GEN}{RgM_RgV_mul}{GEN x, GEN y} returns $x\times y[,1]$ is $y$ is
a column matrix $n\times 1$, error otherwise.

\fun{GEN}{RgM_powers}{GEN x, long n} returns $[\kbd{x}^0,
\dots, \kbd{x}^\kbd{n}]$ as a \typ{VEC} of \kbd{RgM}s.

\smallskip
\fun{GEN}{RgV_sum}{GEN v} sum of the entries of $v$

\fun{GEN}{RgV_sumpart}{GEN v, long n} returns the sum $v[1] + \dots + v[n]$
(assumes that \kbd{lg}$(v) > n$).

\fun{GEN}{RgV_sumpart2}{GEN v, long m, long n} returns the sum $v[m] + \dots +
v[n]$ (assumes that \kbd{lg}$(v) > n$ and $m > 0$). Returns \kbd{gen\_0}
when $m > n$.

\fun{GEN}{RgV_dotproduct}{GEN x,GEN y} returns the scalar product of $x$ and $y$

\fun{GEN}{RgV_dotsquare}{GEN x} returns the scalar product of $x$ with itself.

\fun{GEN}{RgM_inv}{GEN a} returns a left inverse of $a$ (which needs not be
square), or \kbd{NULL} if this turns out to be impossible. The latter
happens when the matrix does not have maximal rank (or when rounding errors
make it appear so).

\fun{GEN}{RgM_inv_upper}{GEN a} as \kbd{RgM\_inv}, assuming that $a$ is a
non-empty invertible upper triangular matrix, hence a little faster.

\fun{GEN}{RgM_solve}{GEN a, GEN b} returns $a^{-1}b$ where $a$ is a square
\typ{MAT} and $b$ is a \typ{COL} or \typ{MAT}.
Returns \kbd{NULL} if $a^{-1}$ cannot be computed, see \tet{RgM_inv}.

\fun{GEN}{RgM_solve_realimag}{GEN M, GEN b} $M$ being a \typ{MAT}
with $r_1+r_2$ rows and $r_1+2r_2$ columns, $y$ a \typ{COL} or \typ{MAT}
such that the equation $Mx = y$ makes sense, returns $x$ under the following
simplifying assumptions: the first $r_1$ rows of $M$ and $y$ are real
(the $r_2$ others are complex), and $x$ is real. This is stabler and faster
than calling $\kbd{RgM\_solve}(M, b)$ over $\C$. In most applications,
$M$ approximates the complex embeddings of an integer basis in a number
field, and $x$ is actually rational.

\fun{GEN}{split_realimag}{GEN x, long r1, long r2} $x$ is a \typ{COL} or
\typ{MAT} with $r_1 + r_2$ rows, whose first $r_1$ rows have real entries
(the $r_2$ others are complex). Return an object of the same type as
$x$ and $r_1 + 2r_2$ rows, such that the first $r_1 + r_2$ rows contain
the real part of $x$, and the $r_2$ following ones contain the imaginary part
of the last $r_2$ rows of $x$. Called by \tet{RgM_solve_realimag}.

\fun{GEN}{RgM_det_triangular}{GEN x} returns the product of the diagonal
entries of $x$ (its determinant if it is indeed triangular).

\fun{GEN}{RgM_diagonal}{GEN m} returns the diagonal of $m$ as a \typ{VEC}.

\fun{GEN}{RgM_diagonal_shallow}{GEN m} shallow version of \kbd{RgM\_diagonal}

\fun{GEN}{gram_matrix}{GEN v} returns the \idx{Gram matrix} $(v_i\cdot v_j)$
associated to the entries of $v$ (matrix or vector).

\fun{GEN}{RgC_gtofp}{GEN x, GEN prec} returns the \typ{COL} obtained by
applying \kbd{gtofp(gel(x,i), prec)} to all coefficients of $x$.

\fun{GEN}{RgC_fpnorml2}{GEN x, long prec} returns (a stack-clean variant of)
\bprog
  gnorml2( RgC_gtofp(x, prec) )
@eprog

\fun{GEN}{RgM_gtofp}{GEN x, GEN prec} returns the \typ{MAT} obtained by
applying \kbd{gtofp(gel(x,i), prec)} to all coefficients of $x$.

\fun{GEN}{RgM_fpnorml2}{GEN x, long prec} returns (a stack-clean variant of)
\bprog
  gnorml2( RgM_gtofp(x, prec) )
@eprog

The following routines check whether matrices or vectors have a special
shape, using \kbd{gequal1} and \kbd{gequal0} to test components. (This makes a
difference when components are inexact.)

\fun{int}{RgV_isscalar}{GEN x} return 1 if all the entries of $x$ are $0$
(as per \kbd{gequal0}), except possibly the first one. The name comes from
vectors expressing polynomials on the standard basis $1,T,\dots, T^{n-1}$, or
on \kbd{nf.zk} (whose first element is $1$).

\fun{int}{QV_isscalar}{GEN x} as \kbd{RgV\_isscalar}, assuming $x$ is a
\kbd{QV} (\typ{INT} and \typ{FRAC} entries only).

\fun{int}{ZV_isscalar}{GEN x} as \kbd{RgV\_isscalar}, assuming $x$ is a
\kbd{ZV} (\typ{INT} entries only).

\fun{int}{RgM_isscalar}{GEN x, GEN s} return 1 if $x$ is the scalar matrix
equal to $s$ times the identity, and 0 otherwise. If $s$ is \kbd{NULL}, test
whether $x$ is an arbitrary scalar matrix.

\fun{int}{RgM_isidentity}{GEN x} return 1 is the \typ{MAT} $x$ is the
identity matrix, and 0 otherwise.

\fun{int}{RgM_isdiagonal}{GEN x} return 1 is the \typ{MAT} $x$ is a
diagonal matrix, and 0 otherwise.

\fun{int}{RgM_is_ZM}{GEN x} return 1 is the \typ{MAT}~$x$ has only
\typ{INT} coefficients, and 0 otherwise.

\fun{long}{RgV_isin}{GEN v, GEN x} return the first index $i$ such that
$v[i] = x$ if it exists, and $0$ otherwise. Naive search in linear time, does
not assume that \kbd{v} is sorted.

\fun{GEN}{Frobeniusform}{GEN V, long n} given the vector $V$ of elementary
divisors for $M - x\text{Id}$, where $M$ is an $n\times n$ square matrix.
Returns the Frobenius form of $M$. Used by \kbd{matfrobenius}.

\subsec{Obsolete functions}

The functions in this section are kept for backward compatibility only
and will eventually disappear.

\fun{GEN}{image2}{GEN x} compute the image of $x$ using a very slow
algorithm. Use \tet{image} instead.

\section{Integral, rational and generic polynomial arithmetic}

\subsec{\kbd{ZX}, \kbd{QX}}

\fun{void}{RgX_check_ZX}{GEN x, const char *s} Assuming \kbd{x} is a \typ{POL}
raise an error if it is not a \kbd{ZX} ($s$ should point to the name of the
caller).

\fun{void}{RgX_check_ZXY}{GEN x, const char *s} Assuming \kbd{x} is a \typ{POL}
raise an error if it one of its coefficients is not an integer or a \kbd{ZX}
($s$ should point to the name of the caller).

\fun{GEN}{ZX_copy}{GEN x,GEN p} returns a copy of \kbd{x}.

\fun{GEN}{scalar_ZX}{GEN x, long v} returns the constant \kbd{ZX} in variable
$v$ equal to the \typ{INT} $x$.

\fun{GEN}{scalar_ZX_shallow}{GEN x, long v} returns the constant \kbd{ZX} in
variable $v$ equal to the \typ{INT} $x$. Shallow function not suitable for
\kbd{gerepile} and friends.

\fun{GEN}{ZX_renormalize}{GEN x, long l}, as \kbd{normalizepol}, where
$\kbd{l} = \kbd{lg(x)}$, in place.

\fun{int}{ZX_equal}{GEN x, GEN y} returns $1$ if the two \kbd{ZX} are equal
and $0$ otherwise.

\fun{GEN}{ZX_add}{GEN x,GEN y} adds \kbd{x} and \kbd{y}.

\fun{GEN}{ZX_sub}{GEN x,GEN y} subtracts \kbd{x} and \kbd{y}.

\fun{GEN}{ZX_neg}{GEN x,GEN p} returns $-\kbd{x}$.

\fun{GEN}{ZX_Z_add}{GEN x,GEN y} adds the integer \kbd{y} to the
\kbd{ZX}~\kbd{x}.

\fun{GEN}{ZX_Z_sub}{GEN x,GEN y} subtracts the integer \kbd{y} to the
\kbd{ZX}~\kbd{x}.

\fun{GEN}{Z_ZX_sub}{GEN x,GEN y} subtracts the \kbd{ZX} \kbd{y} to the
integer \kbd{x}.

\fun{GEN}{ZX_Z_mul}{GEN x,GEN y} multiplies the \kbd{ZX} \kbd{x} by the integer \kbd{y}.

\fun{GEN}{ZX_Z_divexact}{GEN x, GEN y} returns $x/y$ assuming all divisions
are exact.

\fun{GEN}{ZXV_Z_mul}{GEN x,GEN y} multiplies the vector of \kbd{ZX} \kbd{x}
by the integer \kbd{y}.

\fun{GEN}{ZX_mul}{GEN x,GEN y} multiplies \kbd{x} and \kbd{y}.

\fun{GEN}{ZX_sqr}{GEN x,GEN p} returns $\kbd{x}^2$.

\fun{GEN}{ZX_mulspec}{GEN a, GEN b, long na, long nb}. Internal routine:
\kbd{a} and \kbd{b} are arrays of coefficients representing polynomials
$\sum_{i = 0}^{\kbd{na-1}} \kbd{a}[i] X^i$ and
$\sum_{i = 0}^{\kbd{nb-1}} \kbd{b}[i] X^i$. Returns their product (as a true
\kbd{GEN}).

\fun{GEN}{ZX_sqrspec}{GEN a, long na}. Internal routine:
\kbd{a} is an array of coefficients representing polynomial
$\sum_{i = 0}^{\kbd{na-1}} \kbd{a}[i] X^i$. Return its square (as a true
\kbd{GEN}).

\fun{GEN}{ZX_rem}{GEN x, GEN y} returns the remainder of the Euclidean
division of $x$ mod $y$. Assume that $x$, $y$ are two \kbd{ZX} and that
$y$ is monic.

\fun{GEN}{ZXQ_mul}{GEN x,GEN y,GEN T} returns $x*y$ mod $T$, assuming
that all inputs are \kbd{ZX}s and that $T$ is monic.

\fun{GEN}{ZXQ_sqr}{GEN x,GEN T} returns $x^2$ mod $T$, assuming
that all inputs are \kbd{ZX}s and that $T$ is monic.

\fun{long}{ZX_valrem}{GEN P, GEN *z} as \kbd{RgX\_valrem}, but assumes
\kbd{P} has \typ{INT} coefficients.

\fun{long}{ZX_val}{GEN P} as \kbd{RgX\_val}, but assumes \kbd{P} has \typ{INT}
coefficients.

\fun{GEN}{ZX_gcd}{GEN x,GEN y} returns a gcd of the \kbd{ZX} $x$ and $y$.
Not memory-clean, but suitable for \kbd{gerepileupto}.

\fun{GEN}{ZX_gcd_all}{GEN x, GEN y, GEN *pX}. returns a gcd $d$ of $x$ and
$y$. If \kbd{pX} is not \kbd{NULL}, set $\kbd{*pX}$ to a (non-zero) integer
multiple of $x/d$. If $x$ and $y$ are both monic, then $d$ is monic and
\kbd{*pX} is exactly $x/d$. Not memory clean if the gcd is $1$
(in that case \kbd{*pX} is set to $x$).

\fun{GEN}{ZX_content}{GEN x} returns the content of the \kbd{ZX} $x$.

\fun{GEN}{QX_gcd}{GEN x,GEN y} returns a gcd of the \kbd{QX} $x$ and $y$.

\fun{GEN}{ZX_to_monic}{GEN q GEN *L} given $q$ a non-zero \kbd{ZX},
returns a monic integral polynomial $Q$ such that $Q(x) = C q(x/L)$, for some
rational $C$ and positive integer $L > 0$. If $\kbd{L}$ is not \kbd{NULL},
set \kbd{*L} to $L$; if $L = 1$, \kbd{*L} is set to \kbd{gen\_1}. Not
suitable for gerepileupto.

\fun{GEN}{ZX_primitive_to_monic}{GEN q, GEN *L} as \tet{ZX_to_monic} except
$q$ is assumed to have trivial content, which avoids recomputing it.
The result is suboptimal if $q$ is not primitive ($L$ larger than
necessary), but remains correct.

\fun{GEN}{ZX_Z_normalize}{GEN q, GEN *L} a restricted version of
\kbd{ZX\_primitive\_to\_monic}, where $q$ is a \emph{monic} \kbd{ZX}
of degree $> 0$. Finds the largest integer $L > 0$ such that
$Q(X) := L^{-\deg q} q(Lx)$ is integral and return $Q$; this is not
well-defined if $q$ is a monomial, in that case, set $L=1$ and $Q = q$. If
\kbd{L} is not \kbd{NULL}, set \kbd{*L} to $L$.

\fun{GEN}{ZX_Q_normalize}{GEN q, GEN *L} a variant of \tet{ZX_Z_normalize}
where $L > 0$ is allowed to be rational, the monic $Q\in \Z[X]$ has possibly
smaller coefficients.

\fun{GEN}{ZX_rescale}{GEN P, GEN h} returns $h^{\deg(P)} P(x/h)$.
\kbd{P} is a \kbd{ZX} and \kbd{h} is a non-zero integer. (Leaves small
objects on the stack. Suitable but inefficient for \kbd{gerepileupto}.)

\fun{long}{ZX_max_lg}{GEN x} returns the effective length of the longest
component in $x$.

\fun{long}{ZXY_max_lg}{GEN x} returns the effective length of the longest
component in $x$; assume all coefficients are \typ{INT} or \kbd{ZX}s.

\fun{GEN}{ZXQ_charpoly}{GEN A, GEN T, long v}: let \kbd{T} and \kbd{A} be
\kbd{ZX}s, returns the characteristic polynomial of \kbd{Mod(A, T)}.
More generally, \kbd{A} is allowed to be a \kbd{QX}, hence possibly has
rational coefficients, \emph{assuming} the result is a \kbd{ZX}, i.e.~the
algebraic number \kbd{Mod(A,T)} is integral over \kbd{Z}.

\fun{GEN}{ZX_deriv}{GEN x} returns the derivative of \kbd{x}.

\fun{GEN}{ZX_disc}{GEN T} returns the discriminant of the \kbd{ZX}
\kbd{T}.

\fun{GEN}{QX_disc}{GEN T} returns the discriminant of the \kbd{QX}
\kbd{T}.

\fun{int}{ZX_is_squarefree}{GEN T} returns $1$ if the
\kbd{ZX}~\kbd{T} is squarefree, $0$ otherwise.

\fun{GEN}{ZX_factor}{GEN T} returns the factorization of the primitive part
of \kbd{T} over $\Q[X]$ (the content is lost).

\fun{GEN}{QX_factor}{GEN T} as \kbd{ZX\_factor}.

\fun{long}{ZX_is_irred}{GEN T} returns 1 it \kbd{T} is irreducible, and
0 otherwise.

\fun{GEN}{ZX_squff}{GEN T, GEN *E} write $T$ as a product $\prod T_i^{e_i}$
with the $e_1 < e_2 < \cdots$ all distinct and the $T_i$ pairwise coprime.
Return the vector of the $T_i$, and set \kbd{*E} to the vector of the $e_i$,
as a \typ{VECSMALL}.

\fun{GEN}{ZX_resultant}{GEN A, GEN B} returns the resultant of the
\kbd{ZX}~\kbd{A} and \kbd{B}.

\fun{GEN}{QX_resultant}{GEN A, GEN B} returns the resultant of the
\kbd{QX}~\kbd{A} and \kbd{B}.

\fun{GEN}{QXQ_norm}{GEN A, GEN B} $A$ being a \kbd{QX} and $B$ being a
\kbd{ZX}, returns the norm of the algebraic number $A \mod B$, using a
modular algorithm. To ensure that $B$ is a \kbd{ZX}, one may replace it by
\kbd{Q\_primpart(B)}, which of course does not change the norm.

If $A$ is not a \kbd{ZX} --- it has a denominator ---, but the result is
nevertheless known to be an integer, it is much more efficient to call
\tet{QXQ_intnorm} instead.

\fun{GEN}{QXQ_intnorm}{GEN A, GEN B} $A$ being a \kbd{QX} and $B$
being a \kbd{ZX}, returns the norm of the algebraic number $A \mod B$,
\emph{assuming} that the result is an integer, which is for instance the case
is $A\mod B$ is an algebraic integer, in particular if $A$ is a \kbd{ZX}. To
ensure that $B$ is a \kbd{ZX}, one may replace it by \kbd{Q\_primpart(B)}
(which of course does not change the norm).

If the result is not known to be an integer, you must use \tet{QXQ_norm}
instead, which is slower.

\fun{GEN}{ZX_ZXY_resultant}{GEN A, GEN B}
under the assumption that \kbd{A} in $\Z[Y]$, \kbd{B} in $\Q[Y][X]$, and
$R = \text{Res}_Y(A, B) \in \Z[X]$, returns the resultant $R$.

\fun{GEN}{ZX_ZXY_rnfequation}{GEN A, GEN B, long *lambda},
assume \kbd{A} in $\Z[Y]$, \kbd{B} in $\Q[Y][X]$, and $R =
\text{Res}_Y(A, B) \in \Z[X]$. If \kbd{lambda = NULL}, returns $R$
as in \kbd{ZY\_ZXY\_resultant}. Otherwise, \kbd{lambda} must point to
some integer, e.g. $0$ which is used as a seed. The function then finds a
small $\lambda \in \Z$ (starting from \kbd{*lambda}) such that
$R_\lambda(X) := \text{Res}_Y(A, B(X + \lambda Y))$ is squarefree, resets
\kbd{*lambda} to the chosen value and returns $R_{\lambda}$.

\fun{GEN}{nfgcd}{GEN P, GEN Q, GEN T, GEN den} given $P$ and $Q$ in
$\Z[X,Y]$, $T$ monic irreducible in $\Z[Y]$, returns the primitive $d$ in
$\Z[X,Y]$ which is a gcd of $P$, $Q$ in $K[X]$, where $K$ is the number field
$\Q[Y]/(T)$. If not \kbd{NULL}, \kbd{den} is a multiple of the integral
denominator of the (monic) gcd of $P,Q$ in $K[X]$.

\fun{GEN}{nfgcd_all}{GEN P, GEN Q, GEN T, GEN den, GEN *Pnew} as \kbd{nfgcd}.
If \kbd{Pnew} is not \kbd{NULL}, set \kbd{*Pnew} to a non-zero integer
multiple of $P/d$. If $P$ and $Q$ are both monic, then $d$ is monic and
\kbd{*Pnew} is exactly $P/d$. Not memory clean if the gcd is $1$
(in that case \kbd{*Pnew} is set to $P$).

\fun{GEN}{QXQ_inv}{GEN A, GEN B} returns the inverse of $A$ modulo $B$
where $A$ is a \kbd{QX} and $B$ is a \kbd{ZX}. Should you need this for
a \kbd{QX} $B$, just use
\bprog
  QXQ_inv(A, Q_primpart(B));
@eprog\noindent But in all cases where modular arithmetic modulo $B$ is
desired, it is much more efficient to replace $B$ by \kbd{Q\_primpart$(B)$}
once and for all.

\fun{GEN}{QXQ_powers}{GEN x, long n, GEN T} returns $[\kbd{x}^0, \dots,
\kbd{x}^\kbd{n}]$ as \kbd{RgXQ\_powers} would, but in a more efficient way when
$x$ has a huge integer denominator (we start by removing that denominator).
Meant to be used to precompute powers of algebraic integers in $\Q[t]/(T)$.
The current implementation does not require $x$ to be a \kbd{QX}: any
polynomial to which \kbd{Q\_remove\_denom} can be applied is fine.

\fun{GEN}{QXQ_reverse}{GEN f, GEN T} as \kbd{RgXQ\_reverse}, assuming $f$
is a \kbd{QX}.

\subsec{\kbd{zx}}

\fun{GEN}{zero_zx}{long sv} returns a zero \kbd{zx} in variable $v$.

\fun{GEN}{polx_zx}{long sv} returns the variable $v$ as degree~1~\kbd{Flx}.

\fun{GEN}{zx_renormalize}{GEN x, long l}, as \kbd{Flx\_renormalize}, where
$\kbd{l} = \kbd{lg(x)}$, in place.

\fun{GEN}{zx_shift}{GEN T, long n} returns \kbd{T}
multiplied by $\kbd{x}^n$, assuming $n\geq 0$.

\subsec{\kbd{RgX}}

\fun{long}{RgX_type}{GEN x, GEN *ptp, GEN *ptpol, long *ptprec} returns
the ``natural'' base ring over which the polynomial $x$ is defined. Raise an
error if it detects consistency problems in modular objects: incompatible rings
(e.g. $\F_p$ and $\F_q$ for primes $p\neq q$, $\F_p[X]/(T)$ and $\F_p[X]/(U)$
for $T\neq U$). Minor discrepancies are supported if they make general sense
(e.g. $\F_p$ and $\F_{p^k}$, but not $\F_p$ and $\Q_p$); \typ{FFELT} and
\typ{POLMOD} of \typ{INTMOD}s are considered inconsistent, even if they define
the same field : if you need to use simultaneously these different finite
field implementations, multiply the polynomial by a \typ{FFELT} equal to $1$
first.

\item 0: none of the others (presumably multivariate, possibly inconsistent).

\item \typ{INT}: defined over $\Q$ (not necessarily $\Z$).

\item \typ{INTMOD}: defined over $\Z/p\Z$, where \kbd{*ptp} is set to $p$.
It is not checked whether $p$ is prime.

\item \typ{COMPLEX}: defined over $\C$ (at least one \typ{COMPLEX} with at
least one inexact floating point \typ{REAL} component). Set \kbd{*ptprec}
to the minimal accuracy (as per \kbd{precision}) of inexact components.

\item \typ{REAL}: defined over $\R$ (at least one inexact floating point
\typ{REAL} component). Set \kbd{*ptprec} to the minimal accuracy (as per
\kbd{precision}) of inexact components.

\item \typ{PADIC}: defined over $\Q_p$, where \kbd{*ptp} is set to $p$ and
\kbd{*ptprec} to the $p$-adic accuracy.

\item \typ{FFELT}: defined over a finite field $\F_{p^k}$, where \kbd{*ptp}
is set to the field characteristic $p$ and \kbd{*ptpol} is set to a
\typ{FFELT} belonging to the field.

\item other values are composite corresponding to quotients $R[X]/(T)$, with
one primary type \kbd{t1}, describing the form of the quotient,
and a secondary type \kbd{t2}, describing $R$. If \kbd{t} is the
\kbd{RgX\_type}, \kbd{t1} and \kbd{t2} are recovered using

\fun{void}{RgX_type_decode}{long t, long *t1, long *t2}

\kbd{t1} is one of

\typ{POLMOD} : at least one \typ{POLMOD} component,
set \kbd{*ppol} to the modulus,

\typ{QUAD} : no \typ{POLMOD}, at least one \typ{QUAD} component,
set \kbd{*ppol} to the modulus (\kbd{$-$.pol}) of the \typ{QUAD},

\typ{COMPLEX} : no \typ{POLMOD} or \typ{QUAD}, at least one \typ{COMPLEX}
component, set \kbd{*ppol} to $y^2 + 1$.

and the underlying base ring $R$ is given by \kbd{t2}, which
is one of \typ{INT}, \typ{INTMOD} (set \kbd{*ptp}) or \typ{PADIC}
(set \kbd{*ptp} and \kbd{*ptprec}), with the same meaning
as above.

\fun{int}{RgX_type_is_composite}{long t} $t$ as returned by \kbd{RgX\_type},
return 1 if $t$ is a composite type, and 0 otherwise.

\fun{GEN}{RgX_get_0}{GEN x} returns $0$ in the base ring over which $x$
is defined, to the proper accuracy (e.g. \kbd{0}, \kbd{Mod(0,3)},
\kbd{O(5\pow 10)}).

\fun{GEN}{RgX_get_1}{GEN x} returns $1$ in the base ring over which $x$
is defined, to the proper accuracy (e.g. \kbd{0}, \kbd{Mod(0,3)},

\fun{int}{RgX_isscalar}{GEN x} return 1 if $x$ all the coefficients of
$x$ of degree $> 0$ are $0$ (as per \kbd{gequal0}).

\fun{GEN}{RgX_add}{GEN x,GEN y} adds \kbd{x} and \kbd{y}.

\fun{GEN}{RgX_sub}{GEN x,GEN y} subtracts \kbd{x} and \kbd{y}.

\fun{GEN}{RgX_neg}{GEN x} returns $-\kbd{x}$.

\fun{GEN}{RgX_Rg_add}{GEN y, GEN x} returns $x+y$.

\fun{GEN}{RgX_Rg_add_shallow}{GEN y, GEN x} returns $x+y$; shallow function.

\fun{GEN}{Rg_RgX_sub}{GEN x, GEN y}

\fun{GEN}{RgX_Rg_sub}{GEN y, GEN x} returns $x-y$

\fun{GEN}{RgX_mul}{GEN x, GEN y} multiplies the two \typ{POL} (in the same
variable) \kbd{x} and \kbd{y}. Uses Karatsuba algorithm.

\fun{GEN}{RgX_mulspec}{GEN a, GEN b, long na, long nb}. Internal routine:
\kbd{a} and \kbd{b} are arrays of coefficients representing polynomials
$\sum_{i = 0}^{\kbd{na-1}} \kbd{a}[i] X^i$ and
$\sum_{i = 0}^{\kbd{nb-1}} \kbd{b}[i] X^i$. Returns their product (as a true
\kbd{GEN}).

\fun{GEN}{RgX_sqr}{GEN x} squares the \typ{POL} \kbd{x}. Uses Karatsuba
algorithm.

\fun{GEN}{RgX_sqrspec}{GEN a, long na}. Internal routine:
\kbd{a} is an array of coefficients representing polynomial
$\sum_{i = 0}^{\kbd{na-1}} \kbd{a}[i] X^i$. Return its square (as a true
\kbd{GEN}).

\fun{GEN}{RgX_divrem}{GEN x, GEN y, GEN *r} by default, returns the Euclidean
quotient and store the remainder in $r$. Three special values of $r$ change
that behavior
\item \kbd{NULL}: do not store the remainder, used to implement \kbd{RgX\_div},

\item \tet{ONLY_REM}: return the remainder, used to implement \kbd{RgX\_rem},

\item \tet{ONLY_DIVIDES}: return the quotient if the division is exact, and
\kbd{NULL} otherwise.

\fun{GEN}{RgX_div}{GEN x, GEN y}

\fun{GEN}{RgX_div_by_X_x}{GEN A, GEN a, GEN *r} returns the
quotient of the \kbd{RgX}~\kbd{A} by $(X - \kbd{a})$, and sets \kbd{r} to the
remainder $\kbd{A}(\kbd{a})$.

\fun{GEN}{RgX_rem}{GEN x, GEN y}

\fun{GEN}{RgX_pseudodivrem}{GEN x, GEN y, GEN *ptr} compute a pseudo-quotient
$q$ and pseudo-remainder $r$ such that $\kbd{lc}(y)^{\deg(x) - \deg(y) + 1}x
= qy + r$. Return $q$ and set \kbd{*ptr} to $r$.

\fun{GEN}{RgX_pseudorem}{GEN x, GEN y} return the remainder
in the pseudo-division of $x$ by $y$.

\fun{GEN}{RgXQX_pseudorem}{GEN x, GEN y, GEN T} return the remainder
in the pseudo-division of $x$ by $y$ over $R[X]/(T)$.

\fun{GEN}{RgXQX_pseudodivrem}{GEN x, GEN y, GEN T, GEN *ptr} compute
a pseudo-quotient $q$ and pseudo-remainder $r$ such that
$\kbd{lc}(y)^{\deg(x) - \deg(y) + 1}x = qy + r$ in $R[X]/(T)$. Return $q$ and
set \kbd{*ptr} to $r$.

\fun{GEN}{RgX_mulXn}{GEN x, long n} returns $\kbd{x} * t^n$. This may
be a \typ{FRAC} if $n < 0$ and the valuation of \kbd{x} is not large
enough.

\fun{GEN}{RgX_shift}{GEN x, long n} returns $\kbd{x} * t^n$ if $n\geq 0$,
and $\kbd{x} \bs t^{-n}$ otherwise.

\fun{GEN}{RgX_shift_shallow}{GEN x, long n} as \kbd{RgX\_shift}, but
shallow (coefficients are not copied).

\fun{long}{RgX_valrem}{GEN P, GEN *pz} returns the valuation $v$ of the
\typ{POL}~\kbd{P} with respect to its main variable $X$. Check whether
coefficients are $0$ using \kbd{gequal0}. Set \kbd{*pz} to
$\kbd{RgX\_shift\_shallow}(P,-v)$.

\fun{long}{RgX_val}{GEN P} returns the valuation $v$ of the
\typ{POL}~\kbd{P} with respect to its main variable $X$. Check whether
coefficients are $0$ using \kbd{gequal0}.

\fun{long}{RgX_valrem_inexact}{GEN P, GEN *z} as \kbd{RgX\_valrem}, using
\kbd{isexactzero} instead of \kbd{gequal0}.

\fun{GEN}{RgX_deriv}{GEN x} returns the derivative of \kbd{x} with respect to
its main variable.

\fun{GEN}{RgX_gcd}{GEN x, GEN y} returns the GCD of \kbd{x} and \kbd{y},
assumed to be \typ{POL}s in the same variable.

\fun{GEN}{RgX_gcd_simple}{GEN x, GEN y} as \tet{RgX_gcd} using a standard
extended Euclidean algorithm. Usually slower than \tet{RgX_gcd}.

\fun{GEN}{RgX_extgcd}{GEN x, GEN y, GEN *u, GEN *v} returns
$d = \text{GCD}(\kbd{x},\kbd{y})$, and sets \kbd{*u}, \kbd{*v} to the Bezout
coefficients such that $\kbd{*ux} + \kbd{*vy} = d$. Uses a generic
subresultant algorithm.

\fun{GEN}{RgX_extgcd_simple}{GEN x, GEN y, GEN *u, GEN *v} as
\tet{RgX_extgcd} using a standard extended Euclidean algorithm. Usually
slower than \tet{RgX_extgcd}.

\fun{GEN}{RgX_disc}{GEN x} returns the discriminant of the \typ{POL} \kbd{x}
with respect to its main variable.

\fun{GEN}{RgX_resultant_all}{GEN x, GEN y, GEN *sol} returns
\kbd{resultant(x,y)}. If \kbd{sol} is not \kbd{NULL}, sets it to the last
non-zero remainder in the polynomial remainder sequence if it exists and to
\kbd{gen\_0} otherwise (e.g. one polynomial has degree 0). Compared to
\kbd{resultant\_all}, this function always uses the generic subresultant
algorithm, hence always computes \kbd{sol}.

\fun{GEN}{RgX_modXn_shallow}{GEN x, long n} return $\kbd{x \% } t^n$,
where $n\geq 0$. Shallow function.

\fun{GEN}{RgX_renormalize}{GEN x} remove leading terms in \kbd{x} which are
equal to (necessarily inexact) zeros.

\fun{GEN}{RgX_gtofp}{GEN x, GEN prec} returns the polynomial obtained by
applying
\bprog
  gtofp(gel(x,i), prec)
@eprog\noindent to all coefficients of $x$.

\fun{GEN}{RgX_fpnorml2}{GEN x, long prec} returns (a stack-clean variant of)
\bprog
  gnorml2( RgX_gtofp(x, prec) )
@eprog

\fun{GEN}{RgX_recip}{GEN P} returns the reverse of the polynomial
$P$, i.e. $X^{\deg P} P(1/X)$.

\fun{GEN}{RgX_recip_shallow}{GEN P} shallow function of \tet{RgX_recip}.

\fun{GEN}{RgX_deflate}{GEN P, long d} assuming $P$ is a polynomial of the
form $Q(X^d)$, return $Q$. Shallow function, not suitable for
\kbd{gerepileupto}.

\fun{long}{RgX_deflate_max}{GEN P, long *d} sets \kbd{d} to the largest exponent
such that $P$ is of the form $P(x^d)$ (use \kbd{gequal0} to check
whether coefficients are 0), $0$ if $P$ is the zero polynomial. Returns
\kbd{RgX\_deflate(P,d)}.

\fun{GEN}{RgX_inflate}{GEN P, long d} return $P(X^d)$. Shallow function, not
suitable for \kbd{gerepileupto}.

\fun{GEN}{RgX_rescale}{GEN P, GEN h} returns $h^{\deg(P)} P(x/h)$.
\kbd{P} is an \kbd{RgX} and \kbd{h} is non-zero. (Leaves small objects on the
stack. Suitable but inefficient for \kbd{gerepileupto}.)

\fun{GEN}{RgX_unscale}{GEN P, GEN h} returns $P(h x)$. (Leaves small objects
on the stack. Suitable but inefficient for \kbd{gerepileupto}.)

\fun{GEN}{RgXV_unscale}{GEN v, GEN h} apply \kbd{RgX\_unscale} to a vector
of \kbd{RgX}.

\fun{int}{RgX_is_rational}{GEN P} return 1 is the \kbd{RgX}~$P$ has only
rational coefficients (\typ{INT} and \typ{FRAC}), and 0 otherwise.

\fun{int}{RgX_is_ZX}{GEN P} return 1 is the \kbd{RgX}~$P$ has only
\typ{INT} coefficients, and 0 otherwise.

\fun{int}{RgX_is_monomial}{GEN x} returns 1 (true) if \kbd{x} is a non-zero
monomial in its main variable, 0~otherwise.

\fun{long}{RgX_equal}{GEN x, GEN y} returns $1$ if the \typ{POL}s $x$ and $y$
have the same \kbd{degpol} and their coefficients are equal (as per
\tet{gequal}). Variable numbers are not checked. Note that this is more
stringent than \kbd{gequal(x,y)}, which only checks whether $x - y$ satisfies
\kbd{gequal0}; in particular, they may have different apparent degrees provided
the extra leading terms are $0$.

\fun{long}{RgX_equal_var}{GEN x, GEN y} returns $1$ if $x$ and $y$
have the same variable number and \kbd{RgX\_equal(x,y)} is $1$.
\smallskip

\fun{GEN}{RgXQ_mul}{GEN y, GEN x, GEN T} computes $xy$ mod $T$

\fun{GEN}{RgXQ_sqr}{GEN x, GEN T} computes $x^2$ mod $T$

\fun{GEN}{RgXQ_inv}{GEN x, GEN T} return the inverse of $x$ mod $T$.

\fun{GEN}{RgXQ_pow}{GEN x, GEN n, GEN T} computes $x^n$ mod $T$

\fun{GEN}{RgXQ_powu}{GEN x, ulong n, GEN T} computes $x^n$ mod $T$,
$n$ being an \kbd{ulong}.

\fun{GEN}{RgXQ_powers}{GEN x, long n, GEN T} returns $[\kbd{x}^0,
\dots, \kbd{x}^\kbd{n}]$ as a \typ{VEC} of \kbd{RgXQ}s.

\fun{int}{RgXQ_ratlift}{GEN x, GEN T, long amax, long bmax, GEN *P, GEN *Q}
Assuming that $\kbd{amax}+\kbd{bmax}<\deg T$,
attempts to recognize $x$ as a rational function $a/b$, i.e. to find \typ{POL}s $P$ and $Q$ such that

\item $P \equiv Q x$ modulo $T$,

\item $\deg P \leq \kbd{amax}$, $\deg Q \leq \kbd{bmax}$,

\item $\gcd(T,P) = \gcd(P,Q)$.

\noindent If unsuccessful, the routine returns $0$ and leaves $P$, $Q$
unchanged; otherwise it returns $1$ and sets $P$ and $Q$.

\fun{GEN}{RgXQ_reverse}{GEN f, GEN T} returns a \typ{POL} $g$ of degree $< n
= \text{deg}~T$ such that $T(x)$ divides $(g \circ f)(x) - x$, by solving a
linear system. Low-level function underlying \tet{modreverse}: it returns a
lift of \kbd[modreverse(f,T)]; faster than the high-level function since it
needs not compute the characteristic polynomial of $f$ mod $T$ (often already
known in applications). In the trivial case where $n \leq 1$, returns a
scalar, not a constant \typ{POL}.

\fun{GEN}{RgXQ_matrix_pow}{GEN y, long n, long m, GEN P} returns
\kbd{RgXQ\_powers(y,m-1,P)}, as a matrix of dimension $n \geq \deg P$.

\fun{GEN}{RgXQ_norm}{GEN x, GEN T} returns the norm of \kbd{Mod(x, T)}.

\fun{GEN}{RgXQ_charpoly}{GEN x, GEN T, long v} returns the characteristic
polynomial of \kbd{Mod(x, T)}, in variable $v$.

\fun{GEN}{RgX_RgXQ_eval}{GEN f, GEN x, GEN T} returns $\kbd{f}(\kbd{x})$ modulo
$T$.

\fun{GEN}{RgX_RgXQV_eval}{GEN f, GEN V} as \kbd{RgX\_RgXQ\_eval(f, x, T)},
assuming $V$ was output by \kbd{RgXQ\_powers(x, n, T)}.

\fun{GEN}{QX_ZXQV_eval}{GEN f, GEN nV, GEN dV} as \kbd{RgX\_RgXQV\_eval},
except that $f$ is assumed to be a \kbd{QX}, $V$ is given implicitly
by a numerator \kbd{nV} (\kbd{ZV}) and denominator \kbd{dV} (a positive
\typ{INT} or \kbd{NULL} for trivial denominator). Not memory clean, but
suitable for \kbd{gerepileupto}.

\fun{GEN}{RgX_translate}{GEN P, GEN c} assume $c$ is a scalar or
a polynomials whose main variable has lower priority than the main variable
$X$ of $P$. Returns $P(X + c)$ (optimized for $c = \pm 1$).

\fun{GEN}{RgXQX_translate}{GEN P, GEN c, GEN T} assume the main variable
$X$ of $P$ has higher priority than the main variable $Y$ of $T$ and $c$.
Return a lift of $P(X+\text{Mod}(c(Y), T(Y)))$.

\fun{GEN}{RgXQC_red}{GEN z, GEN T} \kbd{z} a vector whose
coefficients are \kbd{RgX}s (arbitrary \kbd{GEN}s in fact), reduce them to
\kbd{RgXQ}s (applying \kbd{grem} coefficientwise) in a \typ{COL}.

\fun{GEN}{RgXQV_red}{GEN z, GEN T} \kbd{z} a \typ{POL} whose
coefficients are \kbd{RgX}s (arbitrary \kbd{GEN}s in fact), reduce them to
\kbd{RgXQ}s (applying \kbd{grem} coefficientwise) in a \typ{VEC}.

\fun{GEN}{RgXQX_red}{GEN z, GEN T} \kbd{z} a \typ{POL} whose
coefficients are \kbd{RgX}s (arbitrary \kbd{GEN}s in fact), reduce them to
\kbd{RgXQ}s (applying \kbd{grem} coefficientwise).

\fun{GEN}{RgXQX_mul}{GEN x, GEN y, GEN T}

\fun{GEN}{RgX_Rg_mul}{GEN y, GEN x} multiplies the \kbd{RgX} \kbd{y}
by the scalar \kbd{x}.

\fun{GEN}{RgX_muls}{GEN y, long s} multiplies the \kbd{RgX} \kbd{y}
by the \kbd{long}~\kbd{s}.

\fun{GEN}{RgX_Rg_div}{GEN y, GEN x} divides the \kbd{RgX} \kbd{y}
by the scalar \kbd{x}.

\fun{GEN}{RgX_divs}{GEN y, long s} divides the \kbd{RgX} \kbd{y}
by the \kbd{long}~\kbd{s}.

\fun{GEN}{RgX_Rg_divexact}{GEN x, GEN y} exact division of the \kbd{RgX}
\kbd{y} by the scalar \kbd{x}.

\fun{GEN}{RgXQX_RgXQ_mul}{GEN x, GEN y, GEN T} multiplies the \kbd{RgXQX}
\kbd{y} by the scalar (\kbd{RgXQ}) \kbd{x}.

\fun{GEN}{RgXQX_sqr}{GEN x, GEN T}

\fun{GEN}{RgXQX_divrem}{GEN x, GEN y, GEN T, GEN *pr}

\fun{GEN}{RgXQX_div}{GEN x, GEN y, GEN T, GEN *r}

\fun{GEN}{RgXQX_rem}{GEN x, GEN y, GEN T, GEN *r}

\newpage
\chapter{Operations on general PARI objects}

\section{Assignment}

It is in general easier to use a direct conversion,
e.g.~\kbd{y = stoi(s)}, than to allocate a target of correct type and
sufficient size, then assign to it:
\bprog
  GEN y = cgeti(3); affsi(s, y);
@eprog\noindent
These functions can still be moderately useful in complicated garbage
collecting scenarios but you will be better off not using them.

\fun{void}{gaffsg}{long s, GEN x} assigns the \kbd{long}~\kbd{s} into the
object~\kbd{x}.

\fun{void}{gaffect}{GEN x, GEN y} assigns the object \kbd{x} into the
object~\kbd{y}. Both \kbd{x} and \kbd{y} must be scalar types. Type
conversions (e.g.~from \typ{INT} to \typ{REAL} or \typ{INTMOD}) occur if
legitimate.

\fun{int}{is_universal_constant}{GEN x} returns $1$ if $x$ is a global PARI constant
you should never assign to (such as \kbd{gen\_1}), and $0$ otherwise.

\section{Conversions}

\subsec{Scalars}

\fun{double}{rtodbl}{GEN x} applied to a \typ{REAL}~\kbd{x}, converts \kbd{x}
into a \kbd{double} if possible.

\fun{GEN}{dbltor}{double x} converts the \kbd{double} \kbd{x} into a
\typ{REAL}.

\fun{long}{dblexpo}{double x} returns \kbd{expo(dbltor(x))}, but
faster and without cluttering the stack.

\fun{ulong}{dblmantissa}{double x} returns the most significant word
in the mantissa of \kbd{dbltor(x)}.

\fun{double}{gtodouble}{GEN x} if \kbd{x} is a real number (not necessarily
a~\typ{REAL}), converts \kbd{x} into a \kbd{double} if possible.

\fun{long}{gtos}{GEN x} converts the \typ{INT} \kbd{x} to a small
integer if possible, otherwise raise an exception. This function
is similar to \tet{itos}, slightly slower since it checks the type of \kbd{x}.

\fun{double}{dbllog2r}{GEN x} assuming \kbd{x} is a non-zero \typ{REAL},
returns an approximation to \kbd{log2(|x|)}.

\fun{long}{gtolong}{GEN x} if \kbd{x} is an integer (not necessarily
a~\typ{INT}), converts \kbd{x} into a \kbd{long} if possible.

\fun{GEN}{fractor}{GEN x, long l} applied to a \typ{FRAC}~\kbd{x}, converts
\kbd{x} into a \typ{REAL} of length \kbd{prec}.

\fun{GEN}{quadtofp}{GEN x, long l} applied to a \typ{QUAD}~\kbd{x}, converts
\kbd{x} into a \typ{REAL} or \typ{COMPLEX} depending on the sign of the
discriminant of~\kbd{x}, to precision \hbox{\kbd{l} \B-bit} words.
% forbid line brk at hyphen here [GN]

\fun{GEN}{cxtofp}{GEN x, long prec} converts the \typ{COMPLEX}~\kbd{x} to a
a complex whose real and imaginary parts are \typ{REAL} of length \kbd{prec}
(special case of~\kbd{gtofp}.

\fun{GEN}{cxcompotor}{GEN x, long prec} converts the
\typ{INT}, \typ{REAL} or \typ{FRAC} $x$ to a \typ{REAL} of length \kbd{prec}.
These are all the real types which may occur as components of a
\typ{COMPLEX}; special case of~\kbd{gtofp} (introduced so that the latter is
not recursive and can thus be inlined).

\fun{GEN}{gtofp}{GEN x, long prec} converts the complex number~\kbd{x}
(\typ{INT}, \typ{REAL}, \typ{FRAC}, \typ{QUAD} or \typ{COMPLEX}) to either
a \typ{REAL} or \typ{COMPLEX} whose components are \typ{REAL} of precision
\kbd{prec}; not necessarily of \emph{length} \kbd{prec}: a real $0$ may be
given as \kbd{real\_0(...)}). If the result is a \typ{COMPLEX} extra care is
taken so that its modulus really has accuracy \kbd{prec}: there is a problem
if the real part of the input is an exact $0$; indeed, converting it to
\kbd{real\_0(prec)} would be wrong if the imaginary part is tiny, since the
modulus would then become equal to $0$, as in $1.E-100 + 0.E-28 = 0.E-28$.

\fun{GEN}{gcvtop}{GEN x, GEN p, long l} converts $x$ into a \typ{PADIC}
of precision~$l$. Works componentwise on recursive objects,
e.g.~\typ{POL} or \typ{VEC}. Converting $0$ yields $O(p^l)$; converting a
non-zero number yield a result well defined modulo $p^{v_p(x) + l}$.

\fun{GEN}{cvtop}{GEN x, GEN p, long l} as \kbd{gcvtop}, assuming that $x$
is a scalar.

\fun{GEN}{cvtop2}{GEN x, GEN y} $y$ being a $p$-adic, converts the scalar $x$
to a $p$-adic of the same accuracy. Shallow function.

\fun{GEN}{cvstop2}{long s, GEN y} $y$ being a $p$-adic, converts the scalar $s$
to a $p$-adic of the same accuracy. Shallow function.

\fun{GEN}{gprec}{GEN x, long l} returns a copy of $x$ whose precision is
changed to $l$ digits. The precision change is done recursively on all
components of $x$. Digits means \emph{decimal}, $p$-adic and $X$-adic digits
for \typ{REAL}, \typ{SER}, \typ{PADIC} components, respectively.

\fun{GEN}{gprec_w}{GEN x, long l} returns a shallow copy of $x$ whose
\typ{REAL} components have their precision changed to $l$ \emph{words}. This
is often more useful than \kbd{gprec}.

\fun{GEN}{gprec_wtrunc}{GEN x, long l} returns a shallow copy of $x$ whose
\typ{REAL} components have their precision \emph{truncated} to $l$
\emph{words}. Contrary to \kbd{gprec\_w}, this function may never increase
the precision of~$x$.

\subsec{Modular objects}

\fun{GEN}{gmodulo}{GEN x, GEN y} creates the object \kbd{\key{Mod}(x,y)} on
the PARI stack, where \kbd{x} and \kbd{y} are either both \typ{INT}s, and the
result is a \typ{INTMOD}, or \kbd{x} is a scalar or a \typ{POL} and \kbd{y} a
\typ{POL}, and the result is a \typ{POLMOD}.

\fun{GEN}{gmodulgs}{GEN x, long y} same as \key{gmodulo} except \kbd{y} is a
\kbd{long}.

\fun{GEN}{gmodulsg}{long x, GEN y} same as \key{gmodulo} except \kbd{x} is a
\kbd{long}.

\fun{GEN}{gmodulss}{long x, long y} same as \key{gmodulo} except both
\kbd{x} and \kbd{y} are \kbd{long}s.

\subsec{Between polynomials and coefficient arrays}

\fun{GEN}{gtopoly}{GEN x, long v} converts or truncates the object~\kbd{x}
into a \typ{POL} with main variable number~\kbd{v}. A common application
would be the conversion of coefficient vectors (coefficients are given by
decreasing degree). E.g.~\kbd{[2,3]} goes to \kbd{2*v + 3}

\fun{GEN}{gtopolyrev}{GEN x, long v} converts or truncates the object~\kbd{x}
into a \typ{POL} with main variable number~\kbd{v}, but vectors are converted
in reverse order compared to \kbd{gtopoly} (coefficients are given by
increasing degree). E.g.~\kbd{[2,3]} goes to \kbd{3*v + 2}. In other words
the vector represents a polynomial in the basis $(1,v,v^2,v^3,\dots)$.

\fun{GEN}{normalizepol}{GEN x} applied to an unnormalized \typ{POL}~\kbd{x}
(with all coefficients correctly set except that \kbd{leading\_term(x)} might
be zero), normalizes \kbd{x} correctly in place and returns~\kbd{x}. For
internal use. Normalizing means deleting all leading \emph{exact} zeroes
(as per \kbd{isexactzero}), except if the polynomial turns out to be $0$,
in which case we try to find a coefficient $c$ which is a non-rational zero,
and return the constant polynomial $c$. (We do this so that information
about the base ring is not lost.)

\fun{GEN}{normalizepol_lg}{GEN x, long l} applies \kbd{normalizepol} to
\kbd{x}, pretending that \kbd{lg(x)} is $l$, which must be less than
or equal to \kbd{lg(x)}. If equal, the function is equivalent to
\kbd{normalizepol(x)}.

\fun{GEN}{normalizepol_approx}{GEN x, long lx} as \kbd{normalizepol\_lg},
with the difference that we just delete all leading zeroes (as per
\kbd{gequal0}). This rougher normalization is used when we have no other
choice, for instance before attempting a Euclidean division by $x$.

The following routines do \emph{not} copy coefficients on the stack (they
only move pointers around), hence are very fast but not suitable for
\kbd{gerepile} calls. Recall that an \kbd{RgV} (resp.~an \kbd{RgX}, resp.~an
\kbd{RgM}) is a \typ{VEC} or \typ{COL} (resp.~a \typ{POL}, resp.~a \typ{MAT})
with arbitrary components. Similarly, an \kbd{RgXV} is a \typ{VEC} or
\typ{COL} with \kbd{RgX} components, etc.

\fun{GEN}{RgV_to_RgX}{GEN x, long v} converts the \kbd{RgV}~\kbd{x} to a
(normalized) polynomial in variable~\kbd{v} (as \kbd{gtopolyrev}, without
copy).

\fun{GEN}{RgX_to_RgV}{GEN x, long N} converts the \typ{POL}~\kbd{x} to a
\typ{COL}~\kbd{v} with \kbd{N} components. Other types than \typ{POL} are
allowed for \kbd{x}, which is then considered as a constant polynomial.
Coefficients of \kbd{x} are listed by increasing degree, so that \kbd{y[i]}
is the coefficient of the term of degree $i-1$ in \kbd{x}.

\fun{GEN}{RgM_to_RgXV}{GEN x, long v} converts the \kbd{RgM}~\kbd{x} to a
\typ{VEC} of \kbd{RgX}, by repeated calls to \kbd{RgV\_to\_RgX}.

\fun{GEN}{RgXV_to_RgM}{GEN v, long N} converts the vector of \kbd{RgX}~\kbd{v}
to a~\typ{MAT} with \kbd{N}~rows, by repeated calls to \kbd{RgX\_to\_RgV}.

\fun{GEN}{RgM_to_RgXX}{GEN x, long v,long w} converts the \kbd{RgM}~\kbd{x} into
a \typ{POL} in variable~\kbd{v}, whose coefficients are \typ{POL}s in
variable~\kbd{w}. This is a shortcut for
\bprog
  RgV_to_RgX( RgM_to_RgXV(x, w), v );
@eprog\noindent
There are no consistency checks with respect to variable
priorities: the above is an invalid object if $\kbd{varncmp(v, w)} \geq 0$.

\fun{GEN}{RgXX_to_RgM}{GEN x, long N} converts the \typ{POL}~\kbd{x} with
\kbd{RgX} (or constant) coefficients to a matrix with \kbd{N} rows.

\fun{GEN}{RgXY_swap}{GEN P, long n, long w} converts the bivariate polynomial
$\kbd{P}(u,v)$ (a \typ{POL} with \typ{POL} coefficients) to
$P(\kbd{pol\_x[w]},u)$, assuming \kbd{n} is an upper bound for
$\deg_v(\kbd{P})$.

\fun{GEN}{RgX_to_ser}{GEN x, long l} applied to a \typ{POL}~\kbd{x}, creates
a \emph{shallow} \typ{SER} of length~$l\geq 2$ starting with~\kbd{x}.
Unless the polynomial is an exact zero, the coefficient of lowest degree
$T^d$ of the result is not an exact zero (as per \kbd{isexactzero}). The
remainder is $O(T^{d+l})$.

\fun{GEN}{RgX_to_ser_inexact}{GEN x, long l} applied to a \typ{POL}~\kbd{x},
creates a \emph{shallow} \typ{SER} of length~\kbd{l} starting with~\kbd{x}.
Unless the polynomial is zero, the coefficient of lowest degree
$T^d$ of the result is not zero (as per \kbd{gequal0}). The
remainder is $O(T^{d+l})$.

\fun{GEN}{gtoser}{GEN x, long v} converts the object~\kbd{x} into a \typ{SER}
with main variable number~\kbd{v}.

\fun{GEN}{gtocol}{GEN x} converts the object~\kbd{x} into a \typ{COL}

\fun{GEN}{gtomat}{GEN x} converts the object~\kbd{x} into a \typ{MAT}.

\fun{GEN}{gtovec}{GEN x} converts the object~\kbd{x} into a \typ{VEC}.

\fun{GEN}{gtovecsmall}{GEN x} converts the object~\kbd{x} into a
\typ{VECSMALL}.

\fun{GEN}{normalize}{GEN x} applied to an unnormalized \typ{SER}~\kbd{x}
(i.e.~type \typ{SER} with all coefficients correctly set except that \kbd{x[2]}
might be zero), normalizes \kbd{x} correctly in place. Returns~\kbd{x}.
For internal use.

\section{Constructors}

\subsec{Clean constructors}\label{se:clean}

\fun{GEN}{zeropadic}{GEN p, long n} creates a $0$ \typ{PADIC} equal to
$O(\kbd{p}^\kbd{n})$.

\fun{GEN}{zeroser}{long v, long n} creates a $0$ \typ{SER} in variable
\kbd{v} equal to $O(X^\kbd{n})$.

\fun{GEN}{scalarser}{GEN x, long v, long prec} creates a constant \typ{SER}
in variable \kbd{v} and precision \kbd{prec}, whose constant coefficient is
(a copy of) \kbd{x}, in other words $\kbd{x} + O(\kbd{v}^\kbd{prec})$.
Assumes that \kbd{x} is non-zero.

\fun{GEN}{pol_0}{long v} Returns the constant polynomial $0$ in variable $v$.

\fun{GEN}{pol_1}{long v} Returns the constant polynomial $1$ in variable $v$.

\fun{GEN}{pol_x}{long v} Returns the monomial of degree $1$ in variable $v$.

\fun{GEN}{pol_x_powers}{long N, long v} returns the powers of
\kbd{pol\_x(v)}, of degree $0$ to $N$, in a vector with $N+1$ components.

\fun{GEN}{scalarpol}{GEN x, long v} creates a constant \typ{POL} in variable
\kbd{v}, whose constant coefficient is (a copy of) \kbd{x}.

\fun{GEN}{deg1pol}{GEN a, GEN b,long v} creates the degree 1 \typ{POL}
$a + b \kbd{pol\_x}(v)$

\fun{GEN}{zeropol}{long v} is identical \kbd{pol\_0}.

\fun{GEN}{zerocol}{long n} creates a \typ{COL} with \kbd{n} components set to
\kbd{gen\_0}.

\fun{GEN}{zerovec}{long n} creates a \typ{VEC} with \kbd{n} components set to
\kbd{gen\_0}.

\fun{GEN}{col_ei}{long n, long i} creates a \typ{COL} with \kbd{n} components
set to \kbd{gen\_0}, but for the \kbd{i}-th one which is set to \kbd{gen\_1}
(\kbd{i}-th vector in the canonical basis).

\fun{GEN}{vec_ei}{long n, long i} creates a \typ{VEC} with \kbd{n} components
set to \kbd{gen\_0}, but for the \kbd{i}-th one which is set to \kbd{gen\_1}
(\kbd{i}-th vector in the canonical basis).

\fun{GEN}{Rg_col_ei}{GEN x, long n, long i} creates a \typ{COL} with \kbd{n}
components set to \kbd{gen\_0}, but for the \kbd{i}-th one which is set to
\kbd{x}.

\fun{GEN}{vecsmall_ei}{long n, long i} creates a \typ{VECSMALL} with \kbd{n}
components set to \kbd{0}, but for the \kbd{i}-th one which is set to
\kbd{1} (\kbd{i}-th vector in the canonical basis).

\fun{GEN}{scalarcol}{GEN x, long n} creates a \typ{COL} with \kbd{n}
components set to \kbd{gen\_0}, but the first one which is set to a copy
of \kbd{x}. (The name comes from \kbd{RgV\_isscalar}.)

\smallskip

\fun{GEN}{mkintmodu}{ulong x, ulong y} creates the \typ{INTMOD} \kbd{Mod(x, y)}.
The inputs must satisfy $x < y$.

\fun{GEN}{zeromat}{long m, long n} creates a \typ{MAT} with \kbd{m} x \kbd{n}
components set to \kbd{gen\_0}. Note that the result allocates a
\emph{single} column, so modifying an entry in one column modifies it in
all columns. To fully allocate a matrix initialized with zero entries,
use \kbd{zeromatcopy}.

\fun{GEN}{zeromatcopy}{long m, long n} creates a \typ{MAT} with \kbd{m} x
\kbd{n} components set to \kbd{gen\_0}.

\fun{GEN}{matid}{long n} identity matrix in dimension \kbd{n} (with
components \kbd{gen\_1} and\kbd{gen\_0}).

\fun{GEN}{scalarmat}{GEN x, long n} scalar matrix, \kbd{x} times the identity.

\fun{GEN}{scalarmat_s}{long x, long n} scalar matrix, \kbd{stoi(x)} times
the identity.

\smallskip
See also next section for analogs of the following functions:

\fun{GEN}{mkfraccopy}{GEN x, GEN y} creates the \typ{FRAC} $x/y$. Assumes that
$y > 1$ and $(x,y) = 1$.

\fun{GEN}{mkcolcopy}{GEN x} creates a 1-dimensional \typ{COL} containing
\kbd{x}.

\fun{GEN}{mkmatcopy}{GEN x} creates a 1-by-1 \typ{MAT} containing \kbd{x}.

\fun{GEN}{mkveccopy}{GEN x} creates a 1-dimensional \typ{VEC} containing
\kbd{x}.

\fun{GEN}{mkvec2copy}{GEN x, GEN y} creates a 2-dimensional \typ{VEC} equal
to \kbd{[x,y]}.

\fun{GEN}{mkvecs}{long x} creates a 1-dimensional \typ{VEC}
containing \kbd{stoi(x)}.

\fun{GEN}{mkvec2s}{long x, long y} creates a 2-dimensional \typ{VEC}
containing \kbd{[stoi(x), stoi(y)]}.

\fun{GEN}{mkvec3s}{long x, long y, long z} creates a 3-dimensional \typ{VEC}
containing \kbd{[stoi(x), stoi(y), stoi(z)]}.

\fun{GEN}{mkvecsmall}{long x} creates a 1-dimensional \typ{VECSMALL}
containing \kbd{x}.

\fun{GEN}{mkvecsmall2}{long x, long y} creates a 2-dimensional \typ{VECSMALL}
containing \kbd{[x, y]}.

\fun{GEN}{mkvecsmall3}{long x, long y, long z} creates a 3-dimensional
\typ{VECSMALL} containing \kbd{[x, y, z]}.

\fun{GEN}{mkvecsmall4}{long x, long y, long z, long t} creates a 4-dimensional
\typ{VECSMALL} containing \kbd{[x, y, z, t]}.

\fun{GEN}{mkvecsmalln}{long n, ...} returns the \typ{VECSMALL} whose $n$
coefficients (\kbd{long}) follow.

\subsec{Unclean constructors}\label{se:unclean}

Contrary to the policy of general PARI functions, the functions in this
subsection do \emph{not} copy their arguments, nor do they produce an object
a priori suitable for \tet{gerepileupto}. In particular, they are
faster than their clean equivalent (which may not exist). \emph{If} you
restrict their arguments to universal objects (e.g \kbd{gen\_0}),
then the above warning does not apply.

\fun{GEN}{mkcomplex}{GEN x, GEN y} creates the \typ{COMPLEX} $x + iy$.

\fun{GEN}{mulcxI}{GEN x} creates the \typ{COMPLEX} $ix$. The result in
general contains data pointing back to the original $x$. Use \kbd{gcopy} if
this is a problem. But in most cases, the result is to be used immediately,
before $x$ is subject to garbage collection.

\fun{GEN}{mulcxmI}{GEN x}, as \tet{mulcxI}, but returns the \typ{COMPLEX}
$-ix$.

\fun{GEN}{mkquad}{GEN n, GEN x, GEN y} creates the \typ{QUAD} $x + yw$,
where $w$ is a root of $n$, which is of the form \kbd{quadpoly(D)}.

\fun{GEN}{mkfrac}{GEN x, GEN y} creates the \typ{FRAC} $x/y$. Assumes that
$y > 1$ and $(x,y) = 1$.

\fun{GEN}{mkrfrac}{GEN x, GEN y} creates the \typ{RFRAC} $x/y$. Assumes
that $y$ is a \typ{POL}, $x$ a compatible type whose variable has lower
or same priority, with $(x,y) = 1$.

\fun{GEN}{mkcol}{GEN x} creates a 1-dimensional \typ{COL} containing \kbd{x}.

\fun{GEN}{mkcol2}{GEN x, GEN y} creates a 2-dimensional \typ{COL} equal to
\kbd{[x,y]}.

\fun{GEN}{mkintmod}{GEN x, GEN y} creates the \typ{INTMOD} \kbd{Mod(x, y)}.
The inputs must be \typ{INT}s satisfying $0 \leq x < y$.

\fun{GEN}{mkpolmod}{GEN x, GEN y} creates the \typ{POLMOD} \kbd{Mod(x, y)}.
The input must satisfy $\deg x < \deg y$ with respect to the main variable of
the \typ{POL} $y$. $x$ may be a scalar.

\fun{GEN}{mkmat}{GEN x} creates a 1-column \typ{MAT} with column $x$
(a \typ{COL}).

\fun{GEN}{mkmat2}{GEN x, GEN y} creates a 2-column \typ{MAT} with columns
$x$, $y$ (\typ{COL}s of the same length).

\fun{GEN}{mkvec}{GEN x} creates a 1-dimensional \typ{VEC} containing \kbd{x}.

\fun{GEN}{mkvec2}{GEN x, GEN y} creates a 2-dimensional \typ{VEC} equal to
\kbd{[x,y]}.

\fun{GEN}{mkvec3}{GEN x, GEN y, GEN z} creates a 3-dimensional \typ{VEC}
equal to \kbd{[x,y,z]}.

\fun{GEN}{mkvec4}{GEN x, GEN y, GEN z, GEN t} creates a 4-dimensional \typ{VEC}
equal to \kbd{[x,y,z,t]}.

\fun{GEN}{mkvec5}{GEN a1, GEN a2, GEN a3, GEN a4, GEN a5} creates the
5-dimensional \typ{VEC} equal to $[a_1,a_2,a_3,a_4,a_5]$.

\smallskip

\fun{GEN}{mkintn}{long n, ...} returns the non-negative \typ{INT} whose
development in base $2^{32}$ is given by the following $n$ words
(\kbd{unsigned long}). It is assumed that all such arguments are less than
$2^{32}$ (the actual \kbd{sizeof(long)} is irrelevant, the behavior is also
as above on $64$-bit machines).
\bprog
  mkintn(3, a2, a1, a0);
@eprog
\noindent returns $a_2 2^{64} + a_1 2^{32} + a_0$.

\fun{GEN}{mkpoln}{long n, ...} Returns the \typ{POL} whose $n$
coefficients (\kbd{GEN}) follow, in order of decreasing degree.
\bprog
  mkpoln(3, gen_1, gen_2, gen_0);
@eprog
\noindent returns the polynomial $X^2 + 2X$ (in variable $0$, use
\tet{setvarn} if you want other variable numbers). Beware that $n$ is the
number of coefficients, hence \emph{one more} than the degree.

\fun{GEN}{mkvecn}{long n, ...} returns the \typ{VEC} whose $n$
coefficients (\kbd{GEN}) follow.

\fun{GEN}{mkcoln}{long n, ...} returns the \typ{COL} whose $n$
coefficients (\kbd{GEN}) follow.

\fun{GEN}{scalarcol_shallow}{GEN x, long n} creates a \typ{COL} with \kbd{n}
components set to \kbd{gen\_0}, but the first one which is set to a shallow
copy of \kbd{x}. (The name comes from \kbd{RgV\_isscalar}.)

\fun{GEN}{scalarmat_shallow}{GEN x, long n} creates an $n\times n$
scalar matrix whose diagonal is set to shallow copies of the scalar \kbd{x}.

\fun{GEN}{diagonal_shallow}{GEN x} returns a diagonal matrix whose diagonal
is given by the vector $x$. Shallow function.

\fun{GEN}{deg1pol_shallow}{GEN a, GEN b,long v} returns the degree 1
\typ{POL} $a + b \kbd{pol\_x}(v)$

\subsec{From roots to polynomials}

\fun{GEN}{deg1_from_roots}{GEN L, long v} given a vector $L$ of scalars,
returns the vector of monic linear polynomials in variable $v$ whose roots
are the $L[i]$, i.e. the $x - L[i]$.

\fun{GEN}{roots_from_deg1}{GEN L} given a vector $L$ of monic linear
polynomials, return their roots, i.e. the $- L[i](0)$.

\fun{GEN}{roots_to_pol}{GEN L, long v} given a vector of scalars $L$,
returns the monic polynomial in variable $v$ whose roots are the $L[i]$.
Calls \tet{divide_conquer_prod}, so leaves some garbage on stack, but suitable for
\kbd{gerepileupto}.

\fun{GEN}{roots_to_pol_r1}{GEN L, long v, long r1} as \kbd{roots\_to\_pol}
assuming the first $r_1$ roots are ``real'', and the following ones are
representatives of conjugate pairs of ``complex'' roots. So if $L$ has $r_1 +
r_2$ elements, we obtain a polynomial of degree $r_1 + 2r_2$. In most
applications, the roots are indeed real and complex, but the implementation
assumes only that each ``complex'' root $z$ introduces a quadratic
factor $X^2 - \kbd{trace}(z) X + \kbd{norm}(z)$. Calls
\tet{divide_conquer_prod}.
Calls \tet{divide_conquer_prod}, so leaves some garbage on stack, but suitable for
\kbd{gerepileupto}.

\section{Integer parts}

\fun{GEN}{gfloor}{GEN x} creates the floor of~\kbd{x}, i.e.\ the (true)
integral part.

\fun{GEN}{gfrac}{GEN x} creates the fractional part of~\kbd{x}, i.e.\ \kbd{x}
minus the floor of~\kbd{x}.

\fun{GEN}{gceil}{GEN x} creates the ceiling of~\kbd{x}.

\fun{GEN}{ground}{GEN x} rounds towards~$+\infty$ the components of \kbd{x}
to the nearest integers.

\fun{GEN}{grndtoi}{GEN x, long *e} same as \kbd{ground}, but in addition sets
\kbd{*e} to the binary exponent of $x - \kbd{ground}(x)$. If this is
positive, all significant bits are lost. This kind of situation raises an
error message in \key{ground} but not in \key{grndtoi}.

\fun{GEN}{gtrunc}{GEN x} truncates~\kbd{x}. This is the false integer part
if \kbd{x} is a real number (i.e.~the unique integer closest to \kbd{x} among
those between 0 and~\kbd{x}). If \kbd{x} is a \typ{SER}, it is truncated
to a \typ{POL}; if \kbd{x} is a \typ{RFRAC}, this takes the polynomial part.

\fun{GEN}{gtrunc2n}{GEN x, long n} creates the floor of~$2^n$\kbd{x}, this is
only implemented for \typ{INT}, \typ{REAL}, \typ{FRAC} and \typ{COMPLEX} of those.

\fun{GEN}{gcvtoi}{GEN x, long *e} analogous to \key{grndtoi} for
\typ{REAL} inputs except that rounding is replaced by truncation. Also applies
componentwise for vector or matrix inputs; otherwise, sets \kbd{*e} to
\kbd{-HIGHEXPOBIT} (infinite real accuracy) and return \kbd{gtrunc(x)}.

\section{Valuation and shift}

\fun{GEN}{gshift[z]}{GEN x, long n[, GEN z]} yields the result of shifting
(the components of) \kbd{x} left by \kbd{n} (if \kbd{n} is non-negative)
or right by $-\kbd{n}$ (if \kbd{n} is negative). Applies only to \typ{INT}
and vectors/matrices of such. For other types, it is simply multiplication
by~$2^{\kbd{n}}$.

\fun{GEN}{gmul2n[z]}{GEN x, long n[, GEN z]} yields the product of \kbd{x}
and~$2^{\kbd{n}}$. This is different from \kbd{gshift} when \kbd{n} is negative
and \kbd{x} is a \typ{INT}: \key{gshift} truncates, while \key{gmul2n}
creates a fraction if necessary.

\fun{long}{ggval}{GEN x, GEN p} returns the greatest exponent~$e$ such that
$\kbd{p}^e$ divides~\kbd{x}, when this makes sense.

\fun{long}{gval}{GEN x, long v} returns the highest power of the variable
number \kbd{v} dividing the \typ{POL}~\kbd{x}.

\section{Comparison operators}

\subsec{Generic}

\fun{long}{gcmp}{GEN x, GEN y} comparison of \kbd{x} with \kbd{y} (returns
the sign ($-1$, 0 or 1) of $\kbd{x}-\kbd{y}$).

\fun{long}{lexcmp}{GEN x, GEN y} comparison of \kbd{x} with \kbd{y} for the
lexicographic ordering.

\fun{int}{gcmpX}{GEN x} return 1 (true) if \kbd{x} is a variable
(monomial of degree $1$ with \typ{INT} coefficients equal to $1$ and $0$),
and $0$ otherwise

\fun{long}{gequal}{GEN x, GEN y} returns 1 (true) if \kbd{x} is equal
to~\kbd{y}, 0~otherwise. A priori, this makes sense only if \kbd{x} and
\kbd{y} have the same type, in which case they are recursively compared
componentwise. When the types are different, a \kbd{true} result
means that \kbd{x - y} was successfully computed and that
\kbd{gequal0} found it equal to $0$. In particular
\bprog
  gequal(cgetg(1, t_VEC), gen_0)
@eprog\noindent is true, and the relation is not transitive. E.g.~an empty
\typ{COL} and an empty \typ{VEC} are not equal but are both equal to
\kbd{gen\_0}.

\fun{long}{gidentical}{GEN x, GEN y} returns 1 (true) if \kbd{x} is identical
to~\kbd{y}, 0~otherwise. In particular, the types and length of \kbd{x} and
\kbd{y} must be equal. This test is much stricter than \tet{gequal}, in
particular, \typ{REAL} with different accuracies are tested different. This
relation is transitive.

\subsec{Comparison with a small integer}

\fun{int}{isexactzero}{GEN x} returns 1 (true) if \kbd{x} is exactly equal
to~0 (including \typ{INTMOD}s like \kbd{Mod(0,2)}), and 0~(false) otherwise.
This includes recursive objects, for instance vectors, whose components are $0$.

\fun{int}{isrationalzero}{GEN x} returns 1 (true) if \kbd{x} is equal
to an integer~0 (excluding \typ{INTMOD}s like \kbd{Mod(0,2)}), and 0~(false)
otherwise. Contrary to \kbd{isintzero}, this includes recursive objects, for
instance vectors, whose components are $0$.

\fun{int}{ismpzero}{GEN x} returns 1 (true) if \kbd{x} is a \typ{INT} or
a \typ{REAL} equal to~0.

\fun{int}{isintzero}{GEN x} returns 1 (true) if \kbd{x} is a \typ{INT}
equal to~0.

\fun{int}{isint1}{GEN x} returns 1 (true) if \kbd{x} is a \typ{INT}
equal to~1.

\fun{int}{isintm1}{GEN x} returns 1 (true) if \kbd{x} is a \typ{INT}
equal to~$-1$.

\fun{int}{equali1}{GEN n}
Assuming that \kbd{x} is a \typ{INT}, return 1 (true) if \kbd{x} is equal to
$1$, and return 0~(false) otherwise.

\fun{int}{equalim1}{GEN n}
Assuming that \kbd{x} is a \typ{INT}, return 1 (true) if \kbd{x} is equal to
$-1$, and return 0~(false) otherwise.

\fun{int}{is_pm1}{GEN x}. Assuming that \kbd{x} is a
\emph{non-zero} \typ{INT}, return 1 (true) if \kbd{x} is equal to $-1$ or
$1$, and return 0~(false) otherwise.

\fun{int}{gequal0}{GEN x} returns 1 (true) if \kbd{x} is equal to~0, 0~(false)
otherwise.

\fun{int}{gequal1}{GEN x} returns 1 (true) if \kbd{x} is equal to~1, 0~(false)
otherwise.

\fun{int}{gequalm1}{GEN x} returns 1 (true) if \kbd{x} is equal to~$-1$,
0~(false) otherwise.


\fun{long}{gcmpsg}{long s, GEN x}

\fun{long}{gcmpgs}{GEN x, long s} comparison of \kbd{x} with the
\kbd{long}~\kbd{s}.

\fun{GEN}{gmaxsg}{long s, GEN x}

\fun{GEN}{gmaxgs}{GEN x, long s} returns the largest of \kbd{x} and
the \kbd{long}~\kbd{s} (converted to \kbd{GEN})

\fun{GEN}{gminsg}{long s, GEN x}

\fun{GEN}{gmings}{GEN x, long s} returns the smallest of \kbd{x} and the
\kbd{long}~\kbd{s} (converted to \kbd{GEN})

\fun{long}{gequalsg}{long s, GEN x}

\fun{long}{gequalgs}{GEN x, long s} returns 1 (true) if \kbd{x} is equal to
the \kbd{long}~\kbd{s}, 0~otherwise.

\section{Miscellaneous Boolean functions}

\fun{int}{isrationalzeroscalar}{GEN x} equivalent to, but faster than,
\bprog
  is_scalar_t(typ(x)) && isrationalzero(x)
@eprog

\fun{int}{isinexact}{GEN x} returns 1 (true) if $x$ has an inexact
component, and 0 (false) otherwise.

\fun{int}{isinexactreal}{GEN x} return 1 if $x$ has an inexact
\typ{REAL} component, and 0  otherwise.

\fun{int}{isrealappr}{GEN x, long e} applies (recursively) to complex inputs;
returns $1$ if $x$ is approximately real to the bit accuracy $e$, and 0
otherwise. This means that any \typ{COMPLEX} component must have imaginary part
$t$ satisfying $\kbd{gexpo}(t) < e$.

\fun{int}{isint}{GEN x, GEN *n} returns 0 (false) if \kbd{x} does not round
to an integer. Otherwise, returns 1 (true) and set \kbd{n} to the rounded
value.

\fun{int}{issmall}{GEN x, long *n} returns 0 (false) if \kbd{x} does not
round to a small integer (suitable for \kbd{itos}). Otherwise, returns 1
(true) and set \kbd{n} to the rounded value.

\fun{long}{iscomplex}{GEN x} returns 1 (true) if \kbd{x} is a complex number
(of component types embeddable into the reals) but is not itself real, 0~if
\kbd{x} is a real (not necessarily of type \typ{REAL}), or raises an error if
\kbd{x} is not embeddable into the complex numbers.

\subsec{Obsolete}

The following less convenient comparison functions and Boolean operators were
used by the historical GP interpreter. They are provided for backward
compatibility only and should not be used:

\fun{GEN}{gle}{GEN x, GEN y}

\fun{GEN}{glt}{GEN x, GEN y}

\fun{GEN}{gge}{GEN x, GEN y}

\fun{GEN}{ggt}{GEN x, GEN y}

\fun{GEN}{geq}{GEN x, GEN y}

\fun{GEN}{gne}{GEN x, GEN y}

\fun{GEN}{gor}{GEN x, GEN y}

\fun{GEN}{gand}{GEN x, GEN y}

\fun{GEN}{gnot}{GEN x, GEN y}

\section{Sorting}

\subsec{Basic sort}

\fun{GEN}{sort}{GEN x} sorts the vector \kbd{x} in ascending order using a
mergesort algorithm, and \kbd{gcmp} as the underlying comparison routine
(returns the sorted vector). This routine copies all components of $x$, use
\kbd{gen\_sort\_inplace} for a more memory-efficient function.

\fun{GEN}{lexsort}{GEN x}, as \kbd{sort}, using \kbd{lexcmp} instead of
\kbd{gcmp} as the underlying comparison routine.

\fun{GEN}{vecsort}{GEN x, GEN k}, as \kbd{sort}, but sorts the
vector \kbd{x} in ascending \emph{lexicographic} order, according to the
entries of the \typ{VECSMALL} \kbd{k}. For example,  if $\kbd{k} = [2,1,3]$,
sorting will be done with respect to the second component,  and when these
are  equal, with respect to the first,  and when these are equal,  with
respect to the third.

\subsec{Indirect sorting}

\fun{GEN}{indexsort}{GEN x} as \kbd{sort}, but only returns the permutation
which, applied to \kbd{x}, would sort the vector. The result is a
\typ{VECSMALL}.

\fun{GEN}{indexlexsort}{GEN x}, as \kbd{indexsort}, using \kbd{lexcmp}
instead of \kbd{gcmp} as the underlying comparison routine.

\fun{GEN}{indexvecsort}{GEN x, GEN k}, as \kbd{vecsort}, but only
returns the permutation that would sort the vector \kbd{x}.

\subsec{Generic sort and search} The following routines allow to use an
arbitrary comparison function \kbd{int (*cmp)(void* data, GEN x, GEN y)},
such that \kbd{cmp(data,x,y)} returns a negative result if $x
< y$, a positive one if $x > y$ and 0 if $x = y$. The \kbd{data} argument is
there in case your \kbd{cmp} requires additional context.

\fun{GEN}{gen_sort}{GEN x, void *data, int (*cmp)(void *,GEN,GEN)}, as
\kbd{sort}, with an explicit comparison routine.

\fun{GEN}{gen_sort_uniq}{GEN x, void *data, int (*cmp)(void *,GEN,GEN)}, as
\kbd{gen\_sort}, removing duplicate entries.

\fun{GEN}{gen_indexsort}{GEN x, void *data, int (*cmp)(void*,GEN,GEN)},
as \kbd{indexsort}.

\fun{GEN}{gen_indexsort_uniq}{GEN x, void *data, int (*cmp)(void*,GEN,GEN)},
as \kbd{indexsort}, removing duplicate entries.

\fun{void}{gen_sort_inplace}{GEN x, void *data, int (*cmp)(void*,GEN,GEN), GEN
*perm} sort \kbd{x} in place, without copying its components. If
\kbd{perm} is non-\kbd{NULL}, it is set to the permutation that would sort
the original \kbd{x}.

\fun{GEN}{gen_setminus}{GEN A, GEN B, int (*cmp)(GEN,GEN)} given two sorted
vectors $A$ and $B$, returns the vector of elements of $A$ not belonging to
$B$.

\fun{GEN}{sort_factor}{GEN y, void *data, int (*cmp)(void *,GEN,GEN)}:
assuming \kbd{y} is a factorization matrix, sorts its rows in place (no copy
is made) according to the comparison function \kbd{cmp} applied to its first
column.

\fun{GEN}{merge_factor}{GEN fx, GEN fy, void *data, int (*cmp)(void *,GEN,GEN)}
let \kbd{fx} and \kbd{fy} be factorization matrices for $X$ and $Y$
sorted with respect to the comparison function \kbd{cmp} (see
\tet{sort_factor}), returns the factorization of $X * Y$. Zero exponents in
the latter factorization are preserved, e.g. when merging the factorization
of $2$ and $1/2$, the result is $2^0$.

\fun{long}{gen_search}{GEN v, GEN y, long flag, void *data, int
(*cmp)(void*,GEN,GEN)}.\hfil\break
Let \kbd{v} be a vector sorted according to \kbd{cmp(data,a,b)}; look for an
index $i$ such that  \kbd{v[$i$]} is equal to \kbd{y}. \kbd{flag} has the
same meaning as in \kbd{setsearch}: if \kbd{flag} is 0, return $i$ if it
exists and 0 otherwise; if \kbd{flag} is non-zero, return $0$ if $i$ exists
and the index where \kbd{y} should be inserted otherwise.

\fun{long}{tablesearch}{GEN T, GEN x, int (*cmp)(GEN,GEN)} is a faster
implementation for the common case \kbd{gen\_search(T,x,0,cmp,cmp\_nodata)}.

\subsec{Further useful comparison functions}

\fun{int}{cmp_universal}{GEN x, GEN y} a somewhat arbitrary universal
comparison function, devoid of sensible mathematical meaning. It is
transitive, and returns 0 if and only if \kbd{gidentical(x,y)} is true.
Useful to sort and search vectors of arbitrary data.

\fun{int}{cmp_nodata}{void *data, GEN x, GEN y}. This function is a hack
used to pass an existing basic comparison function lacking the \kbd{data}
argument, i.e. with prototype \kbd{int (*cmp)(GEN x, GEN y)}. Instead of
\kbd{gen\_sort(x, NULL, cmp)} which may or may not work depending on how your
compiler handles typecasts between incompatible function pointers, one should
use \kbd{gen\_sort(x, (void*)cmp, cmp\_nodata)}.

Here are a few basic comparison functions, to be used with \kbd{cmp\_nodata}:

\fun{int}{ZV_cmp}{GEN x, GEN y} compare two \kbd{ZV}, which we assume have
the same length (lexicographic order).

\fun{int}{cmp_RgX}{GEN x, GEN y} compare two polynomials, which we assume
have the same main variable (lexicographic order). The coefficients are
compared using \kbd{gcmp}.

\fun{int}{cmp_prime_over_p}{GEN x, GEN y} compare two prime ideals, which
we assume divide the same prime number. The comparison is ad hoc but orders
according to increasing residue degrees.

\fun{int}{cmp_prime_ideal}{GEN x, GEN y} compare two prime ideals in the same
\var{nf}. Orders by increasing primes, breaking ties using
\kbd{cmp\_prime\_over\_p}.

Finally a more elaborate comparison function:

\fun{int}{gen_cmp_RgX}{void *data, GEN x, GEN y} compare two polynomials,
ordering first by increasing degree, then according to the coefficient
comparison function:
\bprog
  int (*cmp_coeff)(GEN,GEN) = (int(*)(GEN,GEN)) data;
@eprog

\section{Divisibility, Euclidean division}

\fun{GEN}{gdivexact}{GEN x, GEN y} returns the quotient $\kbd{x} / \kbd{y}$,
assuming $\kbd{y}$ divides $\kbd{x}$. Not stack clean if $y = 1$
(we return $x$, not a copy).

\fun{int}{gdvd}{GEN x, GEN y}  returns 1 (true) if \kbd{y} divides~\kbd{x},
0~otherwise.

\fun{GEN}{gdiventres}{GEN x, GEN y} creates a 2-component vertical
vector whose components are the true Euclidean quotient and remainder
of \kbd{x} and~\kbd{y}.

\fun{GEN}{gdivent[z]}{GEN x, GEN y[, GEN z]} yields the true Euclidean
quotient of \kbd{x} and the \typ{INT} or \typ{POL}~\kbd{y}.

\fun{GEN}{gdiventsg}{long s, GEN y[, GEN z]}, as \kbd{gdivent}
except that \kbd{x} is a \kbd{long}.

\fun{GEN}{gdiventgs[z]}{GEN x, long s[, GEN z]}, as \kbd{gdivent}
except that \kbd{y} is a \kbd{long}.

\fun{GEN}{gmod[z]}{GEN x, GEN y[, GEN z]} yields the remainder of \kbd{x}
modulo the \typ{INT} or \typ{POL}~\kbd{y}. A \typ{REAL} or \typ{FRAC} \kbd{y}
is also allowed, in which case the remainder is the unique real $r$ such that
$0 \leq r < |\kbd{y}|$ and $\kbd{y} = q\kbd{x} + r$ for some (in fact unique)
integer $q$.

\fun{GEN}{gmodsg}{long s, GEN y[, GEN z]} as \kbd{gmod}, except \kbd{x} is
a \kbd{long}.

\fun{GEN}{gmodgs}{GEN x, long s[, GEN z]} as \kbd{gmod}, except \kbd{y} is
a \kbd{long}.

\fun{GEN}{gdivmod}{GEN x, GEN y, GEN *r} If \kbd{r} is not equal to
\kbd{NULL} or \kbd{ONLY\_REM}, creates the (false) Euclidean quotient of
\kbd{x} and~\kbd{y}, and puts (the address of) the remainder into~\kbd{*r}.
If \kbd{r} is equal to \kbd{NULL}, do not create the remainder, and if
\kbd{r} is equal to \kbd{ONLY\_REM}, create and output only the remainder.
The remainder is created after the quotient and can be disposed of
individually with a \kbd{cgiv(r)}.

\fun{GEN}{poldivrem}{GEN x, GEN y, GEN *r} same as \key{gdivmod} but
specifically for \typ{POL}s~\kbd{x} and~\kbd{y}, not necessarily in the same
variable. Either of \kbd{x} and \kbd{y} may also be scalars (treated as
polynomials of degree $0$)

\fun{GEN}{gdeuc}{GEN x, GEN y} creates the Euclidean quotient of the
\typ{POL}s~\kbd{x} and~\kbd{y}. Either of \kbd{x} and \kbd{y} may also be
scalars (treated as polynomials of degree $0$)

\fun{GEN}{grem}{GEN x, GEN y} creates the Euclidean remainder of the
\typ{POL}~\kbd{x} divided by the \typ{POL}~\kbd{y}.

\fun{GEN}{gdivround}{GEN x, GEN y} if \kbd{x} and \kbd{y} are \typ{INT},
as \kbd{diviiround}. Operate componentwise if \kbd{x} is
a \typ{COL}, \typ{VEC} or \typ{MAT}. Otherwise as \key{gdivent}.

\fun{GEN}{centermod_i}{GEN x, GEN y, GEN y2}, as \kbd{centermodii},
componentwise.

\fun{GEN}{centermod}{GEN x, GEN y}, as \kbd{centermod\_i}, except that
\kbd{y2} is computed (and left on the stack for efficiency).

\fun{GEN}{ginvmod}{GEN x, GEN y} creates the inverse of \kbd{x} modulo \kbd{y}
when it exists. \kbd{y} must be of type \typ{INT} (in which case \kbd{x} is
of type \typ{INT}) or \typ{POL} (in which case \kbd{x} is either a scalar
type or a \typ{POL}).

\section{GCD, content and primitive part}

\subsec{Generic}

\fun{GEN}{resultant}{GEN x, GEN y} creates the resultant of the \typ{POL}s
\kbd{x} and~\kbd{y} computed using Sylvester's matrix (inexact inputs), a
modular algorithm (inputs in $\Q[X]$) or the subresultant algorithm, as
optimized by Lazard and Ducos. Either of \kbd{x} and \kbd{y} may also be
scalars (treated as polynomials of degree $0$)

\fun{GEN}{ggcd}{GEN x, GEN y} creates the GCD of \kbd{x} and~\kbd{y}.

\fun{GEN}{glcm}{GEN x, GEN y} creates the LCM of \kbd{x} and~\kbd{y}.

\fun{GEN}{gbezout}{GEN x,GEN y, GEN *u,GEN *v} returns the GCD of \kbd{x}
and~\kbd{y}, and puts (the addresses of) objects $u$ and~$v$ such that
$u\kbd{x}+v\kbd{y}=\gcd(\kbd{x},\kbd{y})$ into \kbd{*u} and~\kbd{*v}.

\fun{GEN}{subresext}{GEN x, GEN y, GEN *U, GEN *V} returns the GCD of \kbd{x}
and~\kbd{y}, and puts (the addresses of) objects $u$ and~$v$ such that
$u\kbd{x}+v\kbd{y}=\text{Res}(\kbd{x},\kbd{y})$ into \kbd{*U} and~\kbd{*V}.

\fun{GEN}{content}{GEN x} returns the GCD of all the components of~\kbd{x}.

\fun{GEN}{primitive_part}{GEN x, GEN *c} sets \kbd{c} to \kbd{content(x)}
and returns the primitive part \kbd{x} / \kbd{c}. A trivial content is set to
\kbd{NULL}.

\fun{GEN}{primpart}{GEN x} as above but the content is lost.
(For efficiency, the content remains on the stack.)

\subsec{Over the rationals}

\fun{long}{Q_pval}{GEN x, GEN p} valuation at the \typ{INT} \kbd{p}
of the \typ{INT} or \typ{FRAC}~\kbd{x}.

\fun{GEN}{Q_abs}{GEN x} absolute value of the \typ{INT} or
\typ{FRAC}~\kbd{x}.

\fun{GEN}{Q_gcd}{GEN x, GEN y} gcd of the \typ{INT} or \typ{FRAC}~\kbd{x}
and~\kbd{y}.
\smallskip

In the following functions, arguments belong to a $M\otimes_\Z\Q$
for some natural $\Z$-module $M$, e.g. multivariate polynomials with integer
coefficients (or vectors/matrices recursively built from such objects), and
an element of $M$ is said to be \emph{integral}.
We are interested in contents, denominators, etc. with respect to this
canonical integral structure; in particular, contents belong to $\Q$,
denominators to $\Z$. For instance the $\Q$-content of $(1/2)xy$ is $(1/2)$,
and its $\Q$-denominator is $2$, whereas \kbd{content} would return $y/2$ and
\kbd{denom}~1.

\fun{GEN}{Q_content}{GEN x} the $\Q$-content of $x$

\fun{GEN}{Q_denom}{GEN x} the $\Q$-denominator of $x$

\fun{GEN}{Q_primitive_part}{GEN x, GEN *c} sets \kbd{c} to the $\Q$-content
of \kbd{x} and returns \kbd{x / c}, which is integral.

\fun{GEN}{Q_primpart}{GEN x} as above but the content is lost. (For
efficiency, the content remains on the stack.)

\fun{GEN}{Q_remove_denom}{GEN x, GEN *ptd} sets \kbd{d} to the
$\Q$-denominator of \kbd{x} and returns \kbd{x * d}, which is integral.

\fun{GEN}{Q_div_to_int}{GEN x, GEN c} returns \kbd{x / c}, assuming $c$
is a rational number (\typ{INT} or \typ{FRAC}) and the result is integral.

\fun{GEN}{Q_mul_to_int}{GEN x, GEN c} returns \kbd{x * c}, assuming $c$
is a rational number (\typ{INT} or \typ{FRAC}) and the result is integral.

\fun{GEN}{Q_muli_to_int}{GEN x, GEN d} returns \kbd{x * c}, assuming $c$
is a \typ{INT} and the result is integral.

\fun{GEN}{mul_content}{GEN cx, GEN cy}  \kbd{cx} and \kbd{cy} are
as set by \kbd{primitive\_part}: either a \kbd{GEN} or \kbd{NULL}
representing the trivial content $1$. Returns their product (either a
\kbd{GEN} or \kbd{NULL}).

\fun{GEN}{mul_denom}{GEN dx, GEN dy} \kbd{dx} and \kbd{dy} are
as set by \kbd{Q\_remove\_denom}: either a \typ{INT} or \kbd{NULL} representing
the trivial denominator $1$. Returns their product (either a \typ{INT} or
\kbd{NULL}).

\section{Generic arithmetic operators}

\subsec{Unary operators}

\fun{GEN}{gneg[z]}{GEN x[, GEN z]} yields $-\kbd{x}$.

\fun{GEN}{gneg_i}{GEN x} shallow function yielding $-\kbd{x}$.

\fun{GEN}{gabs[z]}{GEN x[, GEN z]} yields $|\kbd{x}|$.

\fun{GEN}{gsqr}{GEN x} creates the square of~\kbd{x}.

\fun{GEN}{ginv}{GEN x} creates the inverse of~\kbd{x}.

\subsec{Binary operators}

Let ``\op'' be a binary operation among

\op=\key{add}: addition (\kbd{x + y}).

\op=\key{sub}: subtraction (\kbd{x - y}).

\op=\key{mul}: multiplication (\kbd{x * y}).

\op=\key{div}: division (\kbd{x / y}).

\noindent The names and prototypes of the functions corresponding
to \op\ are as follows:

\funno{GEN}{g\op}{GEN x, GEN y}

\funno{GEN}{g\op gs}{GEN x, long s}

\funno{GEN}{g\op sg}{long s, GEN y}

\noindent Explicitly

\fun{GEN}{gadd}{GEN x, GEN y}, \fun{GEN}{gaddgs}{GEN x, long s},
\fun{GEN}{gaddsg}{GEN s, GEN x}

\fun{GEN}{gmul}{GEN x, GEN y}, \fun{GEN}{gmulgs}{GEN x, long s},
\fun{GEN}{gmulsg}{GEN s, GEN x}

\fun{GEN}{gsub}{GEN x, GEN y}, \fun{GEN}{gsubgs}{GEN x, long s},
\fun{GEN}{gsubsg}{GEN s, GEN x}

\fun{GEN}{gdiv}{GEN x, GEN y}, \fun{GEN}{gdivgs}{GEN x, long s},
\fun{GEN}{gdivsg}{GEN s, GEN x}


\fun{GEN}{gpow}{GEN x, GEN y, long l} creates $\kbd{x}^{\kbd{y}}$. If
\kbd{y} is a \typ{INT}, return \kbd{powgi(x,y)} (the precision \kbd{l} is not
taken into account). Otherwise, the result is $\exp(\kbd{y}*\log(\kbd{x}))$
where exact arguments are converted to floats of precision~\kbd{l} in case of
need; if there is no need, for instance if $x$ is a \typ{REAL}, $l$ is
ignored. Indeed, if $x$ is a \typ{REAL}, the accuracy of $\log x$ is
determined from the accuracy of $x$, it is no problem to multiply by $y$,
even if it is an exact type, and the accuracy of the exponential is
determined, exactly as in the case of the initial $\log x$.

\fun{GEN}{gpowgs}{GEN x, long n} creates $\kbd{x}^{\kbd{n}}$ using
binary powering. To treat the special case $n = 0$, we consider
\kbd{gpowgs} as a series of \kbd{gmul}, so we follow the rule of returning
result which is as exact as possible given the input. More precisely,
we return
\item \kbd{gen\_1} if $x$ has type \typ{INT}, \typ{REAL},  \typ{FRAC}, or
\typ{PADIC}

\item \kbd{Mod(1,N)} if $x$ is a \typ{INTMOD} modulo $N$.

\item \kbd{gen\_1} for \typ{COMPLEX}, \typ{QUAD} unless one component
is a \typ{INTMOD}, in which case we return \kbd{Mod(1, N)} for a suitable
$N$ (the gcd of the moduli that appear).

\item \kbd{FF\_1}$(x)$ for a \typ{FFELT}.

\item \kbd{RgX\_get\_1}$(x)$ for a \typ{POL}.

\item \kbd{qfi\_1}$(x)$ and \kbd{qfr\_1}$(x)$ for \typ{QFI} and \typ{QFR}.

\item the identity permutation for \typ{VECSMALL}.

\item etc. Of course, the only practical use of this routine for $n = 0$ is
to obtain the multiplicative neutral element in the base ring (or to treat
marginal cases that should be special cased anyway if there is the slightest
doubt about what the result should be).

\fun{GEN}{powgi}{GEN x, GEN y} creates $\kbd{x}^{\kbd{y}}$, where \kbd{y} is a
\typ{INT}, using left-shift binary powering. The case where $y = 0$
(as all cases where $y$ is small) is handled by \kbd{gpowgs(x, 0)}.

In addition we also have the obsolete forms:

\fun{void}{gaddz}{GEN x, GEN y, GEN z}

\fun{void}{gsubz}{GEN x, GEN y, GEN z}

\fun{void}{gmulz}{GEN x, GEN y, GEN z}

\fun{void}{gdivz}{GEN x, GEN y, GEN z}

\section{Generic operators: product, powering, factorback}

\fun{GEN}{divide_conquer_prod}{GEN v, GEN (*mul)(GEN,GEN)} $v$ is a vector of
objects, which can be ``multiplied'' using the \kbd{mul} function. Return
the ``product'' of the $v[i]$ using a product tree: by convention
return \kbd{gen\_1} if $v$ is the empty vector, a copy of $v[1]$ if it has a
single entry; and otherwise apply the function recursively on the vector
(twice smaller)

\kbd{mul}$(v[1],v[2])$, \kbd{mul}$(v[3],v[4])$, \dots

\noindent Only requires that \kbd{mul} is an associative binary operator,
which need not correspond to a true multiplication. \kbd{D} is meant to encode
an arbitrary evaluation context, set it to \kbd{NULL} in simple cases where you
do not need this. Leaves some garbage on stack, but suitable for
\kbd{gerepileupto} if \kbd{mul} is.

To describe the following functions, we use the following private typedefs
to simplify the description:
\bprog
  typedef (*F1)(void *, GEN);
  typedef (*F2)(void *, GEN, GEN);
@eprog
\noindent They correspond to generic functions with one and two arguments
respectively (the \kbd{void*} argument provides some arbitrary evaluation
context).

\fun{GEN}{divide_conquer_assoc}{GEN v, void *D, F2 op}
general version of \tet{divide_conquer_prod}. Given two objects
$x,y$, assume that \kbd{op(D, $x$, $y$)} implements an associative binary
operator. If $v$ has $k$ entries, return
$$v[1]~\var{op}~v[2]~\var{op}~\ldots ~\var{op}~v[k];$$
returns \kbd{gen\_1} if $k = 0$ and a copy of $v[1]$ if $k = 1$.

\fun{GEN}{gen_pow}{GEN x, GEN n, void *D, F1 sqr, F2 mul} $n > 0$ a
\typ{INT}, returns $x^n$; \kbd{mul(D, $x$, $y$)} implements the multiplication
in the underlying monoid; \kbd{sqr} is a (presumably optimized) shortcut for
\kbd{mul(D, $x$, $x$)}.

\fun{GEN}{gen_powu}{GEN x, ulong n, void *D, F1 sqr, F2 mul} $n > 0$,
returns $x^n$. See \tet{leftright_pow}.

\fun{GEN}{leftright_pow_fold}{GEN x, GEN n, void *D, F1 sqr, F1 msqr} as
\tet{gen_pow}, \kbd{mul} being replaced by \kbd{msqr}, with \kbd{msqr(D,
$y$)} returning $xy^2$. In particular \kbd{D} must implicitly contain $x$.

\fun{GEN}{leftright_pow_u_fold}{GEN x, ulong n, void *D, F1 sqr, F1 msqr}, see
the previous \tet{leftright_pow_fold}

\fun{GEN}{gen_factorback}{GEN L, GEN e, F2 mul, F2 pow, void *D} generic form
of \tet{factorback}. The pair $[L,e]$ is of the form

\item \kbd{[fa, NULL]}, \kbd{fa} a two-column factorization matrix: expand it.

\item  \kbd{[v, NULL]}, $v$ a vector of objects: return their
product.

\item or \kbd{[v, e]},  $v$ a vector of objects, $e$ a vector of integral
exponents: return the product of the $v[i]^{e[i]}$.

\noindent \kbd{mul(D, $x$, $y$)} and \kbd{pow(D, $x$, $n$)}
return $xy$ and $x^n$ respectively.

\section{Matrix and polynomial norms} This section concerns only standard norms
of $\R$ and $\C$ vector spaces, not algebraic norms given by the determinant of
some multiplication operator. We have already seen type-specific functions like
\tet{ZM_supnorm} or \tet{RgM_fpnorml2} and limit ourselves to generic functions
assuming nothing about their \kbd{GEN} argument; these functions allow
the following scalar types: \typ{INT}, \typ{FRAC}, \typ{REAL}, \typ{COMPLEX},
\typ{QUAD} and are defined recursively (in terms of norms of their components)
for the following ``container'' types: \typ{POL}, \typ{VEC}, \typ{COL} and
\typ{MAT}. They raise an error if some other type appears in the argument.

\fun{GEN}{gnorml2}{GEN x} The norm of a scalar is the square of its complex
modulus, the norm of a recursive type is the sum of the norms of its components.
For polynomials, vectors or matrices of complex numbers one recovers the
\emph{square} of the usual $L^2$ norm. In most applications, the missing square
root computation can be skipped.

\fun{GEN}{gnorml1}{GEN x, long prec} The norm of a scalar is its complex
modulus, the norm of a recursive type is the sum of the norms of its components.
For polynomials, vectors or matrices of complex numbers one recovers the
the usual $L^1$ norm. One must include a real precision \kbd{prec} in case
the inputs include \typ{COMPLEX} or \typ{QUAD} with exact rational components:
a square root must be computed and we must choose an accuracy.

\fun{GEN}{gnorml1_fake}{GEN x} as \tet{gnorml1}, except that the norm
of a \typ{QUAD} $x + wy$ or \typ{COMPLEX} $x + Iy$ is defined as
$|x| + |y|$, where we use the ordinary real absolute value. This is still a norm
of $\R$ vector spaces, which is easier to compute than
\kbd{gnorml1} and can often be used in its place.

\fun{GEN}{gsupnorm}{GEN x, long prec} The norm of a scalar is its complex modulus,
the norm of a recursive type is the max of the norms of its components. A
precision \kbd{prec} must be included for the same reason as in \kbd{gnorml1}.

\fun{void}{gsupnorm_aux}{GEN x, GEN *m, GEN *m2} Low-level function underlying
\kbd{gsupnorm}, used as follows:
\bprog
  GEN m = NULL, m2 = NULL;
  gsupnorm_aux(x, &m, &m2);
@eprog
After the call, the sup norm of $x$ is the min of \kbd{m} and the square root
of \kbd{m2};  one or both of \kbd{m}, \kbd{m2} may be \kbd{NULL}, in
which case it must be omitted. You may initially set \kbd{m} and \kbd{m2} to
non-\kbd{NULL} values, in which case, the above procedure yields the max of
(the initial) \kbd{m}, the square root of (the initial) \kbd{m2}, and the sup
norm of $x$.

The strange interface is due to the fact that $|z|^2$ is easier to compute
than $|z|$ for a \typ{QUAD} or \typ{COMPLEX} $z$: \kbd{m2} is the max of
those $|z|^2$, and \kbd{m} is the max of the other $|z|$.

\section{Substitution and evaluation}

\fun{GEN}{gsubst}{GEN x, long v, GEN y} substitutes the object \kbd{y}
into~\kbd{x} for the variable number~\kbd{v}.

\fun{GEN}{poleval}{GEN q, GEN x} evaluates the \typ{POL} or \typ{RFRAC}
$q$ at $x$. For convenience, a \typ{VEC} or \typ{COL} is also recognized as
the \typ{POL} \kbd{gtovecrev(q)}.

\fun{GEN}{RgX_RgM_eval}{GEN q, GEN x} evaluates the \typ{POL} $q$ at the
square matrix $x$.

\fun{GEN}{RgX_RgMV_eval}{GEN f, GEN V} returns
the evaluation $\kbd{f}(\kbd{x})$, assuming that \kbd{V} was computed by
$\kbd{FpXQ\_powers}(\kbd{x}, n)$ for some $n>1$.

\fun{GEN}{RgX_RgM_eval_col}{GEN q, GEN x, long c} evaluates the \typ{POL} $q$
at the square matrix $x$ but only returns the \kbd{c}-th column of the result.

\fun{GEN}{qfeval}{GEN q, GEN x} evaluates the quadratic form
$q$ (symmetric matrix) at $x$ (column vector of compatible dimensions).

\fun{GEN}{qfevalb}{GEN q, GEN x, GEN y} evaluates the polar bilinear form
associated to the quadratic form $q$ (symmetric matrix) at $x$, $y$ (column
vectors of compatible dimensions).

\fun{GEN}{hqfeval}{GEN q, GEN x} evaluates the Hermitian form $q$
(a Hermitian complex matrix) at $x$.

\fun{GEN}{qf_apply_RgM}{GEN q, GEN M} $q$ is a symmetric $n\times n$ matrix,
$M$ an $n\times k$ matrix, return $M' q M$.

\fun{GEN}{qf_apply_ZM}{GEN q, GEN M} as above assuming that $M$ has integer
entries.

\newpage
\chapter{Miscellaneous mathematical functions}

\section{Fractions}

\fun{GEN}{absfrac}{GEN x} returns the absolute value of the \typ{FRAC} $x$.

\fun{GEN}{sqrfrac}{GEN x} returns the square of the \typ{FRAC} $x$.

\section{Complex numbers}

\fun{GEN}{imag}{GEN x} returns a copy of the imaginary part of \kbd{x}.

\fun{GEN}{real}{GEN x} returns a copy of the real part of \kbd{x}. If \kbd{x}
is a \typ{QUAD}, returns the coefficient of $1$ in the ``canonical'' integral
basis $(1,\omega)$.

The last two functions are shallow, and not suitable for \tet{gerepileupto}:

\fun{GEN}{imag_i}{GEN x} as \kbd{gimag}, returns a pointer to the imaginary
part.
\fun{GEN}{real_i}{GEN x} as \kbd{greal}, returns a pointer to the real part.

\fun{GEN}{mulreal}{GEN x, GEN} returns the real part of $xy$;
$x,y$ have type \typ{INT}, \typ{FRAC}, \typ{REAL} or \typ{COMPLEX}. See also
\kbd{RgM\_mulreal}.

\fun{GEN}{cxnorm}{GEN x} norm of the \typ{COMPLEX} $x$ (modulus squared).

\section{Quadratic numbers and binary quadratic forms}

\fun{GEN}{quad_disc}{GEN x} returns the discriminant of the \typ{QUAD} $x$.

\fun{GEN}{quadnorm}{GEN x} norm of the \typ{QUAD} $x$.

\fun{GEN}{qfb_disc}{GEN x} returns the discriminant of the \typ{QFI}
or \typ{QFR} \kbd{x}.

\fun{GEN}{qfb_disc3}{GEN x, GEN y, GEN z} returns $y^2 - 4xz$ assuming all
inputs are \typ{INT}s. Not stack-clean.

\section{Polynomial and power series}

\fun{GEN}{derivser}{GEN x} returns the derivative of the \typ{SER} \kbd{x}
with respect to its main variable.

\fun{GEN}{truecoeff}{GEN x, long n} returns \kbd{polcoeff0(x,n, -1)}, i.e.
the coefficient of the term of degree \kbd{n} in the main variable.

\fun{long}{degree}{GEN x} returns \kbd{poldegree(x, -1)}, the degree of
\kbd{x} with respect to its main variable.

\fun{GEN}{resultant}{GEN x,GEN y} resultant of \kbd{x} and \kbd{y}, with respect
to the main variable of highest priority. Uses either
the subresultant algorithm (generic case), a modular algorithm (inputs in
$\Q[X]$) or Sylvester's matrix (inexact inputs).

\fun{GEN}{resultant2}{GEN x, GEN y} resultant of \kbd{x} and \kbd{y}, with
respect to the main variable of highest priority. Computes the determinant
of Sylvester's matrix.

\fun{GEN}{resultant_all}{GEN u, GEN v, GEN *sol} returns
\kbd{resultant(x,y)}. If \kbd{sol} is not \kbd{NULL}, sets it to the last
non-zero remainder in the polynomial remainder sequence if such a sequence
was computed, and to \kbd{gen\_0} otherwise (e.g. polynomials of degree 0,
$u,v$ in $\Q[X]$).

\section{Functions to handle \typ{FFELT}}
These functions define the public interface of the \typ{FFELT} type to use in
generic functions.  However, in specific functions, it is better to use the
functions class \kbd{FpXQ} and/or \kbd{Flxq} as appropriate.

\fun{GEN}{FF_p}{GEN a} returns the characteristic of the definition field of the
\typ{FFELT} element \kbd{a}.

\fun{GEN}{FF_p_i}{GEN a} shallow version of \kbd{FF\_p}.

\fun{GEN}{FF_mod}{GEN a} returns the polynomial (with reduced \typ{INT}
coefficients) defining the finite field, in the variable used to display $a$.

\fun{GEN}{FF_to_FpXQ}{GEN a} converts the \typ{FFELT} \kbd{a} to a polynomial
$P$ with reduced \typ{INT} coefficients such that $a=P(g)$ where $g$ is the
generator of the finite field returned by \kbd{ffgen}, in the variable used to
display $g$.

\fun{GEN}{FF_to_FpXQ_i}{GEN a} shallow version of \kbd{FF\_to\_FpXQ}.

\fun{GEN}{FF_1}{GEN a} returns the unity in the definition field of the
\typ{FFELT} element \kbd{a}.

\fun{GEN}{FF_zero}{GEN a} returns the zero element of the definition field of
the \typ{FFELT} element \kbd{a}.

\fun{int}{FF_equal0}{GEN a}, \fun{int}{FF_equal1}{GEN a}, \fun{int}{FF_equalm1}{GEN
a} returns $1$ if the \typ{FFELT} \kbd{a} is equal to $0$ (resp. $1$, resp.
$-1$) else $0$.

\fun{int}{FF_equal}{GEN a, GEN b} return $1$ if the \typ{FFELT} \kbd{a} and
\kbd{b} have the same definition field and are equal, else $0$.

\fun{int}{FF_samefield}{GEN a, GEN b} return $1$ if the \typ{FFELT} \kbd{a} and
\kbd{b} have the same definition field, else $0$.

\fun{GEN}{FF_add}{GEN a, GEN b} returns $a+b$ where \kbd{a} and \kbd{b} are
\typ{FFELT} having the same definition field.

\fun{GEN}{FF_Z_add}{GEN a, GEN x} returns $a+x$, where \kbd{a} is a
\typ{FFELT}, and \kbd{x} is a \typ{INT}, the computation being
performed in the definition field of \kbd{a}.

\fun{GEN}{FF_Q_add}{GEN a, GEN x} returns $a+x$, where \kbd{a} is a
\typ{FFELT}, and \kbd{x} is a \typ{RFRAC}, the computation being
performed in the definition field of \kbd{a}.

\fun{GEN}{FF_sub}{GEN a, GEN b} returns $a-b$ where \kbd{a} and \kbd{b} are
\typ{FFELT} having the same definition field.

\fun{GEN}{FF_mul}{GEN a, GEN b} returns $a\*b$ where \kbd{a} and \kbd{b} are
\typ{FFELT} having the same definition field.

\fun{GEN}{FF_Z_mul}{GEN a, GEN b} returns $a\*x$, where \kbd{a} is a
\typ{FFELT}, and \kbd{x} is a \typ{INT}, the computation being
performed in the definition field of \kbd{a}.

\fun{GEN}{FF_div}{GEN a, GEN b} returns $a/b$ where \kbd{a} and \kbd{b} are
\typ{FFELT} having the same definition field.

\fun{GEN}{FF_neg}{GEN a} returns $-a$ where \kbd{a} is a \typ{FFELT}.

\fun{GEN}{FF_neg_i}{GEN a} shallow function returning $-a$ where \kbd{a} is a
\typ{FFELT}.

\fun{GEN}{FF_inv}{GEN a} returns $a^{-1}$ where \kbd{a} is a \typ{FFELT}.

\fun{GEN}{FF_sqr}{GEN a} returns $a^2$ where \kbd{a} is a \typ{FFELT}.

\fun{GEN}{FF_mul2n}{GEN a, long n} returns $a\*2^n$ where \kbd{a} is a \typ{FFELT}.

\fun{GEN}{FF_pow}{GEN x, GEN n} returns $a^n$ where \kbd{a} is a \typ{FFELT}
and\kbd{n} is a \typ{INT}.

\fun{GEN}{FF_Z_Z_muldiv}{GEN a, GEN x, GEN y} returns $a\*y/z$, where \kbd{a}
is a \typ{FFELT}, and \kbd{x} and \kbd{y} are \typ{INT}, the computation being
performed in the definition field of \kbd{a}.

\fun{GEN}{Z_FF_div}{GEN x, GEN a} return $x/a$ where \kbd{a} is a
\typ{FFELT}, and \kbd{x} is a \typ{INT}, the computation being
performed in the definition field of \kbd{a}.

\fun{GEN}{FF_norm}{GEN a} returns the norm of the \typ{FFELT} \kbd{a} with
respect to its definition field.

\fun{GEN}{FF_trace}{GEN a} returns the trace of the \typ{FFELT} \kbd{a} with
respect to its definition field.

\fun{GEN}{FF_conjvec}{GEN a} returns the vector of conjugates
$[a,a^p,a^{p^2},\ldots,a^{p^{n-1}}]$ where the \typ{FFELT} \kbd{a} belong to a
field with $p^n$ elements.

\fun{GEN}{FF_charpoly}{GEN a} returns the characteristic polynomial) of the
\typ{FFELT} \kbd{a} with respect to its definition field.

\fun{GEN}{FF_minpoly}{GEN a} returns the minimal polynomial of
the \typ{FFELT} \kbd{a}.

\fun{GEN}{FF_sqrt}{GEN a} returns an \typ{FFELT} $b$ such that $a=b^2$ if
it exist, where \kbd{a} is a \typ{FFELT}.

\fun{long}{FF_issquareall}{GEN x, GEN *pt} returns $1$ if \kbd{x} is a
square, and $0$ otherwise. If \kbd{x} is indeed a square, set \kbd{pt} to its
square root.

\fun{long}{FF_issquare}{GEN x} returns $1$ if \kbd{x} is a square and $0$
otherwise.

\fun{long}{FF_ispower}{GEN x, GEN K, GEN *pt} Given $K$ a positive integer,
returns $1$ if \kbd{x} is a $K$-th power, and $0$ otherwise. If \kbd{x} is
indeed a $K$-th power, set \kbd{pt} to its $K$-th root.

\fun{GEN}{FF_sqrtn}{GEN a, GEN n, GEN *zetan} returns an \kbd{n}-th root of
$\kbd{a}$ if it exist. If \kbd{zn} is non-\kbd{NULL} set it to a primitive
\kbd{n}-th root of the unity.

\fun{GEN}{FF_log}{GEN a, GEN g, GEN o} the \typ{FFELT} \kbd{g} being a
generator for the definition field of the \typ{FFELT} \kbd{a}, returns a
\typ{INT} $e$ such that $a^e=g$.  If $e$ does not exists, the result is
currently undefined. If \kbd{o} is not \kbd{NULL} it is assumed to be a
factorization of the multiplicative order of \kbd{g} (as set by
\tet{FF_primroot})

\fun{GEN}{FF_order}{GEN a, GEN o} returns the order of the \typ{FFELT} \kbd{a}.
If \kbd{o} is non-\kbd{NULL}, it is assumed that \kbd{o} is a multiple of the
order of \kbd{a}.

\fun{GEN}{FF_primroot}{GEN a, GEN *o} returns a generator of the
multiplicative group of the definition field of the \typ{FFELT} \kbd{a}.
If \kbd{o} is not \kbd{NULL}, set it to the factorization of the order
of the primitive root (to speed up \tet{FF_log}).

\fun{GEN}{FFX_factor}{GEN f, GEN a} returns the factorization of the univariate
polynomial \kbd{f} over the definition field of the \typ{FFELT} \kbd{a}. The
coefficients of \kbd{f} must be of type \typ{INT}, \typ{INTMOD} or \typ{FFELT}
and compatible with \kbd{a}.

\fun{GEN}{FFX_roots}{GEN f, GEN a} returns the roots (\typ{FFELT})
of the univariate polynomial \kbd{f} over the definition field of the
\typ{FFELT} \kbd{a}. The coefficients of \kbd{f} must be of type \typ{INT},
\typ{INTMOD} or \typ{FFELT} and compatible with \kbd{a}.

\section{Transcendental functions}

The following two functions are only useful when interacting with \kbd{gp},
to manipulate its internal default precision (expressed as a number of
decimal digits, not in words as used everywhere else):

\fun{long}{getrealprecision}{void} returns \kbd{realprecision}.

\fun{long}{setrealprecision}{long n, long *prec} sets the new
\kbd{realprecision} to $n$, which is returned. As a side effect, set
\kbd{prec} to the corresponding number of words \kbd{ndec2prec(n)}.

\subsec{Transcendental functions with \typ{REAL} arguments}

In the following routines, $x$ is assumed to be a \typ{REAL} and the result
is a \typ{REAL} (sometimes a \typ{COMPLEX} with \typ{REAL} components), with
the largest accuracy which can be deduced from the input. The naming scheme
is inconsistent here, since we sometimes use the prefix \kbd{mp} even though
\typ{INT} inputs are forbidden:

\fun{GEN}{sqrtr}{GEN x} returns the square root of $x$.

\fun{GEN}{sqrtnr}{GEN x, long n} returns the $n$-th root of $x$, assuming
$n\geq 1$ and $x > 0$. Not stack clean.

\fun{GEN}{mpcos[z]}{GEN x[, GEN z]} returns $\cos(x)$.

\fun{GEN}{mpsin[z]}{GEN x[, GEN z]} returns $\sin(x)$.

\fun{GEN}{mplog[z]}{GEN x[, GEN z]} returns $\log(x)$. We must have $x > 0$
since the result must be a \typ{REAL}. Use \kbd{glog} for the general case,
where you want such computations as $\log(-1) = I$.

\fun{GEN}{mpexp[z]}{GEN x[, GEN z]} returns $\exp(x)$.

\fun{GEN}{mpexp1}{GEN x} returns $\exp(x)-1$, but is more accurate than
\kbd{subrs(mpexp(x), 1)}, which suffers from catastrophic cancellation if
$|x|$ is very small.

\fun{GEN}{mpveceint1}{GEN C, GEN eC, long n} as \kbd{veceint1}; assumes
that $C > 0$ is a \typ{REAL} and that \kbd{eC} is \kbd{NULL} or \kbd{mpexp(C)}.

\fun{GEN}{mpeint1}{GEN x, GEN expx} returns \kbd{eint1}$(x)$, for a \typ{REAL}
$x\geq 0$, assuming that \kbd{expx} is \kbd{mpexp}$(x)$.

\fun{GEN}{szeta}{long s, long prec} returns the value of Riemann's zeta
function at the (possibly negative) integer $s\neq 1$, in relative accuracy \kbd{prec}.

\noindent Useful low-level functions which \emph{disregard} the sign of $x$:

\fun{GEN}{sqrtr_abs}{GEN x} returns $\sqrt{|x|}$ assuming $x\neq 0$.

\fun{GEN}{exp1r_abs}{GEN x} returns $\exp(|x|) - 1$, assuming $x \neq 0$.

\fun{GEN}{logr_abs}{GEN x} returns $\log(|x|)$, assuming $x \neq 0$.

\noindent A few variants on sin and cos:

\fun{void}{mpsincos}{GEN x, GEN *s, GEN *c} sets $s$ and $c$ to
$\sin(x)$ and $\cos(x)$ respectively, where $x$ is a \typ{REAL}

\fun{GEN}{exp_Ir}{GEN x} returns $\exp(ix)$, where $x$ is a \typ{REAL}.
The return type is \typ{COMPLEX} unless the imaginary part is equal to $0$
to the current accuracy (its sign is $0$).

\fun{void}{gsincos}{GEN x, GEN *s, GEN *c, long prec} general case.

\noindent A generalization of \tet{affrr_fixlg}

\fun{GEN}{affc_fixlg}{GEN x, GEN res} assume \kbd{res} was allocated using
\tet{cgetc}, and that $x$ is either a \typ{REAL} or a \typ{COMPLEX}
with \typ{REAL} components. Assign $x$ to \kbd{res}, first shortening
the components of \kbd{res} if needed (in a \kbd{gerepile}-safe way). Further
convert \kbd{res} to a \typ{REAL} if $x$ is a \typ{REAL}.

\subsec{Transcendental functions with \typ{PADIC} arguments}

\fun{GEN}{Qp_exp}{GEN x} shortcut for \kbd{gexp(x, /*ignored*/prec)}

\fun{GEN}{Qp_gamma}{GEN x} shortcut for \kbd{ggamma(x, /*ignored*/prec)}

\fun{GEN}{Qp_log}{GEN x} shortcut for \kbd{glog(x, /*ignored*/prec)}

\fun{GEN}{Qp_sqrt}{GEN x} shortcut for \kbd{gsqrt(x, /*ignored*/prec)}

\fun{GEN}{Qp_sqrtn}{GEN x, GEN n, GEN *z} shortcut for \kbd{gsqrtn(x, n, z, /*ignored*/prec)}

\subsec{Cached constants}

The cached constant is returned at its current precision, which may be larger
than \kbd{prec}. One should always use the \kbd{mp\var{xxx}} variant:
\kbd{mppi}, \kbd{mpeuler}, or \kbd{mplog2}.

\fun{GEN}{consteuler}{long prec} precomputes Euler-Mascheroni's constant
at precision \kbd{prec}.

\fun{GEN}{constpi}{long prec} precomputes $\pi$ at precision \kbd{prec}.

\fun{GEN}{constlog2}{long prec} precomputes $\log(2)$ at precision
\kbd{prec}.

\fun{void}{mpbern}{long n, long prec} precomputes the even \idx{Bernoulli}
numbers $B_0,\dots,B_{2n-2}$ as \typ{REAL}s of precision \kbd{prec}.

\fun{GEN}{bern}{long i} is a macro returning the \idx{Bernoulli} number
$B_{2i}$ at precision \kbd{prec}, assuming that \kbd{mpbern(n, prec)} was
called previously with $n > i$. The macro does not check whether
$0 \leq i < n$. If cached Bernoullis were initialized to a larger accuracy
than desired, use e.g.~\kbd{rtor(bern(i), prec)}.

The following functions use cached data if \kbd{prec} is not too large;
otherwise the newly computed data replaces the old cache.

\fun{GEN}{mppi}{long prec} returns $\pi$ at precision \kbd{prec}.

\fun{GEN}{Pi2n}{long n, long prec} returns $2^n\pi$ at precision \kbd{prec}.

\fun{GEN}{PiI2}{long n, long prec} returns the complex number $2\pi i$ at
precision \kbd{prec}.

\fun{GEN}{PiI2n}{long n, long prec} returns the complex number $2^n\pi i$ at
precision \kbd{prec}.

\fun{GEN}{mpeuler}{long prec} returns Euler-Mascheroni's constant at
precision \kbd{prec}.

\fun{GEN}{mplog2}{long prec} returns $\log 2$ at precision \kbd{prec}.



\section{Permutations }

\noindent Permutation are represented in two different ways

\item (\kbd{perm}) a \typ{VECSMALL} $p$ representing the bijection $i\mapsto
p[i]$; unless mentioned otherwise, this is the form used in the functions
below for both input and output,

\item (\kbd{cyc}) a \typ{VEC} of \typ{VECSMALL}s representing a product of
disjoint cycles.

\fun{GEN}{identity_perm}{long n} return the identity permutation on $n$
symbols.

\fun{GEN}{cyclic_perm}{long n, long d} return the cyclic permutation mapping
$i$ to $i+d$ (mod $n$) in $S_n$. Assume that $d \leq n$.

\fun{GEN}{perm_mul}{GEN s, GEN t} multiply $s$ and $t$ (composition $s\circ t$)

\fun{GEN}{perm_conj}{GEN s, GEN t} return $sts^{-1}$.

\fun{int}{perm_commute}{GEN p, GEN q} return $1$ if $p$ and $q$ commute, 0
otherwise.

\fun{GEN}{perm_inv}{GEN p} returns the inverse of $p$.

\fun{GEN}{perm_pow}{GEN p, long n} returns $p^n$

\fun{GEN}{cyc_pow_perm}{GEN p, long n} the permutation $p$ is given as
a product of disjoint cycles (\kbd{cyc}); return $p^n$ (as a \kbd{perm}).

\fun{GEN}{cyc_pow}{GEN p, long n} the permutation $p$ is given as
a product of disjoint cycles (\kbd{cyc}); return $p^n$ (as a \kbd{cyc}).

\fun{GEN}{perm_cycles}{GEN p} return the cyclic decomposition of $p$.

\fun{long}{perm_order}{GEN p} returns the order of the permutation $p$
(as the lcm of its cycle lengths).

\fun{GEN}{vecperm_orbits}{GEN p, long n} the permutation $p\in S_n$ being
given as a product of disjoint cycles, return the orbits of the subgroup
generated by $p$ on $\{1,2,\ldots,n\}$.

\section{Small groups}

The small (finite) groups facility is meant to deal with subgroups of Galois
groups obtained by \tet{galoisinit} and thus is currently limited to weakly
super-solvable groups.

A group \var{grp} of order $n$ is represented by its regular representation
(for an arbitrary ordering of its element) in $S_n$.  A subgroup of such group
is represented by the restriction of the representation to the subgroup.
A \emph{small group} can be either a group or a subgroup. Thus it is embedded
in some $S_n$, where $n$ is the multiple of the order. Such $n$ is called the
\emph{domain} of the small group. The domain of a trivial subgroup cannot be
derived from the subgroup data, so some functions require the subgroup domain
as argument.

The small group \var{grp} is represented by a \typ{VEC} with two
components:

$\var{grp}[1]$ is a generating subset $[s_1,\ldots,s_g]$ of \var{grp}
expressed as a vector of permutation of length $n$.

$\var{grp}[2]$ contains the relative orders $[o_1,\ldots,o_g]$ of
the generators $\var{grp}[1]$.

See \tet{galoisinit} for the technical details.

\fun{GEN}{checkgroup}{GEN gal, GEN *elts} checks whether \var{gal} is a
small group or a Galois group. Returns the underlying small
group and set \var{elts} to the list of elements or to \kbd{NULL} if it is not
known.

\fun{GEN}{galois_group}{GEN gal} return the underlying small group of the
Galois group \var{gal}.

\fun{GEN}{cyclicgroup}{GEN g, long s} returns the cyclic group with generator
$g$ of order $s$.

\fun{GEN}{trivialgroup}{void} returns the trivial group.

\fun{GEN}{dicyclicgroup}{GEN g1, GEN g2, long s1, long s2} returns the group
with generators \var{g1}, \var{g2} with respecting relative orders \var{s1},
\var{s2}.

\fun{GEN}{abelian_group}{GEN v} let v be a \typ{VECSMALL} seen as the SNF of
a small abelian group, return its regular representation.

\fun{long}{group_domain}{GEN grp} returns the \kbd{domain} of the
\emph{non-trivial} small group \var{grp}. Return an error if \var{grp} is
trivial.

\fun{GEN}{group_elts}{GEN grp, long n} returns the list of elements of the
small group \var{grp} of domain \var{n} as permutations.

\fun{GEN}{group_set}{GEN grp, long n} returns a \var{F2v} $b$ such that
$b[i]$ is set if and only if the small group \var{grp} of domain \var{n}
contains a permutation sending $1$ to $i$.

\fun{GEN}{groupelts_set}{GEN elts, long n}, where \var{elts} is the list of
elements of a small group of domain \var{n}, returns a \var{F2v} $b$ such that
$b[i]$ is set if and only if the small group contains a permutation sending $1$
to $i$.

\fun{long}{group_order}{GEN grp} returns the order of the small group
\var{grp} (which is the product of the relative orders).

\fun{long}{group_isabelian}{GEN grp} returns $1$ the the small group
\var{grp} is Abelian, else $0$.

\fun{GEN}{group_abelianHNF}{GEN grp, GEN elts} if \var{grp} is not Abelian,
returns \kbd{NULL}, else returns the HNF matrix of \var{grp} with respect to
the generating family $\var{grp}[1]$. If \var{elts} is no \kbd{NULL}, it must
be the list of elements of \var{grp}.

\fun{GEN}{group_abelianSNF}{GEN grp, GEN elts} if \var{grp} is not Abelian,
returns \kbd{NULL}, else returns its cyclic decomposition. If \var{elts} is no
\kbd{NULL}, it must be the list of elements of \var{grp}.

\fun{long}{group_subgroup_isnormal}{GEN G, GEN H}, $H$ being a subgroup of the
small group $G$, returns $1$ if $H$ is normal in $G$, else $0$.

\fun{long}{group_isA4S4}{GEN grp} returns $1$ if the small group
\var{grp} is isomorphic to $A_4$, $2$ if it is isomorphic to $S_4$ and
$0$ else. This is mainly to deal with the idiosyncrasy of the format.

\fun{GEN}{group_leftcoset}{GEN G, GEN g} where $G$ is a small group and $g$ a
permutation of the same domain, the the left coset $gG$ as a vector of
permutations.

\fun{GEN}{group_rightcoset}{GEN G, GEN g} where $G$ is a small group and $g$ a
permutation of the same domain, the the right coset $Gg$  as a vector of permutations.

\fun{long}{group_perm_normalize}{GEN G, GEN g} where $G$ is a small group and
$g$ a permutation of the same domain, return $1$ if $gGg^-1=G$, else $0$.

\fun{GEN}{group_quotient}{GEN G, GEN H}, where $G$ is a small group and
$H$ is a subgroup of $G$, returns the quotient map $G\rightarrow G/H$
as an abstract data structure.

\fun{GEN}{quotient_perm}{GEN C, GEN g} where $C$ is the quotient map
$G\rightarrow G/H$ for some subgroup $H$ of $G$ and $g$ an element of $G$,
return the image of $g$ by $C$ (i.e. the coset $gH$).

\fun{GEN}{quotient_group}{GEN C, GEN G} where $C$ is the quotient map
$G\rightarrow G/H$ for some \emph{normal} subgroup $H$ of $G$, return the
quotient group $G/H$ as a small group.

\fun{GEN}{quotient_subgroup_lift}{GEN C, GEN H, GEN S} where $C$ is the
quotient map $G\rightarrow G/H$ for some group $G$ normalizing $H$ and $S$ is
a subgroup of $G/H$, return the inverse image of $S$ by $C$.

\fun{GEN}{group_subgroups}{GEN grp} returns the list of subgroups of the
small group \var{grp} as a \typ{VEC}.

\fun{GEN}{subgroups_tableset}{GEN S, long n} where $S$ is a vector of subgroups
of domain $n$, returns a table which matchs the set of elements of the
subgroups against the index of the subgroups.

\fun{long}{tableset_find_index}{GEN tbl, GEN set} searchs the set \kbd{set} in
the table \kbd{tbl} and returns its associated index, or $0$ if not found.

\fun{GEN}{groupelts_abelian_group}{GEN elts} where \var{elts} is the list of
elements of an \emph{Abelian} small group, returns the corresponding
small group.

\fun{GEN}{groupelts_center}{GEN elts} where \var{elts} is the list of elements
of a small group, returns the list of elements of the center of the
group.

\fun{GEN}{group_export}{GEN grp, long format} exports a small group
to another format, see \tet{galoisexport}.

\fun{long}{group_ident}{GEN grp, GEN elts} returns the index of the small group
\var{grp} in the GAP4 Small Group library, see \tet{galoisidentify}. If
\var{elts} is no \kbd{NULL}, it must be the list of elements of \var{grp}.

\fun{long}{group_ident_trans}{GEN grp, GEN elts} returns the index of the
regular representation of the small group \var{grp} in the GAP4 Transitive
Group library, see \tet{polgalois}. If \var{elts} is no \kbd{NULL}, it must be
the list of elements of \var{grp}.

\newpage
\chapter{Standard data structures}

\section{Character strings}

\subsec{Functions returning a \kbd{char *}}

\fun{char*}{pari_strdup}{const char *s} returns a malloc'ed copy of $s$
(uses \kbd{pari\_malloc}).

\fun{char*}{pari_strndup}{const char *s, long n} returns a malloc'ed copy of
at most $n$ chars from $s$ (uses \kbd{pari\_malloc}). If $s$ is longer than
$n$, only $n$ characters are copied and a terminal null byte is added.

\fun{char*}{stack_strdup}{const char *s} returns a copy of $s$, allocated
on the PARI stack (uses \kbd{stackmalloc}).

\fun{char*}{itostr}{GEN x} writes the \typ{INT} $x$ to a \tet{stackmalloc}'ed
string.

\fun{char*}{GENtostr}{GEN x}, using the current default output format
(\kbd{GP\_DATA->fmt}, which contains the output style and the number of
significant digits to print), converts $x$ to a malloc'ed string. Simple
variant of \tet{pari_sprintf}.

\fun{char*}{GENtoTeXstr}{GEN x}, as \kbd{GENtostr}, except that
\tet{f_TEX} overrides the output format from \kbd{GP\_DATA->fmt}.

\fun{char*}{RgV_to_str}{GEN g, long flag} $g$ being a vector of \kbd{GEN}s,
returns a malloc'ed string, the concatenation of the \kbd{GENtostr} applied
to its elements, except that \typ{STR} are printed without enclosing quotes.
\kbd{flag} determines the output format: \tet{f_RAW}, \tet{f_PRETTYMAT}
or \tet{f_TEX}.

\subsec{Functions returning a \typ{STR}}

\fun{GEN}{strtoGENstr}{const char *s} returns a \typ{STR} with content $s$.

\fun{GEN}{strntoGENstr}{const char *s, long n}
returns a \typ{STR} containing the first $n$ characters of $s$.

\fun{GEN}{chartoGENstr}{char c} returns a \typ{STR} containing the character
$c$.

\fun{GEN}{GENtoGENstr}{GEN x} returns a \typ{STR} containing the printed
form of $x$ (in \tet{raw} format). This is often easier to use that
\tet{GENtostr} (which returns a malloc-ed \kbd{char*}) since there is no need
to free the string after use.

\fun{GEN}{GENtoGENstr_nospace}{GEN x} as \kbd{GENtoGENstr}, removing all
spaces from the output.

\fun{GEN}{Str}{GEN g} as \tet{RgV_to_str} with output format \tet{f_RAW},
but returns a \typ{STR}, not a malloc'ed string.

\fun{GEN}{Strtex}{GEN g} as \tet{RgV_to_str} with output format \tet{f_TEX},
but returns a \typ{STR}, not a malloc'ed string.

\fun{GEN}{Strexpand}{GEN g} as \tet{RgV_to_str} with output format \tet{f_RAW},
performing tilde and environment expansion on the result. Returns a
\typ{STR}, not a malloc'ed string.

\section{Output}

\subsec{Output contexts}

An output coutext, of type \tet{PariOUT}, is a \kbd{struct}
that models a stream and contains the following function pointers:
\bprog
void (*putch)(char);           /* fputc()-alike */
void (*puts)(const char*);     /* fputs()-alike */
void (*flush)(void);           /* fflush()-alike */
@eprog\noindent
The methods \tet{putch} and \tet{puts} are used to print a character
or a string respectively.  The method \tet{flush} is called to finalize a
messages.

The generic functions \tet{pari_putc}, \tet{pari_puts}, \tet{pari_flush} and
\tet{pari_printf} print according to a \emph{default output context}, which
should be sufficient for most purposes. Lower level functions are available,
which take an explicit output context as first argument:

\fun{void}{out_putc}{PariOUT *out, char c} essentially equivalent to
\kbd{out->putc(c)}. In addition, registers whether the last character printed
was a \kbd{\bs n}.

\fun{void}{out_puts}{PariOUT *out, const char *s} essentially equivalent to
\kbd{out->puts(s)}. In addition, registers whether the last character printed
was a \kbd{\bs n}.

\fun{void}{out_printf}{PariOUT *out, const char *fmt, ...}

\fun{void}{out_vprintf}{PariOUT *out, const char *fmt, va_list ap}

\noindent N.B. The function \kbd{out\_flush} does not exist since it would be
identical to \kbd{out->flush()}

\fun{int}{pari_last_was_newline}{void} returns a non-zero value if the last
character printed via \tet{out_putc} or \tet{out_puts} was \kbd{\bs
n}, and $0$ otherwise.

\fun{void}{pari_set_last_newline}{int last} sets the boolean value
to be returned by the function \tet{pari_last_was_newline} to \var{last}.

\subsec{Default output context} They are defined by the global variables
\tet{pariOut} and \tet{pariErr} for normal outputs and warnings/errors, and you
probably do not want to change them. If you \emph{do} change them, diverting
output in non-trivial ways, this probably means that you are rewriting
\kbd{gp}. For completeness, we document in this section what the default
output contexts do.

\misctitle{pariOut} writes output to the \kbd{FILE*} \tet{pari_outfile},
initialized to \tet{stdout}.  The low-level methods are actually the standard
\kbd{putc} / \kbd{fputs}, plus some magic to handle a log file if one is
open.

\misctitle{pariErr} prints to the \kbd{FILE*} \tet{pari_errfile}, initialized
to \tet{stderr}. The low-level methods are as above.

You can stick with the default \kbd{pariOut} output context and change PARI's
standard output, redirecting \tet{pari_outfile} to another file, using

\fun{void}{switchout}{const char *name} where \kbd{name} is a character string
giving the name of the file you want to write to; the output is
\emph{appended} at the end of the file. To close the file and revert to
outputting to \kbd{stdout}, call \kbd{switchout(NULL)}.

\subsec{PARI colors}
In this section we describe the low-level functions used to implement GP's
color scheme, associated to the \tet{colors} default. The following symbolic
names are associated to gp's output strings:

\item \tet{c_ERR} an error message

\item \tet{c_HIST} a history number (as in \kbd{\%1 = ...})

\item \tet{c_PROMPT} a prompt

\item \tet{c_INPUT} an input line (minus the prompt part)

\item \tet{c_OUTPUT} an output

\item \tet{c_HELP} a help message

\item \tet{c_TIME} a timer

\item \tet{c_NONE} everything else

\emph{If} the \tet{colors} default is set to a non-empty value, before gp
outputs a string, it first outputs an ANSI colors escape sequence ---
understood by most terminals ---, according to the \kbd{colors}
specifications. As long as this is in effect, the following strings are
rendered in color, possibly in bold or underlined.

\fun{void}{term_color}{long c} prints (as if using \tet{pari_puts}) the ANSI
color escape sequence associated to output object \kbd{c}. If \kbd{c} is
\tet{c_NONE}, revert to defaut printing style.

\fun{void}{out_term_color}{PariOUT *out, long c} as \tet{term_color},
using output context \kbd{out}.

\fun{char*}{term_get_color}{char *s, long c} returns as a character
string the ANSI color escape sequence associated to output object \kbd{c}.
If \kbd{c} is \tet{c_NONE}, the value used to revert to defaut printing
style is returned. The argument \kbd{s} is either \kbd{NULL} (string
allocated on the PARI stack), or preallocated storage (in which case, it must
be able to hold at least 16 chars, including the final \kbd{\bs 0}).

\subsec{Obsolete output functions}

These variants of \fun{void}{output}{GEN x}, which prints \kbd{x}, followed by
a newline and a buffer flush are complicated to use and less flexible
than what we saw above, or than the \tet{pari_printf} variants. They are
provided for backward compatibility and are scheduled to disappear.

\fun{void}{brute}{GEN x, char format, long dec}

\fun{void}{matbrute}{GEN x, char format, long dec}

\fun{void}{texe}{GEN x, char format, long dec}

\section{Files}

The following routines are trivial wrappers around system functions
(possibly around one of several functions depending on availability).
They are usually integrated within PARI's diagnostics system, printing
messages if \kbd{DEBUGFILES} is high enough.

\fun{int}{pari_is_dir}{const char *name} returns $1$ if \kbd{name} points to
a directory, $0$ otherwise.

\fun{int}{pari_is_file}{const char *name} returns $1$ if \kbd{name} points to
a directory, $0$ otherwise.

\fun{int}{file_is_binary}{FILE *f} returns $1$ if the file $f$ is a binary
file (in the \tet{writebin} sense), $0$ otherwise.

\fun{void}{pari_unlink}{const char *s} deletes the file named $s$. Warn
if the operation fails.

\fun{char*}{path_expand}{const char *s} perform tilde and environment expansion
on $s$. Returns a \kbd{malloc}'ed buffer.

\fun{void}{strftime_expand}{const char *s, char *buf, long max} perform
time expansion on $s$, storing the result (at most \kbd{max} chars) in
buffer \kbd{buf}. Trivial wrapper around
\bprog
  time_t t = time(NULL);
  strftime(but, max, s, localtime(&t);
@eprog

\fun{char*}{pari_get_homedir}{const char *user} expands \kbd{\til user}
constructs, returning the home directory of user \kbd{user}, or \kbd{NULL} if
it could not be determined (in particular if the operating system has no such
concept). The return value may point to static area and may be overwritten
by subsequent system calls: use immediately or \kbd{strdup} it.

\fun{int}{pari_stdin_isatty}{void} returns $1$ if our standard input
\kbd{stdin} is attached to a terminal. Trivial wrapper around \kbd{isatty}.

\subsec{pariFILE}

PARI maintains a linked list of open files, to reclaim resources
(file descriptors) on error or interrupts. The corresponding data structure
is a \kbd{pariFILE}, which is a wrapper around a standard \kbd{FILE*},
containing further the file name, its type (regular file, pipe, input or
output file, etc.). The following functions create and manipulate this
structure; they are integrated within PARI's diagnostics system, printing
messages if \kbd{DEBUGFILES} is high enough.

\fun{pariFILE*}{pari_fopen}{const char *s, const char *mode} wrapper
around \kbd{fopen(s, mode)}, return \kbd{NULL} on failure.

\fun{pariFILE*}{pari_fopen_or_fail}{const char *s, const char *mode}
simple wrapper around \kbd{fopen(s, mode)}; error on failure.

\fun{pariFILE*}{pari_fopengz}{const char *s} opens the file whose name is
$s$,  and associates a (read-only) \kbd{pariFILE} with it. If $s$ is a
compressed file (\kbd{.gz} suffix), it is uncompressed on the fly.
If $s$ cannot be opened, also try to open \kbd{$s$.gz}. Returns \kbd{NULL}
on failure.

\fun{void}{pari_fclose}{pariFILE *f} closes
the underlying file descriptor and deletes the \kbd{pariFILE} struct.

\fun{pariFILE*}{pari_safefopen}{const char *s, const char *mode}
creates a \emph{new} file $s$ (a priori for writing) with \kbd{600}
permissions. Error if the file already exists. To avoid symlink attacks,
a symbolic link exists, regardless of where it points to.

\subsec{Temporary files}

PARI has its own idea of the system temp directory derived from from an
environment variable (\kbd{\$GPTMPDIR}, else \kbd{\$TMPDIR}), or the first
writable directory among \kbd{/tmp}, \kbd{/var/tmp} and \kbd{.}.

\fun{char*}{pari_unique_dir}{const char *s} creates a ``unique directory''
and return its name built from the string $s$, the user id and process pid
(on Unix systems). This directory is itself located in

The name returned is \tet{malloc}'ed.

\fun{char*}{pari_unique_filename}{const char *s}

\section{Hashtables}
A \tet{hashtable}, or associative array, is a set of pairs $(k,v)$ of keys
and values. PARI implements general extensible hashtables for fast data
retrieval, independently of the PARI stack. A hashtable is implemented as a
table of linked lists, each list containing all entries sharing the same hash
value. The table length is a prime number, which roughly doubles as the table
overflows by gaining new entries; both the current number of entries and the
threshold before the table grows are stored in the table. Finally the table
remembers the functions used to hash the entries's keys and to test for
equality two entries hashed to the same value.

An entry, or \tet{hashentry}, contains

\item a key/value pair $(k,v)$, both of type \kbd{void*} for maximal
flexibility,

\item the hash value of the key, for the table hash function. This hash is
mapped to a table index (by reduction modulo the table length), but it
contains more information, and is used to bypass costly general equality
tests if possible,

\item a link pointer to the next entry sharing the same table cell.

\bprog
typedef struct {
  void *key, *val;
  ulong hash; /* hash(key) */
  struct hashentry *next;
} hashentry;

typedef struct {
  ulong len; /* table length */
  hashentry **table; /* the table */
  ulong nb, maxnb; /* number of entries stored and max nb before enlarging */
  ulong pindex; /* prime index */
  ulong (*hash) (void *k); /* hash function */
  int (*eq) (void *k1, void *k2); /* equality test */
} hashtable;
@eprog\noindent

\fun{hashtable*}{hash_create}{ulong size, ulong (*hash)(void*), int
(*eq)(void*,void*)}\hfil\break
creates a hashtable with enough room to contain \kbd{size} entries.
The functions \kbd{hash} and \kbd{eq} will be used to compute the hash value
of keys and test keys for equality, respectively.

\fun{void}{hash_insert}{hashtable *h, void *k, void *v} inserts $(k,v)$
in hashtable $h$. No copy is made: $k$ and $v$ themselves are stored. The
implementation does not prevent one to insert two entries with equal
keys $k$, but which of the two is affected by later commands is undefined.

\fun{hashentry*}{hash_search}{hashtable *h, void *k} look for an entry
with key $k$ in $h$. Return it if it one exists, and \kbd{NULL} if not.

\fun{hashentry*}{hash_remove}{hashtable *h, void *k} deletes an entry $(k,v)$
with key $k$ from $h$ and return it. (Return \kbd{NULL} if none was found.)
Only the linking structures are freed, memory associated to $k$ and $v$
is not reclaimed.

\fun{void}{hash_destroy}{hashtable *h} deletes the hashtable, by removing all
entries.

Some interesting hash functions are available:

\fun{ulong}{hash_str}{const char *s}

\fun{ulong}{hash_str2}{const char *s} is the historical PARI string hashing
function and seems to be generally inferior to \kbd{hash\_str}.

\fun{ulong}{hash_GEN}{GEN x}

\section{Dynamic arrays}

A \teb{dynamic array} is a generic way to manage stacks of data that need
to grow dynamically. It allocates memory using \kbd{pari\_malloc}, and is
independent of the PARI stack; it even works before the \kbd{pari\_init} call.

\subsec{Initialization}

To create a stack of objects of type \kbd{foo}, we proceed as follows:
\bprog
foo *t_foo;
pari_stack s_foo;
stack_init(&s_foo, sizeof(*t_foo), (void**)t_foo);
@eprog\noindent Think of \kbd{s\_foo} as the controlling interface, and
\kbd{t\_foo} as the (dynamic) array tied to it. The value of \kbd{t\_foo}
may be changed as you add more elements.

\subsec{Adding elements}
The following function pushes an element on the stack.
\bprog
/* access globals t_foo and s_foo */
void push_foo(foo x)
{
  long n = stack_new(&s_foo);
  t_foo[n] = x;
}
@eprog

\subsec{Accessing elements}

Elements are accessed naturally through the \kbd{t\_foo} pointer.
For example this function swaps two elements:
\bprog
void swapfoo(long a, long b)
{
  foo x;
  if (a > s_foo.n || b > s_foo.n) pari_err(bugparier,"swapfoo");
  x        = t_foo[a];
  t_foo[a] = t_foo[b];
  t_foo[b] = x;
}
@eprog

\subsec{Stack of stacks}
Changing the address of \kbd{t\_foo} is not supported in general,
however changing both the address of \kbd{t\_foo} and \kbd{s\_foo}
is supported as long as the offset \kbd{\&t\_foo-\&s\_foo} do not change.
This allow to create stacks of stacks as follow:

\bprog
struct foo_s
{
  foo t_foo;
  pari_stack s_foo;
} tt_foo;
pari_stack st_foo;
stack_init(&st_foo, sizeof(*tt_foo), (void**)&tt_foo);
long new_stack(void)
{
  long n = stack_new(&st_foo);
  struct foo_s *st = tt_foo+n;
  stack_init(&st->s_foo, sizeof(*st->t_foo), (void**)&st->t_foo);
  return n;
}
@eprog
When a reallocation of \kbd{tt\_foo} occurs, the offset between the components
\kbd{.t\_foo} and \kbd{.s\_foo} does not change.

\subsec{Public interface}
Let \kbd{s} be a \kbd{pari\_stack} and \kbd{data} the data linked to it. The
following public fields are defined:

\item \kbd{s.alloc} is the number of elements allocated for \kbd{data}.

\item \kbd{s.n} is the number of elements in the stack and \kbd{data[s.n-1]} is
the topmost element of the stack.  \kbd{s.n} can be changed as long as
$0\leq\kbd{s.n}\leq\kbd{s.alloc}$ holds.

\fun{void}{stack_init}{pari_stack *s, size_t size, void **data} links
\kbd{*s} to the data pointer \kbd{*data}, where \kbd{size} is the size of
data element. The pointer \kbd{*data} is set to \kbd{NULL}, \kbd{s->n} and
\kbd{s->alloc} are set to $0$: the array is empty.

\fun{void}{stack_alloc}{pari_stack *s, long nb} makes room for \kbd{nb} more
elements, i.e.~makes sure that $\kbd{s.alloc}\geq\kbd{s.n} + \kbd{nb}$, possibly
reallocating \kbd{data}.

\fun{long}{stack_new}{pari_stack *s} increases \kbd{s.n} by one unit,
possibly reallocating \kbd{data}, and returns $\kbd{s.n}-1$.

\misctitle{Caveat} The following construction is incorrect because
\kbd{stack\_new} can change the value of \kbd{t\_foo}:
\bprog
t_foo[ stack_new(&s_foo) ] = x;
@eprog

\fun{void}{stack_delete}{pari_stack *s} frees \kbd{data} and resets the stack
to the state immediately following \kbd{stack\_init} (\kbd{s->n} and
\kbd{s->alloc} are set to $0$).

\fun{void *}{stack_pushp}{pari_stack *s, void *u} This function assumes that
\kbd{*data} is of pointer type. Pushes the element \kbd{u} on the stack \kbd{s}.

\fun{void **}{stack_base}{pari_stack *s} returns the address of \kbd{data},
typecast to a \kbd{void **}.

\section{Vectors and Matrices}

\subsec{Access and extract}
See~\secref{se:clean} and~\secref{se:unclean} for various useful constructors.
Coefficients are accessed and set using \tet{gel}, \tet{gcoeff},
see~\secref{se:accessors}. There are many internal functions to extract or
manipulate subvectors or submatrices but, like the accessors above, none of
them are suitable for \tet{gerepileupto}. Worse, there are no type
verification, nor bound checking, so use at your own risk.

\fun{GEN}{shallowcopy}{GEN x} returns a \kbd{GEN} whose components are the
components of $x$ (no copy is made). The result may now be used to compute in
place without destroying $x$. This is essentially equivalent to
\bprog
  GEN y = cgetg(lg(x), typ(x));
  for (i = 1; i < lg(x); i++) y[i] = x[i];
  return y;
@eprog\noindent
except that \typ{MAT} is treated specially since shallow copies of all columns
are made. The function also works for non-recursive types, but is useless
in that case since it makes a deep copy. If $x$ is known to be a \typ{MAT}, you
may call \tet{RgM_shallowcopy} directly; if $x$ is known not to be a \typ{MAT},
you may call \tet{leafcopy} directly.

\fun{GEN}{RgM_shallowcopy}{GEN x} returns \kbd{shallowcopy(x)}, where $x$
is a \typ{MAT}.

\fun{GEN}{shallowtrans}{GEN x} returns the transpose of $x$, \emph{without}
copying its components, i.~e.,~it returns a \kbd{GEN} whose components are
(physically) the components of $x$. This is the internal function underlying
\tet{gtrans}.

\fun{GEN}{shallowconcat}{GEN x, GEN y} concatenate $x$ and $y$, \emph{without}
copying components, i.~e.,~it returns a \kbd{GEN} whose components are
(physically) the components of $x$ and $y$.

\fun{GEN}{shallowconcat1}{GEN x}
$x$ must be \typ{VEC} or \typ{LIST}, concatenate
its elements from left to right. Shallow version of \kbd{concat1}.

\fun{GEN}{shallowextract}{GEN x, GEN y} extract components
of the vector or matrix $x$ according to the selection parameter $y$.
This is the shallow analog of \kbd{extract0(x, y, NULL)}, see \tet{vecextract}.
\kbdsidx{extract0}

\fun{GEN}{RgM_minor}{GEN A, long i, long j} given a square \typ{MAT} A,
return the matrix with $i$-th row and $j$-th column removed.

\fun{GEN}{vconcat}{GEN A, GEN B} concatenate vertically the two \typ{MAT} $A$
and $B$ of compatible dimensions. A \kbd{NULL} pointer is accepted for an
empty matrix. See \tet{shallowconcat}.

\fun{GEN}{row}{GEN A, long i} return $A[i,]$, the $i$-th row of the \typ{MAT}
$A$.

\fun{GEN}{row_i}{GEN A, long i, long j1, long j2} return part of the $i$-th
row of \typ{MAT}~$A$: $A[i,j_1]$, $A[i,j_1+1]\dots,A[i,j_2]$. Assume $j_1
\leq j_2$.

\fun{GEN}{rowcopy}{GEN A, long i} return the row $A[i,]$ of
the~\typ{MAT}~$A$. This function is memory clean and suitable for
\kbd{gerepileupto}. See \kbd{row} for the shallow equivalent.

\fun{GEN}{rowslice}{GEN A, long i1, long i2} return the \typ{MAT}
formed by the $i_1$-th through $i_2$-th rows of \typ{MAT} $A$. Assume $i_1
\leq i_2$.

\fun{GEN}{rowpermute}{GEN A, GEN p}, $p$ being a \typ{VECSMALL}
representing a list $[p_1,\dots,p_n]$ of rows of \typ{MAT} $A$, returns the
matrix whose rows are $A[p_1,],\dots, A[p_n,]$.

\fun{GEN}{rowslicepermute}{GEN A, GEN p, long x1, long x2}, short for
\bprog
  rowslice(rowpermute(A,p), x1, x2)
@eprog\noindent
(more efficient).

\fun{GEN}{vecslice}{GEN A, long j1, long j2}, return $A[j_1], \dots,
A[j_2]$. If $A$ is a \typ{MAT}, these correspond to \emph{columns} of $A$.
The object returned has the same type as $A$ (\typ{VEC}, \typ{COL} or
\typ{MAT}). Assume $j_1 \leq j_2$.

\fun{GEN}{vecsplice}{GEN A, long j} return $A$ with $j$-th entry removed
(\typ{VEC}, \typ{COL}) or $j$-th column removed (\typ{MAT}).

\fun{GEN}{vecreverse}{GEN A}. Returns a \kbd{GEN} which has the same
type as $A$ (\typ{VEC}, \typ{COL} or \typ{MAT}), and whose components
are the $A[n],\dots,A[1]$. If $A$ is a \typ{MAT}, these are the
\emph{columns} of $A$.

\fun{GEN}{vecpermute}{GEN A, GEN p} $p$ is a \typ{VECSMALL} representing
a list $[p_1,\dots,p_n]$ of indices. Returns a \kbd{GEN} which has the same
type as $A$ (\typ{VEC}, \typ{COL} or \typ{MAT}), and whose components
are $A[p_1],\dots,A[p_n]$. If $A$ is a \typ{MAT}, these are the
\emph{columns} of $A$.

\fun{GEN}{vecslicepermute}{GEN A, GEN p, long y1, long y2} short for
\bprog
  vecslice(vecpermute(A,p), y1, y2)
@eprog\noindent
(more efficient).

\subsec{Componentwise operations}

The following convenience routines automate trivial loops of the form
\bprog
  for (i = 1; i < lg(a); i++) gel(v,i) = f(gel(a,i), gel(b,i))
@eprog\noindent
for suitable $f$:

\fun{GEN}{vecinv}{GEN a}. Given a vector $a$,
returns the vector whose $i$-th component is \kbd{ginv}$(a[i])$.

\fun{GEN}{vecmul}{GEN a, GEN b}. Given $a$ and $b$ two vectors of the same
length, returns the vector whose $i$-th component is \kbd{gmul}$(a[i], b[i])$.

\fun{GEN}{vecdiv}{GEN a, GEN b}. Given $a$ and $b$ two vectors of the same
length, returns the vector whose $i$-th component is \kbd{gdiv}$(a[i], b[i])$.

\fun{GEN}{vecpow}{GEN a, GEN n}. Given $n$ a \typ{INT}, returns
the vector whose $i$-th component is $a[i]^n$.

\fun{GEN}{vecmodii}{GEN a, GEN b}. Assuming $a$ and $b$ are two \kbd{ZV}
of the same length, returns the vector whose $i$-th component
is \kbd{modii}$(a[i], b[i])$.

Note that \kbd{vecadd} or \kbd{vecsub} do not exist since \kbd{gadd}
and \kbd{gsub} have the expected behavior. On the other hand,
\kbd{ginv} does not accept vector types, hence \kbd{vecinv}.

\subsec{Low-level vectors and columns functions}

These functions handle \typ{VEC} as an abstract container type of
\kbd{GEN}s. No specific meaning is attached to the content. They accept both
\typ{VEC} and \typ{COL} as input, but \kbd{col} functions always return
\typ{COL} and \kbd{vec} functions always return \typ{VEC}.

\misctitle{Note} All the functions below are shallow.

\fun{GEN}{const_col}{long n, GEN x} returns a \typ{COL} of \kbd{n} components
equal to \kbd{x}.

\fun{GEN}{const_vec}{long n, GEN x} returns a \typ{VEC} of \kbd{n} components
equal to \kbd{x}.

\fun{int}{vec_isconst}{GEN v} Returns 1 if all the components of \kbd{v} are
equal, else returns 0.

\fun{void}{vec_setconst}{GEN v, GEN x} $v$ a pre-existing vector. Set all its
components to $x$.

\fun{int}{vec_is1to1}{GEN v}  Returns 1 if the components of \kbd{v} are
pair-wise distinct, i.e. if $i\mapsto v[i]$ is a 1-to-1 mapping, else returns
0.

\fun{GEN}{vec_shorten}{GEN v, long n} shortens the vector \kbd{v} to \kbd{n}
components.

\fun{GEN}{vec_lengthen}{GEN v, long n} lengthens the vector \kbd{v}
to \kbd{n} components. The extra components are not initialized.

\section{Vectors of small integers}

\subsec{\typ{VECSMALL}}

These functions handle \typ{VECSMALL} as an abstract container type
of small signed integers. No specific meaning is attached to the content.

\fun{GEN}{const_vecsmall}{long n, long c} returns a \typ{VECSMALL}
of \kbd{n} components equal to \kbd{c}.

\fun{GEN}{vec_to_vecsmall}{GEN z} identical to \kbd{ZV\_to\_zv(z)}.

\fun{GEN}{vecsmall_to_vec}{GEN z} identical to \kbd{zv\_to\_ZV(z)}.

\fun{GEN}{vecsmall_to_col}{GEN z} identical to \kbd{zv\_to\_ZC(z)}.

\fun{GEN}{vecsmall_copy}{GEN x} makes a copy of \kbd{x} on the stack.

\fun{GEN}{vecsmall_shorten}{GEN v, long n} shortens the \typ{VECSMALL} \kbd{v}
to \kbd{n} components.

\fun{GEN}{vecsmall_lengthen}{GEN v, long n} lengthens the \typ{VECSMALL}
\kbd{v} to \kbd{n} components. The extra components are not initialized.

\fun{GEN}{vecsmall_indexsort}{GEN x} performs an indirect sort of the
components of the \typ{VECSMALL} \kbd{x} and return a permutation stored in a
\typ{VECSMALL}.

\fun{void}{vecsmall_sort}{GEN v} sorts the \typ{VECSMALL} \kbd{v} in place.

\fun{long}{vecsmall_max}{GEN v} returns the maximum of the elements of
\typ{VECSMALL} \kbd{v}, assumed non-empty.

\fun{long}{vecsmall_min}{GEN v} returns the minimum of the elements of
\typ{VECSMALL} \kbd{v}, assumed non-empty.

\fun{long}{vecsmall_isin}{GEN v, long x} returns the first index $i$
such that \kbd{v[$i$]} is equal to \kbd{x}. Naive search in linear time, does
not assume that \kbd{v} is sorted.

\fun{GEN}{vecsmall_uniq}{GEN v} given a \typ{VECSMALL} \kbd{v}, return
the vector of unique occurrences.

\fun{GEN}{vecsmall_uniq_sorted}{GEN v} same as \kbd{vecsmall\_uniq}, but assumes
 \kbd{v} sorted.

\fun{long}{vecsmall_duplicate}{GEN v} given a \typ{VECSMALL} \kbd{v}, return
$0$ if there is no duplicates, or the index of the first duplicate
(\kbd{vecsmall\_duplicate([1,1])} returns $2$).

\fun{long}{vecsmall_duplicate_sorted}{GEN v} same as
\kbd{vecsmall\_duplicate}, but assume \kbd{v} sorted.

\fun{int}{vecsmall_lexcmp}{GEN x, GEN y} compares two \typ{VECSMALL} lexically.

\fun{int}{vecsmall_prefixcmp}{GEN x, GEN y} truncate the longest \typ{VECSMALL}
to the length of the shortest and compares them lexicographically.

\fun{GEN}{vecsmall_prepend}{GEN V, long s} prepend \kbd{s} to the \typ{VECSMALL} \kbd{V}.

\fun{GEN}{vecsmall_append}{GEN V, long s} append \kbd{s} to the \typ{VECSMALL} \kbd{V}.

\fun{GEN}{vecsmall_concat}{GEN u, GEN v} concat the \typ{VECSMALL} \kbd{u} and \kbd{v}.

\fun{long}{vecsmall_coincidence}{GEN u, GEN v} returns the numbers of indices where \kbd{u} and \kbd{v} agree.

\fun{long}{vecsmall_pack}{GEN v, long base, long mod} handles the
\typ{VECSMALL} \kbd{v} as the digit of a number in base \kbd{base} and return
this number modulo \kbd{mod}. This can be used as an hash function.

\subsec{Vectors of \typ{VECSMALL}}
These functions manipulate vectors of \typ{VECSMALL} (vecvecsmall).

\fun{GEN}{vecvecsmall_sort}{GEN x} sorts lexicographically the components of
the vector \kbd{x}.

\fun{GEN}{vecvecsmall_indexsort}{GEN x} performs an indirect lexicographic sorting of the components of the vector \kbd{x} and return a permutation stored in a \typ{VECSMALL}.

\fun{long}{vecvecsmall_search}{GEN x, GEN y, long flag} \kbd{x} being a sorted
vecvecsmall and \kbd{y} a \typ{VECSMALL}, search \kbd{y} inside \kbd{x}. \kbd{fla} has the same meaning as for \kbd{setsearch}.


\newpage
\chapter{Functions related to the GP interpreter}

\section{Handling closures}

\subsec{Functions to evaluate \typ{CLOSURE}}

\fun{void}{closure_disassemble}{GEN C} print the \typ{CLOSURE} \kbd{C} in
GP assembly format.

\fun{GEN}{closure_callgenall}{GEN C, long n, ...} evaluate the \typ{CLOSURE}
\kbd{C} with the \kbd{n} arguments (of type \kbd{GEN}) following \kbd{n} in
the function call. Assumes \kbd{C} has arity $\geq \kbd{n}$.

\fun{GEN}{closure_callgenvec}{GEN C, GEN args} evaluate the \typ{CLOSURE}
\kbd{C} with the arguments supplied in the vector \kbd{args}. Assumes \kbd{C}
has arity $\geq \kbd{lg(args)-1}$.

\fun{GEN}{closure_callgen1}{GEN C, GEN x} evaluate the \typ{CLOSURE}
\kbd{C} with argument \kbd{x}. Assumes \kbd{C} has arity $\geq 1$.

\fun{GEN}{closure_callgen2}{GEN C, GEN x, GEN y} evaluate the \typ{CLOSURE}
\kbd{C} with argument \kbd{x}, \kbd{y}. Assumes \kbd{C} has arity $\geq 2$.

\fun{void}{closure_callvoid1}{GEN C, GEN x} evaluate the \typ{CLOSURE}
\kbd{C} with argument \kbd{x} and discard the result. Assumes \kbd{C}
has arity $\geq 1$.

The following technical functions are used to evaluate \emph{inline}
closures and closures of arity 0.

The control flow statements (break, next and return) will cause the
evaluation of the closure to be interrupted; this is called below a
\emph{flow change}. When that occurs, the functions below generally
 return \kbd{NULL}. The caller can then adopt three positions:

\item raises an exception (\kbd{closure\_evalnobrk}).

\item passes through (by returning NULL itself).

\item handles the flow change.

\fun{GEN}{closure_evalgen}{GEN code} evaluates a closure and returns the result,
or \kbd{NULL} if a flow change occurred.

\fun{GEN}{closure_evalnobrk}{GEN code} as \kbd{closure\_evalgen} but raise
an exception if a flow change occurs. Meant for iterators where
interrupting the closure is meaningless, e.g.~\kbd{intnum} or \kbd{sumnum}.

\fun{void}{closure_evalvoid}{GEN code} evaluates a closure whose return
value is ignored. The caller has to deal with eventual flow changes by
calling \kbd{loop\_break}.

The remaining functions below are for exceptional situations:

\fun{GEN}{closure_evalres}{GEN code} evaluates a closure and returns the result.
The difference with \kbd{closure\_evalgen} being that, if the flow end by a
\kbd{return} statement, the result will be the returned value instead of
\kbd{NULL}. Used by the main GP loop.

\fun{GEN}{closure_evalbrk}{GEN code, long *status} as \kbd{closure\_evalres}
but set \kbd{status} to a non-zero value if a flow change occurred. This
variant is not stack clean. Used by the break loop.

\fun{GEN}{closure_trapgen}{long numerr, GEN code} evaluates closure, while
trapping error \kbd{numerr}. Return \kbd{(GEN)1L} if error trapped, and the
result otherwise, or \kbd{NULL} if a flow change occurred. Used by trap.


\subsec{Functions to handle control flow changes}

\fun{long}{loop_break}{void} processes an eventual flow changes inside an iterator. If this function return $1$, the iterator should stop.

\subsec{Functions to deal with lexical local variables}\label{se:pushlex}

Function using the prototype code \kbd{`V'} need to manually create and delete a
lexical variable for each code \kbd{`V'}, which will be given a number $-1, -2,
\ldots$.

\fun{void}{push_lex}{GEN a, GEN code} creates a new lexical variable whose
initial value is $a$ on the top of the stack. This variable get the number
$-1$, and the number of the other variables is decreased by one unit. When
the first variable of a closure is created, the argument \kbd{code} must be the
closure that references this lexical variable. The argument \kbd{code} must be
\kbd{NULL} for all subsequent variables (if any).  (The closure contains the
debugging data for the variable).

\fun{void}{pop_lex}{long n} deletes the $n$ topmost lexical variables,
increasing the number of other variables by $n$. The argument $n$ must
match the number of variables allocated through \kbd{push\_lex}.

\fun{GEN}{get_lex}{long vn} get the value of the variable with number \kbd{vn}.

\fun{void}{set_lex}{long vn, GEN x} set the value of the variable with number
\kbd{vn}.

\subsec{Functions returning new closures}

\fun{GEN}{closure_deriv}{GEN code} returns a closure corresponding to the
numerical derivative of the closure \kbd{code}.

\fun{GEN}{snm_closure}{entree *ep, GEN data}
Let \kbd{data} be a vector of length $m$, \kbd{ep} be an \kbd{entree} pointing
to a C function $f$ of arity $n+m$, returns a \typ{CLOSURE} object $g$ of arity
$n$ such that $g(x_1,\ldots,x_n)=f(x_1,\ldots,x_n,gel(data,1),...,gel(data,m))$.
If \kbd{data} is \kbd{NULL}, then $m=0$ is assumed.  This function has a low
overhead since it does not copy \kbd{data}.

\fun{GEN}{strtofunction}{char *str} returns a closure corresponding to the
built-in or install'ed function named \kbd{str}.

\fun{GEN}{strtoclosure}{char *str, long n, ...} returns a closure corresponding to the
built-in or install'ed function named \kbd{str} with the $n$ last parameters set to
the $n$ \kbd{GEN}s following $n$, see \tet{snm_closure}. This function
has an higher overhead since it copies the parameters and does more input validation.

In the example code below, \kbd{agm1} is set to the function \kbd{x->agm(x,1)} and
\kbd{res} is set to \kbd{agm(2,1)}.

\bprog
  GEN agm1 = strtoclosure("agm",1, gen_1);
  GEN res = closure_callgen1(agm1, gen_2);
@eprog

\subsec{Functions used by the gp debugger (break loop)}
\fun{long}{closure_context}{long s} restores the compilation context
starting at frame \kbd{s+1}, and returns the index of the topmost frame.
This allow to compile expressions in the topmost lexical scope.

\fun{void}{closure_err}{void} prints a backtrace of the last $20$ stack frames.

\subsec{Standard wrappers for iterators}
Two families of standard wrappers are provided to interface iterators like \kbd{intnum}
or \kbd{sumnum} with GP.

\subsubsec{Standard wrappers for inline closures}
Theses wrappers are used to implement GP functions taking
inline closures as input. The object \kbd{(GEN)E} must be an inline closure which
is evaluated with the lexical variable number $-1$ set to $x$.

\fun{GEN}{gp_eval}{void *E, GEN x} is used for the prototype code \kbd{`E'}.

\fun{long}{gp_evalvoid}{void *E, GEN x} is used for the prototype code \kbd{`I'}.
The resulting value is discarded.  Return a non-zero value if a control-flow
instruction request the iterator to terminate immediatly.

\subsubsec{Standard wrappers for true closures}
Theses wrappers are used to implement GP functions taking
true closures as input.

\fun{GEN}{gp_call}{void *E, GEN x} evaluates the closure \kbd{(GEN)E} on $x$.

\fun{long}{gp_callbool}{void *E, GEN x} evaluates the closure \kbd{(GEN)E} on $x$,
returns \kbd{1} if its result is non-zero, and \kbd{0} otherwise.

\fun{long}{gp_callvoid}{void *E, GEN x} evaluates the closure \kbd{(GEN)E} on $x$,
discarding the result. Return a non-zero value if a control-flow
instruction request the iterator to terminate immediatly.

\section{Defaults}

\fun{int}{pari_is_default}{const char *s} return $1$ if $s$ is the name
of a default, $0$ otherwise.

\fun{GEN}{setdefault}{const char *s, const char *v, long flag} is the
low-level function underlying \kbd{default0}. If $s$ is \kbd{NULL}, call all
default setting functions with string argument \kbd{NULL} and flag
\tet{d_ACKNOWLEDGE}. Otherwise, check whether $s$ corresponds to a default
and call the corresponding default setting function with arguments $v$ and
\fl.

We shall describe these functions below: if $v$ is \kbd{NULL}, we only look
at the default value (and possibly print or return it, depending on
\kbd{flag}); otherwise the value of the default to $v$, possibly after some
translation work. The flag is one of

\item \tet{d_INITRC} called while reading the \kbd{gprc} : print and return
\kbd{gnil}, possibly defer until \kbd{gp} actually starts.

\item \tet{d_RETURN} return the current value, as a \typ{INT} if possible, as
a \typ{STR} otherwise.

\item \tet{d_ACKNOWLEDGE} print the current value, return \kbd{gnil}.

\item \tet{d_SILENT} print nothing, return \kbd{gnil}.

\noindent Low-level functions called by \kbd{setdefault}:

\fun{GEN}{sd_TeXstyle}{const char *v, long flag}

\fun{GEN}{sd_colors}{const char *v, long flag}

\fun{GEN}{sd_compatible}{const char *v, long flag}

\fun{GEN}{sd_datadir}{const char *v, long flag}

\fun{GEN}{sd_debug}{const char *v, long flag}

\fun{GEN}{sd_debugfiles}{const char *v, long flag}

\fun{GEN}{sd_debugmem}{const char *v, long flag}

\fun{GEN}{sd_factor_add_primes}{const char *v, long flag}

\fun{GEN}{sd_factor_proven}{const char *v, long flag}

\fun{GEN}{sd_format}{const char *v, long flag}

\fun{GEN}{sd_histsize}{const char *v, long flag}

\fun{GEN}{sd_log}{const char *v, long flag}

\fun{GEN}{sd_logfile}{const char *v, long flag}

\fun{GEN}{sd_new_galois_format}{const char *v, long flag}

\fun{GEN}{sd_output}{const char *v, long flag}

\fun{GEN}{sd_parisize}{const char *v, long flag}

\fun{GEN}{sd_path}{const char *v, long flag}

\fun{GEN}{sd_prettyprinter}{const char *v, long flag}

\fun{GEN}{sd_primelimit}{const char *v, long flag}

\fun{GEN}{sd_realprecision}{const char *v, long flag}

\fun{GEN}{sd_recover}{const char *v, long flag}

\fun{GEN}{sd_secure}{const char *v, long flag}

\fun{GEN}{sd_seriesprecision}{const char *v, long flag}

\fun{GEN}{sd_simplify}{const char *v, long flag}

\fun{GEN}{sd_strictmatch}{const char *v, long flag}

\noindent Generic functions used to implement defaults: most of the above
routines are implemented in terms of the following generic ones. In all
routines below

\item \kbd{v} and \kbd{flag} are the arguments passed to \kbd{default} :
\kbd{v} is a new value (or the empty string: no change), and \kbd{flag} is one
of \tet{d_INITRC}, \tet{d_RETURN}, etc.

\item \kbd{s} is the name of the default being changed, used to display error
messages or acknowledgements.

\fun{GEN}{sd_toggle}{const char *v, long flag, const char *s, int *ptn}

\item if \kbd{v} is neither \kbd{"0"} nor \kbd{"1"}, an error is raised using
\tet{pari_err}.

\item \kbd{ptn} points to the current numerical value of the toggle (1 or 0),
and is set to the new value (when \kbd{v} is non-empty).

For instance, here is how the timer default is implemented internally:
\bprog
GEN
sd_timer(const char *v, long flag)
{ return sd_toggle(v,flag,"timer", &(GP_DATA->chrono)); }
@eprog

The exact behavior and return value depends on \kbd{flag}:

\item \tet{d_RETURN}: returns the new toggle value, as a \kbd{GEN}.

\item \tet{d_ACKNOWLEDGE}: prints a message indicating the new toggle value
and return \kbd{gnil}.

\item other cases: print nothing and return \kbd{gnil}.


\fun{GEN}{sd_ulong}{const char *v, long flag, const char *s, ulong *ptn,
ulong Min, ulong Max, const char **msg}\hbadness 10000

\item \kbd{ptn} points to the current numerical value of the toggle, and is set
to the new value (when \kbd{v} is non-empty).

\item \kbd{Min} and \kbd{Max} point to the minimum and maximum values allowed
for the default.

\item \kbd{v} must translate to an integer in the allowed ranger, a suffix
among
\kbd{k}/\kbd{K} ($\times 10^3$),
\kbd{m}/\kbd{M} ($\times 10^6$),
or
\kbd{g}/\kbd{G} ($\times 10^9$) is allowed, but no arithmetic expression.

\item \kbd{msg} is a \kbd[NULL]-terminated array of messages or \kbd{NULL}
(ignored). If \kbd{msg} is not \kbd{NULL}, \kbd{msg}$[i]$ contains
a message associated to the value $i$ of the default. The last entry in the
\kbd{msg} array is used as a message associated to all subsequent ones.

The exact behavior and return value depends on \kbd{flag}:

\item \tet{d_RETURN}: returns the new toggle value, as a \kbd{GEN}.

\item \tet{d_ACKNOWLEDGE}: prints a message indicating the new value,
possibly a message associated to it via the \kbd{msg} argument, and return
\kbd{gnil}.

\item other cases: print nothing and return \kbd{gnil}.

\fun{GEN}{sd_string}{const char *v, long flag, const char *s, char **pstr}
\item \kbd{v} is subjet to environment expansion, then time expansion.

\item \kbd{pstr} points to the current string value, and is set to the new
value (when \kbd{v} is non-empty).
