User’s Guide

to

PARI / GP

C. Batut, K. Belabas, D. Bernardi, H. Cohen, M. Olivier

Laboratoire A2X, U.M.R. 9936 du C.N.R.S.

Université Bordeaux I, 351 Cours de la Libération

33405 TALENCE Cedex, FRANCE

e-mail: pari@math.u-bordeaux.fr

Home Page:

http://www.parigp-home.de/

Primary ftp site:

ftp://megrez.math.u-bordeaux.fr/pub/pari/

last updated 5 November 2000

for version 2.1.2

Copyright © 2000 The PARI Group

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions, or translations, of this manual under the conditions for verbatim copying, provided also that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

PARI/GP is Copyright © 2000 The PARI Group

PARI/GP is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY WHATSOEVER.

Table of Contents

Chapter 1: Overview of the PARI system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.2@x The PARI types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.3@x Operations and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Chapter 2: Specific Use of the GP Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.1@x Defaults and output formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.2@x Simple metacommands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.3@x Input formats for the PARI types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.4@x GP operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

2.5@x The general GP input line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

2.6@x The GP/PARI programming language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.7@x Interfacing GP with other languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

2.8@x The preferences file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.2@x The PARI types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.3@x Operations and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Chapter 2: Specific Use of the GP Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.1@x Defaults and output formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.2@x Simple metacommands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.3@x Input formats for the PARI types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.4@x GP operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

2.5@x The general GP input line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

2.6@x The GP/PARI programming language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.7@x Interfacing GP with other languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

2.8@x The preferences file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Chapter 1:

Overview of the PARI system

1.1 Introduction.

The PARI system is a package which is capable of doing formal computations on recursive types at high speed; it is primarily aimed at number theorists, but can be used by anybody whose primary need is speed.

Although quite an amount of symbolic manipulation is possible in PARI, this system does very badly compared to much more sophisticated systems like Axiom, Macsyma, Maple, Mathematica or Reduce on such manipulations (e.g. multivariate polynomials, formal integration, etc... ). On the other hand, the three main advantages of the system are its speed (which can be between 5 and 100 times better on many computations), the possibility of using directly data types which are familiar to mathematicians, and its extensive algebraic number theory module which has no equivalent in the above-mentioned systems.

It is possible to use PARI in two different ways:

1) as a library, which can be called from an upper-level language application (for instance written in C, C++, Pascal or Fortran);

2) as a sophisticated programmable calculator, named GP, which contains most of the control instructions of a standard language like C.

The use of GP is explained in chapters 2 and 3, and the programming in library mode is explained in chapters 3, 4 and 5. In the present Chapter 1, we give an overview of the system.

Important note: A tutorial for GP is provided in the standard distribution (tutorial.dvi) and you should read this first (at least the beginning of it, you can skip the specialized topics you’re not interested in). You can then start over and read the more boring stuff which lies ahead. But you should do that eventually, at the very least the various Chapter headings. You can have a quick idea of what is available by looking at the GP reference card (refcard.dvi or refcard.ps). In case of need, you can then refer to the complete function description in Chapter 3.

How to get the latest version?

This package can be obtained by anonymous ftp from quite a number of sites (ask archie or your favourite Web search engine for the site nearest to you). But, if you want the very latest version (including development versions), you should use the anonymous ftp address

ftp://megrez.math.u-bordeaux.fr/pub/pari

where you will find all the different ports and possibly some binaries. A lot of version information, mailing list archives, and various tips can be found on PARI’s (fledgling) home page:

http://www.parigp-home.de/

Implementation notes: (You can skip this section and switch to Section 1.2 if you’re not interested in hardware technicalities. You won’t miss anything that would be mentioned here.)

The PARI package contains essentially three versions. The first one is a specific implementation for 680x0 based
computers which contains a kernel (for the elementary arithmetic operations on multiprecise integers and real
numbers, and binary/decimal conversion routines) entirely written in MC68020 assembly language
(around 6000 lines), the rest being at present entirely written in ANSI C with a C++-compatible
syntax. The system runs on SUN-3/xx, Sony News, NeXT cubes and on 680x0 based Macs with x__>__2. It
should be very easy to port on any other 680x0 based machine like for instance the Apollo Domain
workstations.

Note that the assembly language source code uses the SUN syntax, which for some strange reason differs from the Motorola standard used by most other 680x0 machines in the world. In the Mac distribution, we have included a program which automatically converts from the SUN syntax into the standard one, at least for the needed PARI assembly file. On the Unix distribution, we have included other versions of the assembly file, using different syntaxes. This version is not really maintained anymore since we lack the hardware to update/test it.

The second version is a version where most of the kernel routines are written in C, but the time-critical parts are written in a few hundred lines of assembler at most. At present there exist three versions for the Sparc architecture: one for Sparc version 7 (e.g. Sparcstation 1, 1+, IPC, IPX or 2), one for Sparc version 8 with supersparc processors (e.g. Sparcstation 10 and 20) and one for Sparc version 8 with microsparc I or II processors (e.g. Sparcclassic or Sparcstation 4 and 5). No specific version is written for the Ultrasparc since it can use the microsparc II version. In addition, versions exist for the HP-PA architecture, for the PowerPC architecture (only for the 601), for the Intel family starting at the 386 (under Linux, OS/2, MSDOS, or Windows), and finally for the DEC Alpha 64-bit processors.

Finally, a third version is written entirely in C, and should be portable without much trouble to any 32 or 64-bit computer having no real memory constraints. It is about 2 times slower than versions with a small assembly kernel. This version has been tested for example on MIPS based DECstations 3100 and 5000 and SGI computers.

In addition to Unix workstations and Macs, PARI has been ported to a considerable number of smaller and larger machines, for example the VAX, 68000-based machines like the Atari, Mac Classic or Amiga 500, 68020 machines such as the Amiga 2500 or 3000, and even to MS-DOS 386 or better machines, using the EMX port of the GNU C compiler and DOS-extender.

1.2 The PARI types.

The crucial word in PARI is recursiveness: most of the types it knows about are recursive. For example, the basic
type Complex exists (actually called t_COMPLEX). However, the components (i.e. the real and imaginary part) of
such a “complex number” can be of any type. The only sensible ones are integers (we are then in Z[i]), rational
numbers (Q[i]), real numbers (R[i] = C), or even elements of Z/nZ ((Z/nZ)[i] when this makes sense), or p-adic
numbers when p 3 mod 4 (Q_{p}[i]).

This feature must of course not be used too rashly: for example you are in principle allowed to create objects which are “complex numbers of complex numbers”, but don’t expect PARI to make sensible use of such objects: you will mainly get nonsense.

On the other hand, one thing which is allowed is to have components of different, but compatible, types. For example, taking again complex numbers, the real part could be of type integer, and the imaginary part of type rational.

By compatible, we mean types which can be freely mixed in operations like + or ×. For example if the real part is of type real, the imaginary part cannot be of type integermod (integers modulo a given number n).

Let us now describe the types. As explained above, they are built recursively from basic types which are as follows. We use the letter T to designate any type; the symbolic names correspond to the internal representations of the types.

type t_INT | Z | Integers (with arbitrary precision) |

type t_REAL | R | Real numbers (with arbitrary precision) |

type t_INTMOD | Z/nZ | Integermods (integers modulo n) |

type t_FRAC | Q | Rational numbers (in irreducible form) |

type t_FRACN | Q | Rational numbers (not necessarily in irreducible form) |

type t_COMPLEX | T[i] | Complex numbers |

type t_PADIC | Q_{p} | p-adic numbers |

type t_QUAD | Q[w] | Quadratic Numbers (where [Z[w] : Z] = 2) |

type t_POLMOD | T[X]/P(X)T[X] | Polmods (polynomials modulo P) |

type t_POL | T[X] | Polynomials |

type t_SER | T((X)) | Power series (finite Laurent series) |

type t_RFRAC | T(X) | Rational functions (in irreducible form) |

type t_RFRACN | T(X) | Rational functions (not necessarily in irreducible form) |

type t_VEC | T^n | Row (i.e. horizontal) vectors |

type t_COL | T^n | Column (i.e. vertical) vectors |

type t_MAT | M_{m,n}(T) | Matrices |

type t_LIST | T^n | Lists |

type t_STR | Character strings |

and where the types T in recursive types can be different in each component.

In addition, there exist types t_QFR and t_QFI for binary quadratic forms of respectively positive and negative discriminants, which can be used in specific operations, but which may disappear in future versions.

Every PARI object (called GEN in the sequel) belongs to one of these basic types. Let us have a closer look.

1.2.1 Integers and reals: they are of arbitrary and varying length (each number carrying in its internal representation its own length or precision) with the following mild restrictions (given for 32-bit machines, the restrictions for 64-bit machines being so weak as to be considered inexistent): integers must be in absolute value less than 2^268435454 (i.e. roughly 80807123 digits). The precision of real numbers is also at most 80807123 significant decimal digits, and the binary exponent must be in absolute value less than 2^23 = 8388608.

Note that PARI has been optimized so that it works as fast as possible on numbers with at most a few thousand decimal digits. In particular, not too much effort has been put into fancy multiplication techniques (only the Karatsuba multiplication is implemented). Hence, although it is possible to use PARI to do computations with 10^7 decimal digits, much better programs can be written for such huge numbers.

Integers and real numbers are completely non-recursive types and are sometimes called the leaves.

1.2.2 Integermods, rational numbers (irreducible or not), p-adic numbers, polmods, and rational functions: these are recursive, but in a restricted way.

For integermods or polmods, there are two components: the modulus, which must be of type integer (resp. polynomial), and the representative number (resp. polynomial).

For rational numbers or rational functions, there are also only two components: the numerator and the denominator, which must both be of type integer (resp. polynomial).

Finally, p-adic numbers have three components: the prime p, the “modulus” p^k, and an approximation to the
p-adic number. Here Z_{p} is considered as lim _{-}Z/p^kZ, and Q_{p} as its field of fractions. Like real numbers, the
codewords contain an exponent (giving essentially the p-adic valuation of the number) and also the information
on the precision of the number (which is in fact redundant with p^k, but is included for the sake of
efficiency).

1.2.3 Complex numbers and quadratic numbers: quadratic numbers are numbers of the form a + bw, where w is such that [Z[w] : Z] = 2, and more precisely w = /2 when d 0 mod 4, and w = (1 + )/2 when d 1 mod 4, where d is the discriminant of a quadratic order. Complex numbers correspond to the very important special case w = .

Complex and quadratic numbers are partially recursive: the two components a and b can be of type integer,
real, rational, integermod or p-adic, and can be mixed, subject to the limitations mentioned above. For example,
a + bi with a and b p-adic is in Q_{p}[i], but this is equal to Q_{p} when p 1 mod 4, hence we must exclude these p when
one explicitly uses a complex p-adic type.

1.2.4 Polynomials, power series, vectors, matrices and lists: they are completely recursive: their components can be of any type, and types can be mixed (however beware when doing operations). Note in particular that a polynomial in two variables is simply a polynomial with polynomial coefficients.

Note that in the present version 2.1.2 of PARI, there is a bug in the handling of power series of power series (i.e. power series in several variables). However power series of polynomials (which are power series in several variables of a special type) are OK. The reason for this bug is known, but it is difficult to correct because the mathematical problem itself contains some amount of imprecision.

1.2.5 Strings: These contain objects just as they would be printed by the GP calculator.

1.2.6 Notes:

1.2.6.1 Exact and imprecise objects: we have already said that integers and reals are called the leaves because they are ultimately at the end of every branch of a tree representing a PARI object. Another important notion is that of an exact object: by definition, numbers of basic type real, p-adic or power series are imprecise, and we will say that a PARI object having one of these imprecise types anywhere in its tree is not exact. All other PARI objects will be called exact. This is a very important notion since no numerical analysis is involved when dealing with exact objects.

1.2.6.2 Scalar types: the first nine basic types, from t_INT to t_POLMOD, will be called scalar types because they essentially occur as coefficients of other more complicated objects. Note that type t_POLMOD is used to define algebraic extensions of a base ring, and as such is a scalar type.

1.2.6.3 What is zero? This is a crucial question in all computer systems. The answer we give in PARI is the following. For exact types, all zeros are equivalent and are exact, and thus are usually represented as an integer zero. The problem becomes non-trivial for imprecise types. For p-adics the answer is as follows: every p-adic number (including 0) has an exponent e and a “mantissa” (a purist would say a “significand”) u which is a p-adic unit, except when the number is zero (in which case u is zero), the significand having a certain “precision” k (i.e. being defined modulo p^k). Then this p-adic zero is understood to be equal to O(p^e), i.e. there are infinitely many distinct p-adic zeros. The number k is thus irrelevant.

For power series the situation is similar, with p replaced by X, i.e. a power series zero will be O(X^e), the number k (here the length of the power series) being also irrelevant.

For real numbers, the precision k is also irrelevant, and a real zero will in fact be O(2^e) where e is now usually a negative binary exponent. This of course will be printed as usual for a real number (0.0000 in f format or 0.Exx in e format) and not with a O() symbol as with p-adics or power series. With respect to the natural ordering on the reals we make the following convention: whatever its exponent a real zero is smaller than any positive number, and any two real zeroes are equal.

1.3 Operations and functions.

1.3.1 The PARI philosophy. The basic philosophy which governs PARI is that operations and functions should, firstly, give as exact a result as possible, and secondly, be permitted if they make any kind of sense.

More specifically, if you do an operation (not a transcendental one) between exact objects, you will get an exact object. For example, dividing 1 by 3 does not give 0.33333 as you might expect, but simply the rational number (1/3). If you really want the result in type real, evaluate 1./3 or add 0. to (1/3).

The result of operations between imprecise objects will be as precise as possible. Consider for example one of the most difficult cases, that is the addition of two real numbers x and y. The accuracy of the result is a priori unpredictable; it depends on the precisions of x and y, on their sizes (i.e. their exponents), and also on the size of x + y. PARI works out automatically the right precision for the result, even when it is working in calculator mode GP where there is a default precision.

In particular, this means that if an operation involves objects of different accuracies, some digits will be disregarded by PARI. It is a common source of errors to forget, for instance, that a real number is given as r + 2^e where r is a rational approximation, e a binary exponent and is a nondescript real number less than 1 in absolute value*. Hence, any number less than 2^e may be treated as an exact zero:

? 0.E-28 + 1.E-100

%1 = 0.E-28

? 0.E100 + 1

%2 = 0.E100

As an exercise, if a = 2^(-100), why do a + 0. and a * 1. differ ?

The second part of the PARI philosophy is that PARI operations are in general quite permissive. For instance taking the exponential of a vector should not make sense. However, it frequently happens that a computation comes out with a result which is a vector with many components, and one wants to get the exponential of each one. This could easily be done either under GP or in library mode, but in fact PARI assumes that this is exactly what you want to do when you take the exponential of a vector, so no work is necessary. Most transcendental functions work in the same way (see Chapter 3 for details).

An ambiguity would arise with square matrices. PARI always considers that you want to do componentwise function evaluation, hence to get for example the exponential of a square matrix you would need to use a function with a different name, matexp for instance. In the present version 2.1.2, this is not yet implemented. See however the program in Appendix C, which is a first attempt for this particular function.

The available operations and functions in PARI are described in detail in Chapter 3. Here is a brief summary:

1.3.2 Standard operations.

Of course, the four standard operators +, -, *, / exist. It should once more be emphasized that division is, as far as possible, an exact operation: 4 divided by 3 gives (4/3). In addition to this, operations on integers or polynomials, like \ (Euclidean division), % (Euclidean remainder) exist (and for integers, \/ computes the quotient such that the remainder has smallest possible absolute value). There is also the exponentiation operator ^, when the exponent is of type integer. Otherwise, it is considered as a transcendental function. Finally, the logical operators ! (not prefix operator), && (and operator), || (or operator) exist, giving as results 1 (true) or 0 (false). Note that & and | are also accepted as synonyms respectively for && and ||. However, there is no bitwise and or or.

1.3.3 Conversions and similar functions.

Many conversion functions are available to convert between different types. For example floor, ceiling, rounding, truncation, etc... . Other simple functions are included like real and imaginary part, conjugation, norm, absolute value, changing precision or creating an integermod or a polmod.

1.3.4 Transcendental functions.

They usually operate on any object in C, and some also on p-adics. The list is everexpanding and of course contains all the elementary functions, plus already a number of others. Recall that by extension, PARI usually allows a transcendental function to operate componentwise on vectors or matrices.

1.3.5 Arithmetic functions.

Apart from a few like the factorial function or the Fibonacci numbers, these are functions which explicitly use the prime factor decomposition of integers. The standard functions are included. In the present version 2.1.2, a primitive, but useful version of Lenstra’s Elliptic Curve Method (ECM) has been implemented.

There is now a very large package which enables the number theorist to work with ease in algebraic number fields. All the usual operations on elements, ideals, prime ideals, etc... are available.

More sophisticated functions are also implemented, like solving Thue equations, finding integral bases and discriminants of number fields, computing class groups and fundamental units, computing in relative number field extensions (including explicit class field theory), and also many functions dealing with elliptic curves over Q or over local fields.

1.3.6 Other functions.

Quite a number of other functions dealing with polynomials (e.g. finding complex or p-adic roots, factoring, etc), power series (e.g. substitution, reversion), linear algebra (e.g. determinant, characteristic polynomial, linear systems), and different kinds of recursions are also included. In addition, standard numerical analysis routines like Romberg integration (open or closed, on a finite or infinite interval), real root finding (when the root is bracketed), polynomial interpolation, infinite series evaluation, and plotting are included. See the last sections of Chapter 3 for details.

Chapter 2:

Specific Use of the GP Calculator

Originally, GP was designed as a debugging tool for the PARI system library, and hence not much thought had been given to making it user-friendly. The situation has now changed somewhat, and GP is very useful as a stand-alone tool. The operations and functions available in PARI and GP will be described in the next chapter. In the present one, we describe the specific use of the GP programmable calculator.

For starting the calculator, the general commandline syntax is:

gp [-s stacksize] [-p primelimit]

where items within brackets are optional*. These correspond to some internal parameters of GP, or defaults. See Section 2.1.1 below for a list and explanation of all defaults, there are many more than just those two. These defaults can be changed by adding parameters to the input line as above, or interactively during a GP session or in a preferences file (also known as gprc).

UNIX: Some new features were developed on UNIX platforms, and depend heavily on the operating system in use. It is possible that some of these will be ported to other operating systems (BeOS, MacOS, DOS, OS/2, Windows, etc.) in future versions (most of them should be easy tasks for anybody acquainted with those). As for now, most of them were not. So, whenever a specific feature of the UNIX version is discussed in a paragraph, a UNIX sign sticks out in the left margin, like here. Just skip these if you’re stranded on a different operating system: the core GP functions (i.e. at least everything which is even faintly mathematical in nature) will still be available to you. It may also be possible (and then definitely advisable) to install Linux or FreeBSD on your machine.

Note (added in version 2.0.12): Most UNIX goodies are now available for DOS, OS/2 and Windows, thanks to the EMX/RSX runtime package (install excluded under DOS, since DLLs are not supported by the OS). For Windows 95/98 and NT, you can also use the Cygwin compatibility library to run GP almost as if running a genuine Unix system. Note that a native Linux binary will be much faster than one using any of these compatibility packages (see the MACHINES benchmark file, included in the distribution).

EMACS: If you have GNU Emacs, you can work in a special Emacs shell (see Section ??), which is started by typing M-x gp (where as usual M is the Meta key) if you accept the default stack, prime and buffer sizes, or C-u M-x gp which will ask you for the name of the gp executable, the stack size, the prime limit and the buffer size. Specific features of this Emacs shell will be indicated by an EMACS sign.

If a preferences file (or gprc, to be discussed in Section 2.8) can be found, GP will then read it and execute the commands it contains. This provides an easy way to customize GP without having to delve into the code to hardwire it to your likings.

A copyright message then appears which includes the version number. Please note this number, so as to be sure to have the most recent version if you wish to have updates of PARI. The present manual is written for version 2.1.2, and has undergone major changes since the 1.39.xx versions.

After the copyright, the computer works for a few seconds (it is in fact computing and storing a table of primes), writes the top-level help information, some initial defaults, and then waits after printing its prompt (initially: ?).

Note that at any point the user can type Ctrl-C (that is press simultaneously the Control and C keys): the current computation will be interrupted and control given back to the user at the GP prompt.

The top-level help information tells you that (as in many systems) to get help, you should type a ?. When you
do this and hit return, a menu appears, describing the eleven main categories of available functions and what to do
to get more detailed help. If you now type ?n with 1 __<__ n __<__ 11, you will get the list of commands corresponding to
category n and simultaneously to Section 3.n of this manual.

If you type ?functionname where functionname is the name of a PARI function, you will get a short explanation of this function.

UNIX: If extended help (see Section 2.2.4) is available on your system, you can double or triple the ? sign to get much more: respectively the complete description of the function (e.g. ?? sqrt), or a list of GP functions relevant to your query (e.g. ??? "elliptic curve" or ??? "quadratic field").

If GP was compiled with the right options (see Appendix A), a line editor will be available to correct the command line, get automatic completions, and so on. See Section ?? for a short summary of available commands. This might not be available for all architectures.

Whether extended on-line help and line editing are available or not is indicated in the GP banner, between the version number and the copyright message.

If you type ?\ you will get a short description of the metacommands (keyboard shortcuts).

Finally, typing ?. will return the list of available (pre-defined) member functions. These are functions attached to specific kind of objects, used to retrieve easily some information from complicated structures (you can define your own but they won’t be shown here). We will soon describe these commands in more detail.

As a general rule, under GP, commands starting with \ or with some other symbols like ? or #, are not computing commands, but are metacommands which allow the user to exchange information with GP. The available metacommands can be divided into default setting commands (explained below) and simple commands (or keyboard shortcuts, to be dealt with in Section 2.2.1).

2.1 Defaults and output formats.

There are many internal variables in GP, defining how the system will behave in certain situations, unless a specific override has been given. Most of them are a matter of basic customization (colors, prompt) and will be set once and for all in your preferences file (see Section 2.8), but some of them are useful interactively (set timer on, increase precision, etc.).

The function used to manipulate these values is called default, which is described in Section ??. The basic syntax is

default(def , value),

which sets the default def to value. In interactive use, most of these can be abbreviated using historic GP metacommands (mostly, starting with \), which we shall describe in the next section.

Here we will only describe the available defaults and how they are used. Just be aware that typing default by itself will list all of them, as well as their current values (see \d). Just after the default name, we give between parentheses the initial value when GP starts (assuming you did not tamper with it using command-line switches or a gprc).

Note: the suffixes k or M can be appended to a value which is a numeric argument, with the effect of multiplying it by 10^3 or 10^6 respectively. Case is not taken into account there, so for instance 30k and 30K both stand for 30000. This is mostly useful to modify or set the defaults primelimit or stacksize which typically involve a lot of trailing zeroes.

(somewhat technical) Note: As we will see in Section ??, the second argument to default will be subject to string context expansion, which means you can use run-time values. In other words, something like a = 3; default(logfile, "some filename" a ".log") will work (and log the output in some filename3.log).

Some defaults will be expanded further when the values are used (after the above expansion has been performed):

• time expansion: the string is sent through the library function strftime. This means that %char combinations have a special meaning, usually related to the time and date. For instance, %H = hour (24-hour clock) and %M = minute [00,59] (on a Unix system, you can try man strftime at your shell prompt to get a complete list). This is applied to prompt, psfile, and logfile. For instance,

default(prompt,"(%R) ? ")

will prepend the time of day, in the form (hh:mm) to GP’s usual prompt.

UNIX: • environment expansion: When the string contains a sequence of the form $SOMEVAR (e.g. $HOME) the environment is searched and if SOMEVAR is defined, the sequence is replaced by the corresponding value. Also the ~ symbol has the same meaning as in the C and bash shells -- ~ by itself stands for your home directory, and ~user is expanded to user’s home directory. This is applied to all filenames.

2.1.1 buffersize (default 30k): GP input is buffered, which means only so many bytes of data can be read at a time before a command is executed. This used to be a very important variable, to allow for very large input files to be read into GP, for example large matrices, without it complaining about “unused characters”. Currently, buffersize is automatically adjusted to the size of the data that are to be read. It will never go down by itself though. Thus this option may come in handy to decrease the buffer size after some unusually large read, when you don’t need to keep gigantic buffers around anymore.

UNIX: 2.1.2 colors (default ""): this default is only usable if GP is running within certain color-capable
terminals. For instance rxvt, color_xterm and modern versions of xterm under X Windows, or standard
Linux/DOS text consoles. It causes GP to use a small palette of colors for its output. With xterms, the
colormap used corresponds to the resources Xterm*colorn where n ranges from 0 to 15 (see the file
misc/color.dft for an example). Legal values for this default are strings "a_{1},... ,a_{k}" where k __<__ 7 and each a_{i} is
either

• the keyword no (use the default color, usually black on transparent background)

• an integer between 0 and 15 corresponding to the aforementioned colormap

• a triple [c_{0}, c_{1}, c_{2}] where c_{0} stands for foreground color, c_{1} for background color, and c_{2} for attributes (0 is default,
1 is bold, 4 is underline).

The output objects thus affected are respectively error messages, history numbers, prompt, input line, output,
help messages, timer (that’s seven of them). If k < 7, the remaining a_{i} are assumed to be no. For
instance

default(colors, "9, 5, no, no, 4")

typesets error messages in color 9, history numbers in color 5, output in color 4, and does not affect the rest.

A set of default colors for dark (reverse video or PC console) and light backgrounds respectively is activated when colors is set to darkbg, resp. lightbg (or any proper prefix: d is recognized as an abbreviation for darkbg).

EMACS: In the present version, this default is incompatible with Emacs. Changing it will just fail silently (the alternative would be to display escape sequences as is, since Emacs will refuse to interpret them). On the other hand, you can customize highlighting in your .emacs so as to mimic exactly this behaviour. See emacs/pariemacs.txt.

If you use an old readline library (version number less than 2.0), you should do as in the example above and
leave a_{3} and a_{4} (prompt and input line) strictly alone. Since old versions of readline did not handle escape
characters correctly (or more accurately, treated them in the only sensible way since they did not care to check all
your terminal capabilities: it just ignored them), changing them would result in many annoying display
bugs.

The hacker’s way to check if this is the case would be to look in the readline.h include file (wherever your readline include files are) for the string RL_PROMPT_START_IGNORE. If it’s there, you are safe.

A more sensible way is to make some experiments, and get a more recent readline if yours doesn’t work the way you’d like it to. See the file misc/gprc.dft for some examples.

2.1.3 compatible (default 0): The GP function names and syntax have changed tremendously between versions 1.xx and 2.00. To help you cope with this we provide some kind of backward compatibility, depending on the value of this default:

compatible = 0: no backward compatibility. In this mode, a very handy function, to be described in Section ??, is whatnow, which tells you what has become of your favourite functions, which GP suddenly can’t seem to remember.

compatible = 1: warn when using obsolete functions, but otherwise accept them. The output uses the new conventions though, and there may be subtle incompatibilities between the behaviour of former and current functions, even when they share the same name (the current function is used in such cases, of course!). We thought of this one as a transitory help for GP old-timers. Thus, to encourage switching to compatible=0, it is not possible to disable the warning.

compatible = 2: use only the old function naming scheme (as used up to version 1.39.15), but taking case into account. Thus I ( = ) is not the same as i (user variable, unbound by default), and you won’t get an error message using i as a loop index as used to be the case.

compatible = 3: try to mimic exactly the former behaviour. This is not always possible when functions have changed in a fundamental way. But these differences are usually for the better (they were meant to, anyway), and will probably not be discovered by the casual user.

One adverse side effect is that any user functions and aliases that have been defined before changing compatible will get erased if this change modifies the function list, i.e. if you move between groups {0, 1} and {2, 3} (variables are unaffected). We of course strongly encourage you to try and get used to the setting compatible=0.

2.1.4 debug (default 0): debugging level. If it is non-zero, some extra messages may be printed (some of it in French), according to what is going on (see \g).

2.1.5 debugfiles (default 0): file usage debugging level. If it is non-zero, GP will print information on file descriptors in use, from PARI’s point of view (see \gf).

2.1.6 debugmem (default 0): memory debugging level. If it is non-zero, GP will regularly print information on memory usage. If it’s greater than 2, it will indicate any important garbage collecting and the function it is taking place in (see \gm).

Important Note: As it noticeably slows down the performance (and triggers bugs in some versions of a popular compiler), the first functionality (memory usage) is disabled if you’re not running a version compiled for debugging (see Appendix A).

2.1.7 echo (default 0): this is a toggle, which can be either 1 (on) or 0 (off). When echo mode is on, each command is reprinted before being executed. This can be useful when reading a file with the \r or read commands. For example, it is turned on at the beginning of the test files used to check whether GP has been built correctly (see \e).

2.1.8 format (default "g0.28" and "g0.38" on 32-bit and 64-bit machines, respectively): of the form xm.n, where x is a letter in {e, f, g}, and n, m are integers. If x is f, real numbers will be printed in fixed floating point format with no explicit exponent (e.g. 0.000033), unless their integer part is not defined (not enough significant digits); if the letter is e, they will be printed in scientific format, always with an explicit exponent (e.g. 3.3e-5). If the letter is g, real numbers will be printed in f format, except when their absolute value is less than 2^-32 or they are real zeroes (of arbitrary exponent), in which case they are printed in e format.

The number n is the number of significant digits printed for real numbers, except if n < 0 where all the significant digits will be printed (initial default 28, or 38 for 64-bit machines), and the number m is the number of characters to be used for printing integers, but is ignored if equal to 0 (which is the default). This is a feeble attempt at formatting.

UNIX: 2.1.9 help (default: the location of the gphelp script): the name of the external help program which will be used from within GP when extended help is invoked, usually through a ?? or ??? request (see Section 2.2.4), or M-H under readline (see Section ??).

2.1.10 histsize (default 5000): GP keeps a history of the last histsize results computed so far, which you can recover using the % notation (see Section 2.2.24). When this number is exceeded, the oldest values are erased. Tampering with this default is the only way to get rid of the ones you don’t need anymore.

2.1.11 lines (default 0): if set to a positive value, GP prints at most that many lines from each result, terminating the last line shown with [+++] if further material has been suppressed. The various print commands (see Section ??) are unaffected, so you can always type print(%), \a, or \b to view the full result. If the actual screen width cannot be determined, a “line” is assumed to be 80 characters long.

2.1.12 log (default 0): this is a toggle, which can be either 1 (on) or 0 (off). When logging mode is turned on, GP opens a log file, whose exact name is determined by the logfile default. Subsequently, all the commands and results will be written to that file (see \l). In case a file with this precise name already existed, it will not be erased: your data will be appended at the end.

2.1.13 logfile (default "pari.log"): name of the log file to be used when the log toggle is on. Tilde and time expansion are performed.

2.1.14 output (default 1): there are four possible values: 0 (= raw), 1 (= prettymatrix), 2 (= prettyprint), or 3 (= external prettyprint). This means that, independently of the default format for reals which we explained above, you can print results in four ways: either in raw format, i.e. a format which is equivalent to what you input, including explicit multiplication signs, and everything typed on a line instead of two dimensional boxes. This can have several advantages, for instance it allows you to pick the result with a mouse or an editor, and to paste it somewhere else.

The second format is the prettymatrix format. The only difference to raw format is that matrices are printed as boxes instead of horizontally. This is prettier, but takes more space and cannot be used for input. Column vectors are still printed horizontally.

The third format is the prettyprint format, or beautified format. In the present version 2.1.2, this is not beautiful at all.

UNIX: The fourth format is external prettyprint, which pipes all GP output in TeX format to an external prettyprinter, according to the value of prettyprinter. The default script (tex2mail) converts its input to readable two-dimensional text.

Independently of the setting of this default, an object can be printed in any of the three formats at any time using the commands \a, \m and \b respectively (see below).

2.1.15 parisize (default, 1M bytes on the Mac, 4M otherwise): GP, and in fact any program using the PARI library, needs a stack in which to do its computations. parisize is the stack size, in bytes. It is strongly recommended you increase this default (using the -s command-line switch, or a gprc) if you can afford it. Don’t increase it beyond the actual amount of RAM installed on your computer or GP will spend most of its time paging.

In case of emergency, you can use the allocatemem function to increase parisize, once the session is started. GP will try to double the stack size by itself when memory runs low during a computation, but this very computation will then be lost, and you will have to type the command again.

2.1.16 path (default ".:~:~/gp" on UNIX systems, ".;C:\;C:\GP on DOS, OS/2 and Windows, and "." otherwise): This is a list of directories, separated by colons ’:’ (semicolons ’;’ in the DOS world, since colons are pre-empted for drive names). When asked to read a file whose name does not contain / (i.e. no explicit path was given), GP will look for it in these directories, in the order they were written in path. Here, as usual, ’.’ means the current directory, and ’. .’ its immediate parent. Tilde expansion is performed.

UNIX: 2.1.17 prettyprinter (default "tex2mail -TeX -noindent -ragged -by_par") the name of an external prettyprinter to use when output is 3 (alternate prettyprinter). This is experimental but the default tex2mail looks already much nicer than the built-in “beautified format” (output = 2). If the corresponding program doesn’t exist on your system,

2.1.18 primelimit (default 200k on the Mac, and 500k otherwise): GP precomputes a list of all primes less than primelimit at initialization time. These are used by many arithmetical functions. If you don’t plan to invoke any of them, you can just set this to 1.

2.1.19 prompt (default "? "): a string that will be printed as prompt. Note that most usual escape sequences are available there: \e for Esc, \n for Newline, ... , \\ for \. Time expansion is performed.

This string is sent through the library function strftime (on a Unix system, you can try man strftime at your shell prompt). This means that % constructs have a special meaning, usually related to the time and date. For instance, %H = hour (24-hour clock) and %M = minute [00,59] (use %% to get a real %).

If you use readline, escape sequences in your prompt will result in display bugs. If you have a relatively recent readline (see the comment at the end of Section 2.1.3), you can brace them with special sequences (\[ and \]), and you will be safe. If these just result in extra spaces in your prompt, then you’ll have to get a more recent readline. See the file misc/gprc.dft for an example.

EMACS: Caution: Emacs needs to know about the prompt pattern to separate your input from previous GP results, without ambiguity. It’s not a trivial problem to adapt automatically this regular expression to an arbitrary prompt (which can be self-modifying!). Thus, in this version 2.1.2, Emacs relies on the prompt being the default one. So, do not tamper with the prompt variable unless you modify it simultaneously in your .emacs file (see emacs/pariemacs.txt and misc/gprc.dft for examples).

2.1.20 psfile (default "pari.ps"): name of the default file where GP is to dump its PostScript drawings (these will always be appended, so that no previous data are lost). Tilde and time expansion are performed.

2.1.21 realprecision (default 28 and 38 on 32-bit and 64-bit machines respectively): the number of significant digits
and, at the same time, the number of printed digits of real numbers (see \p). Note that PARI internal precision
works on a word basis (32 or 64 bits), hence may not coincide with the number of decimal digits you input. For
instance to get 2 decimal digits you need one word of precision which, on a 32-bit machine, actually gives you 9
digits (9 < log _{10}(2^32) < 10):

? default(realprecision, 2)

realprecision = 9 significant digits (2 digits displayed)

2.1.22 secure (default 0): this is a toggle which can be either 1 (on) or 0 (off). If on, the system and extern command are disabled. These two commands are potentially dangerous when you execute foreign scripts since they let GP execute arbitrary UNIX commands. GP will ask for confirmation before letting you (or a script) unset this toggle.

2.1.23 seriesprecision (default 16): precision of power series (see \ps).

2.1.24 simplify (default 1): this is a toggle which can be either 1 (on) or 0 (off). When the PARI library computes something, the type of the result is not always the simplest possible. The only type conversions which the PARI library does automatically are rational numbers to integers (when they are of type t_FRAC and equal to integers), and similarly rational functions to polynomials (when they are of type t_RFRAC and equal to polynomials). This feature is useful in many cases, and saves time, but can be annoying at times. Hence you can disable this and, whenever you feel like it, use the function simplify (see Chapter 3) which allows you to simplify objects to the simplest possible types recursively (see \y).

2.1.25 strictmatch (default 1): this is a toggle which can be either 1 (on) or 0 (off). If on, unused characters after a sequence has been processed will produce an error. Otherwise just a warning is printed. This can be useful when you’re not sure how many parentheses you have to close after complicated nested loops.

2.1.26 timer (default 0): this is a toggle which can be either 1 (on) or 0 (off). If on, every instruction sequence (anything ended by a newline in your input) is timed, to some accuracy depending on the hardware and operating system. The time measured is the user CPU time, not including the time for printing the results (see # and ##).

2.1.27 Note on output formats.

A zero real number is printed in e format as 0.Exx where xx is the (usually negative) decimal exponent of the number (cf. Section 1.3.1). This allows the user to check the accuracy of the zero in question (this could also be done using \x, but that would be more technical).

When the integer part of a real number x is not known exactly because the exponent of x is greater than the internal precision, the real number is printed in e format (note that in versions before 1.38.93, this was instead printed with a * at the end).

Note also that in beautified format, a number of type integer or real is written without enclosing parentheses, while most other types have them. Hence, if you see the expression (3.14), it is not of type real, but probably of type complex with zero imaginary part (if you want to be sure, type \x or use the function type).

2.2 Simple metacommands.

Simple metacommands are meant as shortcuts and should not be used in GP scripts (see Section ??). Beware that these, as all of GP input, are now case sensitive. For example, \Q is no longer identical to \q. In the following list, braces are used to denote optional arguments, with their default values when applicable, e.g. {n = 0} means that if n is not there, it is assumed to be 0. Whitespace (or spaces) between the metacommand and its arguments and within arguments is optional. (This can cause problems only with \w, when you insist on having a filename whose first character is a digit, and with \r or \w, if the filename itself contains a space. In such cases, just use the underlying read or write function; see Section ??).

2.2.1 ? {command}: GP on-line help interface. As already mentioned, if you type ?n where n is a number from 1 to 11, you will get the list of functions in Section 3.n of the manual (the list of sections being obtained by simply typing ?).

These names are in general not informative enough. More details can be obtained by typing ?function, which gives a short explanation of the function’s calling convention and effects. Of course, to have complete information, read Chapter 3 of this manual (the source code is at your disposal as well, though a trifle less readable!). Much better help can be obtained through the extended help system (see below).

UNIX: If the line before the copyright message indicates that extended help is available (this means perl is installed on your system, GP was told about it at compile time, and the whole PARI distribution was correctly installed), you can add more ? signs for extended functionalities:

?? keyword yields the functions description as it stands in this manual, usually in Chapter 2 or 3. If you’re not satisfied with the default chapter chosen, you can impose a given chapter by ending the keyword with @ followed by the chapter number, e.g. ?? Hello@2 will look in Chapter 2 for section heading Hello (which doesn’t exist, by the way).

All operators (e.g. +, &&, etc.) are accepted by this extended help, as well as a few other keywords describing key GP concepts, e.g. readline (the line editor), integer, nf (“number field” as used in most algebraic number theory computations), ell (elliptic curves), etc.

In case of conflicts between function and default names (e.g log, simplify), the function has higher priority. Use ?? default /defaultname to get the default help.

??? pattern produces a list of sections in Chapter 3 of the manual related to your query. As before, if pattern ends by @ followed by a chapter number, that chapter is searched instead; you also have the option to append a simple @ (without a chapter number) to browse through the whole manual.

If your query contains dangerous characters (e.g ? or blanks) it is advisable to enclose it within double quotes, as for GP strings (e.g ??? "elliptic curve").

Note that extended help is much more powerful than the short help, since it knows about operators as well: you can type ?? * or ?? &&, whereas a single ? would just yield a not too helpful

*** unknown identifier.

message. Also, you can ask for extended help on section number n in Chapter 3, just by typing ?? n (where ?n would yield merely a list of functions). Finally, a few key concepts in GP are documented in this way: metacommands (e.g ?? "??"), defaults (e.g ?? psfile) and type names (e.g t_INT or integer), as well as various miscellaneous keywords such as edit (short summary of line editor commands), operator, member, "user defined", nf, ell, ...

Last but not least : ?? without argument will open a dvi previewer (xdvi by default, $GPXDVI if it is defined in your environment) containing the full user’s manual. ??tutorial and ??refcard do the same with the tutorial and reference card respectively.

Technical note: these functionalities are provided by an external perl script that you are free to use outside any GP session (and modify to your liking, if you are perl-knowledgeable). It is called gphelp, lies in the doc subdirectory of your distribution (just make sure you run Configure first, see Appendix A) and is really two programs in one. The one which is used from within GP is gphelp which runs TEX on a selected part of this manual, then opens a previewer. gphelp -detex is a text mode equivalent, which looks often nicer especially on a colour-capable terminal (see misc/gprc.dft for examples). The default help selects which help program will be used from within GP. You are welcome to improve this help script, or write new ones (and we really would like to know about it so that we may include them in future distributions). By the way, outside of GP you can give more than one keyword as argument to gphelp.

2.2.2 /*...*/: comment. Everything between the stars is ignored by GP. These comments can span any number of lines.

2.2.3 \\: one-line comment. The rest of the line is ignored by GP.

2.2.4 \a {n}: prints the object number n (%n) in raw format. If the number n is omitted, print the latest computed object (%).

2.2.5 \b {n}: Same as \a, in prettyprint (i.e. beautified) format.

2.2.6 \c: prints the list of all available hardcoded functions under GP, not including operators written as special symbols (see Section 2.4). More information can be obtained using the ? metacommand (see above). For user-defined functions / member functions, see \u and \um.

2.2.7 \d: prints the defaults as described in the previous section (shortcut for default(), see Section ??).

2.2.8 \e {n}: switches the echo mode on (1) or off (0). If n is explicitly given, set echo to n.

2.2.9 \g {n}: sets the debugging level debug to the non-negative integer n.

2.2.10 \gf {n}: sets the file usage debugging level debugfiles to the non-negative integer n.

2.2.11 \gm {n}: sets the memory debugging level debugmem to the non-negative integer n.

2.2.12 \h {m-n}: outputs some debugging info about the hashtable. If the argument is a number n, outputs the contents of cell n. Ranges can be given in the form m-n (from cell m to cell n, $ = last cell). If a function name is given instead of a number or range, outputs info on the internal structure of the hash cell this function occupies (a struct entree in C). If the range is reduced to a dash (’-’), outputs statistics about hash cell usage.

2.2.13 \l {logfile}: switches log mode on and off. If a logfile argument is given, change the default logfile name to logfile and switch log mode on.

2.2.14 \m: as \a, but using prettymatrix format.

2.2.15 \o {n}: sets output mode to n (0: raw, 1: prettymatrix, 2: prettyprint, 3: external prettyprint).

2.2.16 \p {n}: sets realprecision to n decimal digits. Prints its current value if n is omitted.

2.2.17 \ps {n}: sets seriesprecision to n significant terms. Prints its current value if n is omitted.

2.2.18 \q: quits the GP session and returns to the system. Shortcut for the function quit (see Section ??).

2.2.19 \r {filename}: reads into GP all the commands contained in the named file as if they had been typed from the keyboard, one line after the other. Can be used in combination with the \w command (see below). Related but not equivalent to the function read (see Section ??); in particular, if the file contains more than one line of input, there will be one history entry for each of them, whereas read would only record the last one. If filename is omitted, re-read the previously used input file (fails if no file has ever been successfully read in the current session).

UNIX: This command accepts compressed files in compressed (.Z) or gzipped (.gz or .z) format. They will be uncompressed on the fly as GP reads them, without changing the files themselves.

2.2.20 \s: prints the state of the PARI stack and heap. This is used primarily as a debugging device for PARI, and is not intended for the casual user.

2.2.21 \t: prints the internal longword format of all the PARI types. The detailed bit or byte format of the initial codeword(s) is explained in Chapter 4, but its knowledge is not necessary for a GP user.

2.2.22 \u: prints the definitions of all user-defined functions.

2.2.23 \um: prints the definitions of all user-defined member functions.

2.2.24 \v: prints the version number and implementation architecture (680x0, Sparc, Alpha, other) of the GP executable you are using. In library mode, you can use instead the two character strings PARIVERSION and PARIINFO, which correspond to the first two lines printed by GP just before the Copyright message.

2.2.25 \w {n} {filename}: writes the object number n ( %n ) into the named file, in raw format. If the number n is omitted, writes the latest computed object ( % ). If filename is omitted, appends to logfile (the GP function write is a trifle more powerful, as you can have filenames whose first character is a digit).

2.2.26 \x: prints the complete tree with addresses and contents (in hexadecimal) of the internal representation of the latest computed object in GP. As for \s, this is used primarily as a debugging device for PARI, and the format should be self-explanatory (a * before an object - typically a modulus - means the corresponding component is out of stack). However, used on a PARI integer, it can be used as a decimalhexadecimal converter.

2.2.27 \y {n}: switches simplify on (1) or off (0). If n is explicitly given, set simplify to n.

2.2.28 #: switches the timer on or off.

2.2.29 ##: prints the time taken by the latest computation. Useful when you forgot to turn on the timer.

2.3 Input formats for the PARI types.

Before describing more sophisticated functions in the next section, let us see here how to input values of the different data types known to PARI. Recall that blanks are ignored in any expression which is not a string (see below).

2.3.1 Integers (type t_INT): type the integer (with an initial + or -, if desired) with no decimal point.

2.3.2 Real numbers (type t_REAL): type the number with a decimal point. The internal precision of the real number will be the supremum of the input precision and the default precision. For example, if the default precision is 28 digits, typing 2. will give a number with internal precision 28, but typing a 45 significant digit real number will give a number with internal precision at least 45 (although less may be printed).

You can also use scientific notation with the letter E or e, in which case the (non leading) decimal point may be omitted (like 6.02 E 23 or 1e-5, but not e10). By definition, 0.E N (or 0 E N) returns a real 0 of (decimal) exponent N, whereas 0. returns a real 0 “of default precision” (of exponent -defaultprecision), see Section 1.3.1.

2.3.3 Integermods (type t_INTMOD): to enter n mod m, type Mod(n,m), not n%m (see Section ??).

2.3.4 Rational numbers (types t_FRAC and t_FRACN): under GP, all fractions are automatically reduced to lowest terms, so it is in principle impossible to work with reducible fractions (of type t_FRACN), although of course in library mode this is easy. To enter n/m just type it as written. As explained in Section ??, division will not be performed, only reduction to lowest terms.

If you really want a reducible fraction under GP, you must use the type function (see Section ??), by typing type(x,FRACN). Be warned however that this function must be used with extreme care.

2.3.5 Complex numbers (type t_COMPLEX): to enter x + iy, type x + I*y (not x+i*y). The letter I stands for . Recall from Chapter 1 that x and y can be of type t_INT, t_REAL, t_INTMOD, t_FRAC/t_FRACN, or t_PADIC.

2.3.6 p-adic numbers (type t_PADIC): to enter a p-adic number, simply write a rational or integer expression and add to it O(p^k), where p and k are integers. This last expression indicates three things to GP: first that it is dealing with a t_PADIC type (the fact that p is an integer, and not a polynomial, which would be used to enter a series, see Section 2.4), secondly the “prime” p (note that it is not checked whether p is indeed prime; you can work on 10-adics if you want, but beware of disasters as soon as you do something non-trivial like taking a square root), and finally the number of significant p-adic digits k. Note that O(25) is not the same as O(5^2); you probably want the latter!

For example, you can type in the 7-adic number

2*7^(-1) + 3 + 4*7 + 2*7^2 + O(7^3)

exactly as shown, or equivalently as 905/7 + O(7^3).

2.3.7 Quadratic numbers (type t_QUAD): first, you must define the default quadratic order or field in which you want to work. This is done using the quadgen function, in the following way. Write something like

w = quadgen(d)

where d is the discriminant of the quadratic order in which you want to work (hence d is congruent to 0 or 1 modulo 4). The name w is of course just a suggestion, but corresponds to traditional usage. You can of course use any variable name that you like. However, quadratic numbers are always printed with a w, regardless of the discriminant. So beware, two numbers can be printed in the same way and not be equal. However GP will refuse to add or multiply them for example.

Now (1, w) will be the “canonical” integral basis of the quadratic order (i.e. w = /2 if d 0 mod 4, and w = (1 + )/2 if d 1 mod 4, where d is the discriminant), and to enter x + yw you just type x + y*w.

2.3.8 Polmods (type t_POLMOD): exactly as for integermods, to enter x mod y (where x and y are polynomials), type
Mod(x,y), not x%y (see Section ??). Note that when y is an irreducible polynomial in one variable, polmods
whose modulus is y are simply algebraic numbers in the finite extension defined by the polynomial
y. This allows us to work easily in number fields, finite extensions of the p-adic field Q_{p}, or finite
fields.

Important remark. Since the variables occurring in a polmod are not free variables, it is essential in order to avoid inconsistencies that polmods use the same variable in internal operations (i.e. between polmods) and variables of lower priority (which have been introduced later in the GP session) for external operations (typically between a polynomial and a polmod). For example, PARI will not recognize that Mod(y, y^2 + 1) is the same as Mod(x, x^2 + 1). Hopefully, this problem will pass away when type “element of a number field” is eventually introduced.

On the other hand, Mod(x, x^2 + 1) + Mod(x, x^2 + 1) (which gives Mod(2*x, x^2 + 1)) and x + Mod(y, y^2 + 1) (which gives a result mathematically equivalent to x + i with i^2 = -1) are completely correct, while y + Mod(x, x^2 + 1) gives Mod(x + y, x^2 + 1), which may not be what you want (y is treated here as a numerical parameter, not as a polynomial variable).

Note (added in version 2.0.16) As long as the main variables are the same, it is allowed to mix t_POL and t_POLMODs. The result will be the expected t_POLMOD. For instance x + Mod(x, x^2 + 1) is equal to Mod(2*x, x^2 + 1). This wasn’t the case prior to version 2.0.16: it returned a polynomial in x equivalent to x + i, which was in fact an invalid object (you couldn’t lift it).

2.3.9 Polynomials (type t_POL): type the polynomial in a natural way, not forgetting to put a “*” between a coefficient and a formal variable (this * does not appear in beautified output). Any variable name can be used except for the reserved names I (used exclusively for the square root of -1), Pi (3.14...), Euler (Euler’s constant), and all the function names: predefined functions, as described in Chapter 3 (use \c to get the complete list of them) and user-defined functions, which you ought to know about (use \u if you are subject to memory lapses). The total number of different variable names is limited to 16384 and 65536 on 32-bit and 64-bit machines respectively, which should be enough. If you ever need hundreds of variables, you should probably be using vectors instead.

2.3.10 Power series (type t_SER): type a rational function or polynomial expression and add to it O(expr ^k), where expr is an expression which has non-zero valuation (it can be a polynomial, power series, or a rational function; the most common case being simply a variable name). This indicates to GP that it is dealing with a power series, and the desired precision is k times the valuation of expr with respect to the main variable of expr (to check the ordering of the variables, or to modify it, use the function reorder; see Section ??).

2.3.11 Rational functions (types t_RFRAC and t_RFRACN): as for fractions, all rational functions are automatically reduced to lowest terms under GP. All that was said about fractions in Section 2.3.8 remains valid here.

2.3.12 Binary quadratic forms of positive or negative discriminant (type t_QFR and t_QFI): these are input using the function Qfb (see Chapter 3). For example Qfb(1,2,3) will create the binary form x^2 + 2xy + 3y^2. It will be imaginary (of internal type t_QFI) since 2^2 - 4 * 3 = -8 is negative.

In the case of forms with positive discriminant (type t_QFR), you may add an optional fourth component (related to the regulator, more precisely to Shanks and Lenstra’s “distance”), which must be a real number. See also the function qfbprimeform which directly creates a prime form of given discriminant (see Chapter 3).

2.3.13 Row and column vectors (types t_VEC and t_COL): to enter a row vector, type the components separated by commas “,”, and enclosed between brackets “[ ” and “ ]”, e.g. [1,2,3]. To enter a column vector, type the vector horizontally, and add a tilde “~” to transpose. [ ] yields the empty (row) vector. The function Vec can be used to transform any object into a vector (see Chapter 3).

2.3.14 Matrices (type t_MAT): to enter a matrix, type the components line by line, the components being separated by commas “,”, the lines by semicolons “;”, and everything enclosed in brackets “[ ” and “ ]”, e.g. [x,y; z,t; u,v]. [ ; ] yields the empty (0x0) matrix. The function Mat can be used to transform any object into a matrix (see Chapter 3).

Note that although the internal representation is essentially the same (only the type number is different), a row vector of column vectors is not a matrix; for example, multiplication will not work in the same way.

Note also that it is possible to create matrices (by conversion of empty column vectors and concatenation, or using the matrix function) with a given positive number of columns, each of which has zero rows. It is not possible to create or represent matrices with zero columns and a nonzero number of rows.

2.3.15 Lists (type t_LIST): lists cannot be input directly; you have to use the function listcreate first, then listput each time you want to append a new element (but you can access the elements directly as with the vector types described above). The function List can be used to transform (row or column) vectors into lists (see Chapter 3).

2.3.16 Strings (type t_STR): to enter a string, just enclose it between double quotes ", like this: "this is a string". The function Str can be used to transform any object into a string (see Chapter 3).

2.4 GP operators.

Loosely speaking, an operator is a function (usually associated to basic arithmetic operations) whose name
contains only non-alphanumeric characters. In practice, most of these are simple functions, which take
arguments, and return a value; assignment operators also have side effects. Each of these has some fixed
and unchangeable priority, which means that, in a given expression, the operations with the highest
priority will be performed first. Operations at the same priority level will always be performed in the
order they were written, i.e. from left to right. Anything enclosed between parenthesis is considered a
complete subexpression, and will be resolved independently of the surrounding context. For instance,
assuming that op_{1}, op_{2}, op_{3} are standard binary operators with increasing priorities (think of +, *, ^ for
instance),

GP knows quite a lot of different operators, some of them unary (having only one argument), some binary. Unary operators are defined for either prefix (preceding their single argument: op x) or postfix (following the argument: x op) position, never both (some are syntactically correct in both positions, but with different meanings). Binary operators all use the syntax x op y. Most of them are well known, some are borrowed from C syntax, and a few are specific to GP. Beware that some GP operators may differ slightly from their C counterparts. For instance, GP’s postfix ++ returns the new value, like the prefix ++ of C, and the binary shifts <<, >> have a priority which is different from (higher than) that of their C counterparts. When in doubt, just surround everything by parentheses (besides, your code will probably be more legible).

Here is the complete list (in order of decreasing priority, binary unless mentioned otherwise):

• Priority 9 ++ and -- (unary, postfix): x++ assigns the value x + 1 to x, then returns the new value of x. This corresponds to the C statement ++x (there is no prefix ++ operator in GP). x-- does the same with x - 1.

• Priority 8 op=, where op is any simple binary operator (i.e. a binary operator with no side effects, i.e. one of those defined below) which is not a boolean operator (comparison or logical). x op= y assigns (x op y) to x, and returns the new value of x, not a reference to the variable x. (Thus an assignment cannot occur on the lefthand side of another assignment.)

• Priority 7 = is the assignment operator. The result of x = y is the value of the expression y, which is also assigned to the variable x. This is not the equality test operator. Beware that a statement like x = 1 is always true (i.e. non-zero), and sets x to 1.

• Priority 6 ! (unary, prefix): logical not. !x return 1 if x is equal to 0 (specifically, if gcmp0(x)==1), and 0 otherwise.

' (unary, prefix): quote its argument without evaluating it.

? a = x + 1; x = 1;

? subst(a,x,1)

*** variable name expected: subst(a,x,1)

^---

? subst(a,'x,1)

%1 = 2

• Priority 5 ^: powering.

' (unary, postfix): derivative with respect to the main variable. If f is a (GP or user) function, f'(x) is allowed. If x is a scalar, the operator performs numerical derivation, defined as (f(x + ) - f(x - ))/2 for a suitably small epsilon depending on current precision. It behaves as (f(x))' otherwise.

~ (unary, postfix): vector/matrix transpose.

! (unary, postfix): factorial. x! = x(x - 1)1.

.: x.b extracts member b from structure x.

• Priority 4 +, - (unary, prefix): - toggles the sign of its argument, + has no effect whatsoever.

• Priority 3 *: multiplication.

/: exact division (3/2=3/2, not 1.5).

\, %: euclidean quotient and remainder, i.e. if x = qy + r, with 0 __<__ r < y (if x and y are polynomials, assume
instead that deg r < deg y and that the leading terms of r and x have the same sign), then x\y = q,
x%y = r.

\/: rounded euclidean quotient for integers (rounded towards + when the exact quotient would be a half-integer).

<<, >>: left and right binary shift: x<<n = x * 2^n if n > 0, and x\/2^-n otherwise; and x>>n = x<<(-n).

• Priority 2 +, -: addition/subtraction.

• Priority 1
<, >, <=, >=: the usual comparison operators, returning 1 for true and 0 for false. For instance, x<=1 returns 1
if x __<__ 1 and 0 otherwise.

<>, !=: test for (exact) inequality.

==: test for (exact) equality.

• Priority 0 &, &&: logical and.

|, ||: logical (inclusive) or. Any sequence of logical or and and operations is evaluated from left to right, and aborted as soon as the final truth value is known. Thus, for instance, (x && 1/x) or (type(p) == "t_INT" && isprime(p)) will never produce an error since the second argument need not (and will not) be processed when the first is already zero (false).

Remark: For the optimal efficiency, you should use the ++, -- and op= operators whenever possible:

? a = 200000;

? i = 0; while(i<a, i=i+1)

time = 4,919 ms.

? i = 0; while(i<a, i+=1)

time = 4,478 ms.

? i = 0; while(i<a, i++)

time = 3,639 ms.

For the same reason, the shift operators should be preferred to multiplication:

? a = 1<<20000;

? i = 1; while(i<a, i=i*2);

time = 5,255 ms.

? i = 1; while(i<a, i<<=1);

time = 988 ms.

2.5 The general GP input line.

2.5.1 Generalities. User interaction with a GP session proceeds as follows: a sequence of characters is typed by the user at the GP prompt. This can be either a \ command, a function definition, an expression, or a sequence of expressions (i.e. a program). In the latter two cases, after the last expression has been computed its result is put into an internal (“history”) array, and printed. The successive elements of this array are called %1, %2, ... As a shortcut, the latest computed expression can also be called %, the previous one %`, the one before that %`` and so on.

If you want to suppress the printing of the result, for example because it is a long unimportant intermediate result, end the expression with a ; sign. This same sign is used as an instruction separator when several instructions are written on the same line (note that for the pleasure of BASIC addicts, the : sign can also be used, but we will try to stick to C-style conventions in this manual). The final expression computed, even if not printed, will still be assigned to the history array, so you may have to pay close attention when you intend to refer back to it by number since this number does not appear explicitly. Of course, if you just want to use it on the next line, use % as usual.

Any legal expression can be typed in, and is evaluated using the conventions about operator priorities and left to right associativity (see the previous section), using the available operator symbols, function names (including user-defined functions and member functions see Section 2.6.3), and special variables. Please note that, from version 1.900 on, there is a distinction between lowercase and uppercase. Also, note that, outside of constant strings, blanks are completely ignored in the input to GP.

The special variable names known to GP are Euler (Euler’s constant = 0.577...), I (the square root of -1), Pi (3.14... ) -- which could be thought of as functions with no arguments, and which may therefore be invoked without parentheses --, and O which obeys the following syntax:

O(expr^k)

When expr is an integer or a rational number, this creates an expr-adic number (zero in fact) of precision k. When expr is a polynomial, a power series or a rational function whose main variable is X, say, this creates a power series (also zero) of precision v * k where v is the X-adic valuation of expr (see 2.3.8 and 2.4).

2.5.2 Special editing characters. A GP program can of course have more than one line. Since GP executes your commands as soon as you have finished typing them, there must be a way to tell it to wait for the next line or lines of input before doing anything. There are three ways of doing this.

The first one is simply to use the backslash character \ at the end of the line that you are typing, just before hitting <Return>. This tells GP that what you will write on the next line is the physical continuation of what you have just written. In other words, it makes GP forget your newline character. For example if you use this while defining a function, and if you ask for the definition of the function using ?name, you will see that your backslash has disappeared and that everything is on the same line. You can type a \ anywhere. It will be interpreted as above only if (apart from ignored whitespace characters) it is immediately followed by a newline. For example, you can type

? 3 + \

4

instead of typing 3 + 4.

The second one is a slight variation on the first, and is mostly useful when defining a user function (see Section 2.6.3): since an equal sign can never end a valid expression, GP will disregard a newline immediately following an =.

? a =

123

%1 = 123

The third one cannot be used everywhere, but is in general much more useful. It is the use of braces { and }. When GP sees an opening brace ({) at the beginning of a line (modulo spaces as usual), it understands that you are typing a multi-line command, and newlines will be ignored until you type a closing brace }. However, there is an important (but easily obeyed) restriction: inside an open brace-close brace pair, all your input lines will be concatenated, suppressing any newlines. Thus, all newlines should occur after a semicolon (;), a comma (,) or an operator (for clarity’s sake, we don’t recommend splitting an identifier over two lines in this way). For instance, the following program

{

a = b

b = c

}

would silently produce garbage, since what GP will really see is a=bb=c which will assign the value of c to both bb and a (if this really is what you intended, you’re a hopeless case).

2.6 The GP/PARI programming language.

The GP calculator uses a purely interpreted language. The structure of this language is reminiscent of LISP with a functional notation, f(x,y) rather than (f x y): all programming constructs, such as if, while, etc... are functions * (see Section ?? for a complete list), and the main loop does not really execute, but rather evaluates (sequences of) expressions. Of course, it is by no means a true LISP.

2.6.1 Variables and symbolic expressions.

In GP you can use up to 16383 variable names (up to 65535 on 64-bit machines). These names can be any standard identifier names, i.e. they must start with a letter and contain only valid keyword characters: _ or alphanumeric characters ([_A-Za-z0-9]). To avoid confusion with other symbols, you must not use other non-alphanumeric symbols like $, or ’.’. In addition to the function names which you must not use (see the list with \c), there are exactly three special variable names which you are not allowed to use: Pi and Euler, which represent well known constants, and I = .

Note that GP names are case sensitive since version 1.900. This means for instance that the symbol i is perfectly safe to use, and will not be mistaken for , and that o is not synonymous anymore to O. If you grew addicted to the previous behaviour, you can have it back by setting the default compatible to 3.

Now the main thing to understand is that PARI/GP is not a symbolic manipulation package, although it shares some of the functionalities. One of the main consequences of this fact is that all expressions are evaluated as soon as they are written, they never stay in a purely abstract form**. As an important example, consider what happens when you use a variable name before assigning a value into it. This is perfectly acceptable to GP, which considers this variable in fact as a polynomial of degree 1, with coefficients 1 in degree 1, 0 in degree 0, whose variable is the variable name you used.

If later you assign a value to that variable, the objects which you have created before will still be considered as polynomials. If you want to obtain their value, use the function eval (see Section ??).

Finally, note that if the variable x contains a vector or list, you can assign a result to x[m] (i.e. write something like x[k] = expr). If x is a matrix, you can assign a result to x[m, n], but not to x[m]. If you want to assign an expression to the m-th column of a matrix x, use x[, m] = expr instead. Similarly, use x[m, ] = expr to assign an expression to the m-th row of x. This process is recursive, so if x is a matrix of matrices of ... , an expression such as x[1, 1][, 3][4] = 1 would be perfectly valid (assuming of course that all matrices along the way have the correct dimensions).

Note: We’ll see in Section 2.6.3 that it is possible to restrict the use of a given variable by declaring it to be global or local. This can be useful to enforce clean programming style, but is in no way mandatory.

(Technical) Note: Variables are numbered in the order that they appear since the beginning of the session, and the main variable of an expression is always the lowest numbered variable. Hence if you are working with expressions involving several variables and want to have them ordered in a specific manner in the internal representation, the simplest is just to write down the variables one after the other under GP before starting any real computations. If you already have started working and want to change the names of the variables in an object, use the function changevar. If you only want to have them ordered when the result is printed, you can also use the function reorder, but this won’t change anything to the internal representation.

(Very technical) Note: Each variable has a stack of values, implemented as a linked list. When a new scope is entered (during a function call which uses it as a parameter, or if the variable is used as a loop index, see Section 2.6.3 and Section ??), the value of the actual parameter is pushed on the stack. If the parameter is not supplied, a special 0 value called gnil is pushed on the stack (this value is not printed if it is returned as the result of a GP expression sequence). Upon exit, the stack decreases. You can kill a variable, decreasing the stack yourself. This should be used only at the top level of GP, to undo the effect of an assignment, not from a function. However, the stack has a bottom: the value of a variable is the monomial of degree 1 in this variable, as is natural for a mathematician.

2.6.2 Expressions and expression sequences.

An expression is formed by combining the GP operators, functions (including user-defined functions, see below) and control statements. It may be preceded by an assignment statement ’=’ into a variable. It always has a value, which can be any PARI object.

Several expressions can be combined on a single line by separating them with semicolons (’;’) and also with colons (’:’) for those who are used to BASIC. Such an expression sequence will be called simply a seq. A seq also has a value, which is the value of the last non-empty expression in the sequence. Under GP, the value of the seq, and only this last value, is always put on the stack (i.e. it will become the next object %n). The values of the other expressions in the seq are discarded after the execution of the seq is complete, except of course if they were assigned into variables. In addition, the value of the seq (or of course of an expression if there is only one) is printed if the line does not end with a semicolon (’;’).

2.6.3 User defined functions.

It is very easy to define a new function under GP, which can then be used like any other function. The syntax is as follows:

name(list of formal variables) = local(list of local variables); seq

which looks better written on consecutive lines:

name(x_{0}, x_{1}, ... ) =

{

local(t_{0}, t_{1}, ... );

local(... );

...

}

(note that the first newline is disregarded due to the preceding = sign, and the others because of the enclosing braces). Both lists of variables are comma-separated and allowed to be empty. The local statements can be omitted; as usual seq is any expression sequence.

name is the name given to the function and is subject to the same restrictions as variable names. In addition, variable names are not valid function names, you have to kill the variable first (the converse is true: function names can’t be used as variables, see Section ??). Previously used function names can be recycled: you are just redefining the function (the previous definition is lost of course).

list of formal variables is the list of variables corresponding to those which you will actually use when calling your function. The number of actual parameters supplied when calling the function has to be less than the number of formal variables.

Uninitialized formal variables will be given a default value. An equal (=) sign following a variable name in the function definition, followed by any expression, gives the variable a default value. The expression gets evaluated the moment the function is defined, and is fixed afterward. A variable for which you supply no default value will be initialized to zero.

list of local variables is the list of the additional local variables which are used in the function body. Note that if you omit some or all of these local variable declarations, the non-declared variables will become global, hence known outside of the function, and this may have undesirable side-effects. On the other hand, in some cases it may also be what you want. Local variables can be given a default value as the formal variables.

Example: For instance

foo(x=1, y=2, z=3) = print(x ":" y ":" z)

defines a function which prints its arguments (at most three of them), separated by colons. This then follows the rules of default arguments generation as explained at the beginning of Section ??.

? foo(6,7)

6:7:3

? foo(,5)

1:5:3

? foo

1:2:3

Once the function is defined using the above syntax, you can use it like any other function. In addition, you can also recall its definition exactly as you do for predefined functions, that is by writing ?name. This will print the list of arguments, as well as their default values, the text of seq, and a short help text if one was provided using the addhelp function (see Section ??). One small difference to predefined functions is that you can never redefine the built-in functions, while you can redefine a user-defined function as many times as you want.

Typing \u will output the list of user-defined functions.

An amusing example of a user-defined function is the following. It is intended to illustrate both the use of user-defined functions and the power of the sumalt function. Although the Riemann zeta-function is included in the standard functions, let us assume that this is not the case (or that we want another implementation). One way to define it, which is probably the simplest (but certainly not the most efficient), is as follows:

zet(s) =

{

local(n); /* not needed, and possibly confusing (see below) */

sumalt(n=1, (-1)^(n-1)*n^(-s)) / (1 - 2^(1-s))

}

This gives reasonably good accuracy and speed as long as you are not too far from the domain of convergence. Try it for s integral between -5 and 5, say, or for s = 0.5 + i * t where t = 14.134...

The iterative constructs which use a variable name (forxxx, prodxxx, sumxxx, vector, matrix, plot, etc.) also consider the given variable to be local to the construct. A value is pushed on entry and pulled on exit. So, it is not necessary for a function using such a construct to declare the variable as a dummy formal parameter.

In particular, since loop variables are not visible outside their loops, the variable n need not be declared in the protoype of our zet function above.

zet(s) = sumalt(n=1, (-1)^(n-1)*n^(-s)) / (1 - 2^(1-s))

would be a perfectly sensible (and in fact better) definition. Since local/global scope is a very tricky point, here’s one more example. What’s wrong with the following definition?

? first_prime_div(x) =

{

local(p);

forprime(p=2, x, if (x%p == 0, break));

p

}

? first_prime_div(10)

%1 = 0

Answer: the index p in the forprime loop is local to the loop and is not visible to the outside world. Hence, it doesn’t survive the break statement. More precisely, at this point the loop index is restored to its preceding value, which is 0 (local variables are initialized to 0 by default). To sum up, the routine returns the p declared local to it, not the one which was local to forprime and ran through consecutive prime numbers. Here’s a corrected version:

? first_prime_div(x) = forprime(p=2, x, if (x%p == 0, return(p)))

Again, it is strongly recommended to declare all other local variables that are used inside a function: if a function accesses a variable which is not one of its formal parameters, the value used will be the one which happens to be on top of the stack at the time of the call. This could be a “global” value, or a local value belonging to any function higher in the call chain. So, be warned.

Recursive functions can easily be written as long as one pays proper attention to variable scope. Here’s a last example, used to retrieve the coefficient array of a multivariate polynomial (a non-trivial task due to PARI’s unsophisticated representation for those objects):

coeffs(P, nbvar) =

{

local(v);

if (type(P) != "t_POL",

for (i=0, nbvar-1, P = [P]);

return (P)

);

v = vector(poldegree(P)+1, i, polcoeff(P,i-1));

vector(length(v), i, coeffs(v[i], nbvar-1))

}

If P is a polynomial in k variables, show that after the assignment v = coeffs(P,k), the coefficient of x_{1}^{n1}...x_{k}^{nk}
in P is given by v[n_{1}+1][... ][n_{k}+1]. What would happen if the declaration local(v) had been omitted
?

The operating system will automatically limit the recursion depth:

? dive(n) = if (n, dive(n-1))

? dive(5000);

*** deep recursion: if(n,dive(n-1))

^---------------

There’s no way to increase the recursion limit (which may be different on your machine) from within, since it would simply crash the GP process. To increase it before launching GP, you can use ulimit or limit, depending on your shell, to raise the process available stack space (increase stacksize).

Function which take functions as parameters ? This is easy in GP using the following trick (neat example due to Bill Daly):

calc(f, x) = eval(Str( f "(x)"))

If you call this with calc("sin", 1), it will return sin(1) (evaluated!).

Restrictions on variable use: it is not allowed to use the same variable name for different parameters of your function. Or to use a given variable both as a formal parameter and a local variable in a given function. Hence

? f(x,x) = 1

*** user function f: variable x declared twice.

Also, the statement global(x, y, z, t) (see Section ??) declares the corresponding variables to be global. It is then forbidden to use them as formal parameters or loop indexes as described above, since the parameter would “shadow” the variable.

Implementation note. For the curious reader, here is how these stacks are handled: a hashing function is computed from the identifier, and used as an index in hashtable, a table of pointers. Each of these pointers begins a linked list of structures (type entree). The linked list is searched linearly for the identifier (each list will typically have less than 7 components or so). When the correct entree is found, it points to the top of the stack of values for that identifier if it is a variable, to the function itself if it is a predefined function, and to a copy of the text of the function if it is a user-defined function. When an error occurs, all of this maze (rather a tree, in fact) is searched and (hopefully) restored to the state preceding the last call of the main evaluator.

Note: The above syntax (using the local keyword) was introduced in version 2.0.13. The old syntax

name(list of true formal variables, list of local variables) = seq

is still recognized but is deprecated since genuine arguments and local variables become undistinguishable.

2.6.4 Member functions.

Member functions use the ‘dot’ notation to retrieve information from complicated structures (by default: types ell, nf, bnf, bnr and prime ideals). The syntax structure.member is taken to mean: retrieve member from structure, e.g. ell.j returns the j-invariant of the elliptic curve ell (or outputs an error message if ell doesn’t have the correct type).

To define your own member functions, use the syntax structure.member = function text, where function text is written as the seq in a standard user function (without local variables), whose only argument would be structure. For instance, the current implementation of the ell type is simply an horizontal vector, the j-invariant being the thirteenth component. This could be implemented as

x.j =

{

if (type(x) != "t_VEC" || length(x) < 14,

error("this is not a proper elliptic curve: " x)

);

x[13]

}

You can redefine one of your own member functions simply by typing a new definition for it. On the other hand, as a safety measure, you can’t redefine the built-in member functions, so typing the above text would in fact produce an error (you’d have to call it e.g. x.j2 in order for GP to accept it).

Warning: contrary to user functions arguments, the structure accessed by a member function is not copied before being used. Any modification to the structure’s components will be permanent.

Note: Member functions were not meant to be too complicated or to depend on any data that wouldn’t be global. Hence they do no have parameters (besides the implicit structure) or local variables. Of course, if you need some preprocessing work in there, there’s nothing to prevent you from calling your own functions (using freely their local variables) from a member function. For instance, one could implement (a dreadful idea as far as efficiency goes):

correct_ell_if_needed(x) =

{

local(tmp);

if (type(x) != "t_VEC", tmp = ellinit(x))

\\ ^I=10

x.j = correctellifneeded(x)[13];

Typing \b{um} will output the list of user-defined member functions.

\subsec{Strings and Keywords}\sidx{string}\sidx{keyword}

\label{se:strings}

\noindent

GP variables can now hold values of type character string (internal type

\typ{STR}). This section describes how they are actually used, as well as

some convenient tricks (automatic concatenation and expansion, keywords)

valid in string context.

As explained above, the general way to input a string is to enclose

characters between quotes~\kbd{"}. This is the only input construct where

whitespace characters are significant: the string will contain the exact

number of spaces you typed in. Besides, you can ``escape'' characters by

putting a \kbd{\bs} just before them; the translation is as follows

\bprog

\e: <Escape>

\n: <Newline>

\t: <Tab>

For any other character x, \x is expanded to x. In particular, the only way to put a " into a string is to escape it. Thus, for instance, "\"a\"" would produce the string whose content is “a”. This is definitely not the same thing as typing "a", whose content is merely the one-letter string a.

You can concatenate two strings using the concat function. If either argument is a string, the other is automatically converted to a string if necessary (it will be evaluated first).

? concat("ex", 1+1)

%1 = "ex2"

? a = 2; b = "ex"; concat(b, a)

%2 = "ex2"

? concat(a, b)

%3 = "2ex"

Some functions expect strings for some of their arguments: print would be an obvious example, Str is a less obvious but very useful one (see the end of this section for a complete list). While typing in such an argument, you will be said to be in string context. The rest of this section is devoted to special syntactical tricks which can be used with such arguments (and only here; you will get an error message if you try these outside of string context):

• Writing two strings alongside one another will just concatenate them, producing a longer string. Thus it is equivalent to type in "a " "b" or "a b". A little tricky point in the first expression: the first whitespace is enclosed between quotes, and so is part of a string; while the second (before the "b") is completely optional and GP actually suppresses it, as it would with any number of whitespace characters at this point (i.e. outside of any string).

• If you insert an expression without quotes when GP expects a string, it gets “expanded”: it is evaluated as a standard GP expression, and the final result (as would have been printed if you had typed it by itself) is then converted to a string, as if you had typed it directly. For instance "a" 1+1 "b" is equivalent to "a2b": three strings get created, the middle one being the expansion of 1+1, and these are then concatenated according to the rule described above. Another tricky point here: assume you did not assign a value to aaa in a GP expression before. Then typing aaa by itself in a string context will actually produce the correct output (i.e. the string whose content is aaa), but in a fortuitous way. This aaa gets expanded to the monomial of degree one in the variable aaa, which is of course printed as aaa, and thus will expand to the three letters you were expecting.

• Since there are cases where expansion is not really desirable, we now distinguish between “Keywords” and “Strings”. String is what has been described so far. Keywords are special relatives of Strings which are automatically assumed to be quoted, whether you actually type in the quotes or not. Thus expansion is never performed on them. They get concatenated, though. The analyzer supplies automatically the quotes you have “forgotten” and treats Keywords just as normal strings otherwise. For instance, if you type "a"b+b in Keyword context, you will get the string whose contents are ab+b. In String context, on the other hand, you would get a2*b.

All GP functions have prototypes (described in Chapter 3 below) which specify the types of arguments they expect: either generic PARI objects (GEN), or strings, or keywords, or unevaluated expression sequences. In the keyword case, only a very small set of words will actually be meaningful (the default function is a prominent example).

Let’s now try some not-so-stupid exercises to get the hang of it. Try to guess the results of the following commands without actually typing them, assuming that the print command evaluates and prints its (string) arguments in left-to-right order, ending with a newline (and returns 0 as an unprinted result):

print()

print(1+3"a,3" ,4)

print(a=3, (1 + ((a-3)==print())) (a = (a == 5\/2)))

Here is a less artificial example, used to create generic matrices:

? genmat(u,v,s="x") = matrix(u,v,i,j, eval(Str(s "" i "" j)))

? genmat(2,3) + genmat(2,3,"m")

%1 =

[x11 + m11 x12 + m12 x13 + m13]

[x21 + m21 x22 + m22 x23 + m23]

Note that the argument of Str is evaluated in string context, and really consists of 5 pieces (exercise: why are the empty strings necessary?). This part could also have been written as concat(concat(Str(s), i), j) (but not as concat(Str(s), concat(i,j))!). More simply, we could have written concat([Str(s), i,j]), or even concat([s,i,j]), silently assuming that s will indeed be a string. In practice Str is much more efficient, if slightly more cryptic.

And here’s a final one: the function hist returns all history entries from %a to %b neatly packed into a single vector

? hist(a,b) = vector(b-a+1, i, eval(Str("%" a-1+i)))

The arguments of the following functions are processed in string context:

Str |

addhelp (second argument) |

default (second argument) |

error |

extern |

plotstring (second argument) |

plotterm (first argument) |

read |

system |

all the printxxx functions |

all the writexxx functions |

The arguments of the following functions are processed as keywords:

alias |

default (first argument) |

install (all arguments but the last) |

trap (first argument) |

type (second argument) |

whatnow |

2.7 Interfacing GP with other languages.

The PARI library was meant to be interfaced with C programs. This specific use will be dealt with extensively in Chapter 4. GP itself provides a convenient, if simple-minded, interpreter, which enables you to execute rather intricate scripts (see Section ??).

Scripts, when properly written, tend to be shorter and much clearer than C programs, and are certainly easier to write, maintain or debug. You don’t need to deal with memory management, garbage collection, pointers, declarations, and so on. Because of their intrinsic simplicity, they are more robust as well. They are unfortunately somewhat slower. Thus their use will remain complementary: it is suggested that you test and debug your algorithms using scripts, before actually coding them in C for the sake of speed.

UNIX: Note that the install command enables you to concentrate on critical parts of your programs only (which can of course be written with the help of other mathematical libraries than PARI!), and to easily and efficiently import foreign functions for use under GP (see Section ??).

We are aware of three PARI-related public domain libraries. We neither endorse nor support any of them. You might want to give them a try if you are familiar with the languages they are based on. First, there are PariPerl*, written by Ilya Zakharevich (ilya@math.ohio-state.edu), and PariPython**, by Stéfane Fermigier (fermigie@math.jussieu.fr). Finaly, Michael Stoll (Michael_Stoll@math.uni-bonn.de) has integrated PARI into CLISP, which is a Common Lisp implementation by Bruno Haible, Marcus Daniels and others. These provide interfaces to GP functions for use in perl, python or Lisp programs. To our knowledge, only the python and perl interfaces have been upgraded to version 2.0 of PARI, the CLISP one being still based on version 1.39.xx.

2.8 The preferences file.

When GP is started, it looks for a customization file, or gprc in the following places (in this order, only the first one found will be read):

• On the Macintosh (only), GP looks in the directory which contains the GP executable itself for a file called gprc. No other places are examined.

• If the operating system supports environment variables (essentially, anything but MacOS), GP checks whether the environment variable GPRC is set. Under DOS, you can set it in AUTOEXEC.BAT. On Unix, this can be done with something like:

GPRC=/my/dir/anyname; export GPRC | in sh syntax (for instance in your .profile), |

setenv GPRC /my/dir/anyname | in csh syntax (in your .login or .cshrc file). |

If so, the file named by $GPRC is the gprc.

• If GPRC is not set, and if the environment variable HOME is defined, GP then tries

$HOME/.gprc on a Unix system

$HOME\_ gprc on a DOS, OS/2, or Windows system.

• If HOME also leaves us clueless, we try

~/.gprc on a Unix system (where as usual ~ stands for your home directory), or

\_ gprc on a DOS, OS/2, or Windows system.

• Finally, if no gprc was found among the user files mentioned above we look for /etc/gprc (\etc\gprc) for a system-wide gprc file (you’ll need root privileges to set up such a file yourself).

Note that on Unix systems, the gprc’s default name starts with a ’.’ and thus is hidden to regular ls commands; you need to type ls -a to see whether it’s already there without your knowing about it.

In any case, GP will open the corresponding file and process the commands in there, before doing anything else, e.g. creating the PARI stack. If the file doesn’t exist or cannot be read, GP will proceed to the initialization phase at once, eventually emitting a prompt. If any explicit commandline switches are given, they will override the values read from the gprc file.

The syntax in this file (and valid in this file only, at this very precise moment!) is simple-minded, but should be sufficient for most purposes. It is read line by line, white space being optional as usual (unless surrounded by quotes). Two types of lines are first dealt with by a preprocessor:

• comments are removed. This applies to all text surrounded by /* ... */ as well as everything following \\ on a given line.

• lines starting with #if keyword are treated as comments if keyword is not defined, and read normally otherwise. The condition can be negated using either #if not (or #if !). Only two keywords are recognized:

EMACS: defined if GP is running in an Emacs shell (see Section ??).

READL: defined if GP is compiled with readline support (see Section ??).

For instance you could set your prompt in the following portable way:

\\ self modifying prompt looking like ^I=10

%%

%% This is file `.tex',

%% generated with the docstrip utility.

%%

%% The original source files were:

%%

%% fileerr.dtx (with options: `return')

%%

%% This is a generated file.

%%

%% Copyright 1993 1994 1995 1996 1997 1998 1999 2000

%% The LaTeX3 Project and any individual authors listed elsewhere

%% in this file.

%%

%% This file was generated from file(s) of the Standard LaTeX `Tools Bundle'.

%% --------------------------------------------------------------------------

%%

%% It may be distributed and/or modified under the

%% conditions of the LaTeX Project Public License, either version 1.2

%% of this license or (at your option) any later version.

%% The latest version of this license is in

%% http://www.latex-project.org/lppl.txt

%% and version 1.2 or later is part of all distributions of LaTeX

%% version 1999/12/01 or later.

%%

%% This file may only be distributed together with a copy of the LaTeX

%% `Tools Bundle'. You may however distribute the LaTeX `Tools Bundle'

%% without such generated files.

%%

%% The list of all files belonging to the LaTeX `Tools Bundle' is

%% given in the file `manifest.txt'.

%%

usersch3

%%

%% This is file `.tex',

%% generated with the docstrip utility.

%%

%% The original source files were:

%%

%% fileerr.dtx (with options: `return')

%%

%% This is a generated file.

%%

%% Copyright 1993 1994 1995 1996 1997 1998 1999 2000

%% The LaTeX3 Project and any individual authors listed elsewhere

%% in this file.

%%

%% This file was generated from file(s) of the Standard LaTeX `Tools Bundle'.

%% --------------------------------------------------------------------------

%%

%% It may be distributed and/or modified under the

%% conditions of the LaTeX Project Public License, either version 1.2

%% of this license or (at your option) any later version.

%% The latest version of this license is in

%% http://www.latex-project.org/lppl.txt

%% and version 1.2 or later is part of all distributions of LaTeX

%% version 1999/12/01 or later.

%%

%% This file may only be distributed together with a copy of the LaTeX

%% `Tools Bundle'. You may however distribute the LaTeX `Tools Bundle'

%% without such generated files.

%%

%% The list of all files belonging to the LaTeX `Tools Bundle' is

%% given in the file `manifest.txt'.

%%

usersch4

%%

%% This is file `.tex',

%% generated with the docstrip utility.

%%

%% The original source files were:

%%

%% fileerr.dtx (with options: `return')

%%

%% This is a generated file.

%%

%% Copyright 1993 1994 1995 1996 1997 1998 1999 2000

%% The LaTeX3 Project and any individual authors listed elsewhere

%% in this file.

%%

%% This file was generated from file(s) of the Standard LaTeX `Tools Bundle'.

%% --------------------------------------------------------------------------

%%

%% It may be distributed and/or modified under the

%% conditions of the LaTeX Project Public License, either version 1.2

%% of this license or (at your option) any later version.

%% The latest version of this license is in

%% http://www.latex-project.org/lppl.txt

%% and version 1.2 or later is part of all distributions of LaTeX

%% version 1999/12/01 or later.

%%

%% This file may only be distributed together with a copy of the LaTeX

%% `Tools Bundle'. You may however distribute the LaTeX `Tools Bundle'

%% without such generated files.

%%

%% The list of all files belonging to the LaTeX `Tools Bundle' is

%% given in the file `manifest.txt'.

%%

usersch5

%%

%% This is file `.tex',

%% generated with the docstrip utility.

%%

%% The original source files were:

%%

%% fileerr.dtx (with options: `return')

%%

%% This is a generated file.

%%

%% Copyright 1993 1994 1995 1996 1997 1998 1999 2000

%% The LaTeX3 Project and any individual authors listed elsewhere

%% in this file.

%%

%% This file was generated from file(s) of the Standard LaTeX `Tools Bundle'.

%% --------------------------------------------------------------------------

%%

%% It may be distributed and/or modified under the

%% conditions of the LaTeX Project Public License, either version 1.2

%% of this license or (at your option) any later version.

%% The latest version of this license is in

%% http://www.latex-project.org/lppl.txt

%% and version 1.2 or later is part of all distributions of LaTeX

%% version 1999/12/01 or later.

%%

%% This file may only be distributed together with a copy of the LaTeX

%% `Tools Bundle'. You may however distribute the LaTeX `Tools Bundle'

%% without such generated files.

%%

%% The list of all files belonging to the LaTeX `Tools Bundle' is

%% given in the file `manifest.txt'.

%%

appa

%%

%% This is file `.tex',

%% generated with the docstrip utility.

%%

%% The original source files were:

%%

%% fileerr.dtx (with options: `return')

%%

%% This is a generated file.

%%

%% Copyright 1993 1994 1995 1996 1997 1998 1999 2000

%% The LaTeX3 Project and any individual authors listed elsewhere

%% in this file.

%%

%% This file was generated from file(s) of the Standard LaTeX `Tools Bundle'.

%% --------------------------------------------------------------------------

%%

%% It may be distributed and/or modified under the

%% conditions of the LaTeX Project Public License, either version 1.2

%% of this license or (at your option) any later version.

%% The latest version of this license is in

%% http://www.latex-project.org/lppl.txt

%% and version 1.2 or later is part of all distributions of LaTeX

%% version 1999/12/01 or later.

%%

%% This file may only be distributed together with a copy of the LaTeX

%% `Tools Bundle'. You may however distribute the LaTeX `Tools Bundle'

%% without such generated files.

%%

%% The list of all files belonging to the LaTeX `Tools Bundle' is

%% given in the file `manifest.txt'.

%%

appb

%%

%% This is file `.tex',

%% generated with the docstrip utility.

%%

%% The original source files were:

%%

%% fileerr.dtx (with options: `return')

%%

%% This is a generated file.

%%

%% Copyright 1993 1994 1995 1996 1997 1998 1999 2000

%% The LaTeX3 Project and any individual authors listed elsewhere

%% in this file.

%%

%% This file was generated from file(s) of the Standard LaTeX `Tools Bundle'.

%% --------------------------------------------------------------------------

%%

%% It may be distributed and/or modified under the

%% conditions of the LaTeX Project Public License, either version 1.2

%% of this license or (at your option) any later version.

%% The latest version of this license is in

%% http://www.latex-project.org/lppl.txt

%% and version 1.2 or later is part of all distributions of LaTeX

%% version 1999/12/01 or later.

%%

%% This file may only be distributed together with a copy of the LaTeX

%% `Tools Bundle'. You may however distribute the LaTeX `Tools Bundle'

%% without such generated files.

%%

%% The list of all files belonging to the LaTeX `Tools Bundle' is

%% given in the file `manifest.txt'.

%%