Programming in GP: control statements

break({n = 1})

Interrupts execution of current seq, and immediately exits from the n innermost enclosing loops, within the current function call (or the top level loop); the integer n must be positive. If n is greater than the number of enclosing loops, all enclosing loops are exited.


breakpoint()

Interrupt the program and enter the breakloop. The program continues when the breakloop is exited.

  ? f(N,x)=my(z=x^2+1);breakpoint();gcd(N,z^2+1-z);
  ? f(221,3)
    ***   at top-level: f(221,3)
    ***                 ^--------
    ***   in function f: my(z=x^2+1);breakpoint();gcd(N,z
    ***                              ^--------------------
    ***   Break loop: type <Return> to continue; 'break' to go back to GP
  break> z
  10
  break>
  %2 = 13


dbg_down({n = 1})

(In the break loop) go down n frames. This allows to cancel a previous call to dbg_up.


dbg_err()

In the break loop, return the error data of the current error, if any. See iferr for details about error data. Compare:

  ? iferr(1/(Mod(2,12019)^(6!)-1),E,Vec(E))
  %1 = ["e_INV", "Fp_inv", Mod(119, 12019)]
  ? 1/(Mod(2,12019)^(6!)-1)
    ***   at top-level: 1/(Mod(2,12019)^(6!)-
    ***                  ^--------------------
    *** _/_: impossible inverse in Fp_inv: Mod(119, 12019).
    ***   Break loop: type 'break' to go back to GP prompt
  break> Vec(dbg_err())
  ["e_INV", "Fp_inv", Mod(119, 12019)]


dbg_up({n = 1})

(In the break loop) go up n frames. This allows to inspect data of the parent function. To cancel a dbg_up call, use dbg_down


dbg_x(A{,n})

Print the inner structure of A, complete if n is omitted, up to level n otherwise. This is useful for debugging. This is similar to \x but does not require A to be an history entry. In particular, it can be used in the break loop.


for(X = a,b,seq)

Evaluates seq, where the formal variable X goes from a to b. Nothing is done if a > b. a and b must be in R.


forcomposite(n = a,{b},seq)

Evaluates seq, where the formal variable n ranges over the composite numbers between the non-negative real numbers a to b, including a and b if they are composite. Nothing is done if a > b.

  ? forcomposite(n = 0, 10, print(n))
  4
  6
  8
  9
  10
Omitting b means we will run through all composites >= a, starting an infinite loop; it is expected that the user will break out of the loop himself at some point, using break or return.

Note that the value of n cannot be modified within seq:

  ? forcomposite(n = 2, 10, n = [])
   ***   at top-level: forcomposite(n=2,10,n=[])
   ***                                      ^---
   ***   index read-only: was changed to [].


fordiv(n,X,seq)

Evaluates seq, where the formal variable X ranges through the divisors of n (see divisors, which is used as a subroutine). It is assumed that factor can handle n, without negative exponents. Instead of n, it is possible to input a factorization matrix, i.e. the output of factor(n).

This routine uses divisors as a subroutine, then loops over the divisors. In particular, if n is an integer, divisors are sorted by increasing size.

To avoid storing all divisors, possibly using a lot of memory, the following (much slower) routine loops over the divisors using essentially constant space:

  FORDIV(N)=
  { my(P, E);
  
    P = factor(N); E = P[,2]; P = P[,1];
    forvec( v = vector(#E, i, [0,E[i]]),
    X = factorback(P, v)
    \\ ...
  );
  }
  ? for(i=1,10^5, FORDIV(i))
  time = 3,445 ms.
  ? for(i=1,10^5, fordiv(i, d, ))
  time = 490 ms.


forell(E,a,b,seq)

Evaluates seq, where the formal variable E = [name, M, G] ranges through all elliptic curves of conductors from a to b. In this notation name is the curve name in Cremona's elliptic curve database, M is the minimal model, G is a Z-basis of the free part of the Mordell-Weil group E(Q).

  ? forell(E, 1, 500, my([name,M,G] = E); \
      if (#G > 1, print(name)))
  389a1
  433a1
  446d1

The elldata database must be installed and contain data for the specified conductors.

The library syntax is forell(void *data, long (*call)(void*,GEN), long a, long b).


forpart(X = k,seq,{a = k},{n = k})

Evaluate seq over the partitions X = [x_1,...x_n] of the integer k, i.e. increasing sequences x_1 <= x_2... <= x_n of sum x_1+...+ x_n = k. By convention, 0 admits only the empty partition and negative numbers have no partitions. A partition is given by a t_VECSMALL, where parts are sorted in nondecreasing order:

  ? forpart(X=3, print(X))
  Vecsmall([3])
  Vecsmall([1, 2])
  Vecsmall([1, 1, 1])
Optional parameters n and a are as follows:

* n = nmax (resp. n = [nmin,nmax]) restricts partitions to length less than nmax (resp. length between nmin and nmax), where the length is the number of nonzero entries.

* a = amax (resp. a = [amin,amax]) restricts the parts to integers less than amax (resp. between amin and amax).

By default, parts are positive and we remove zero entries unless amin <= 0, in which case X is of constant length nmax.

  \\ at most 3 non-zero parts, all <= 4
  ? forpart(v=5,print(Vec(v)),4,3)
  [1, 4]
  [2, 3]
  [1, 1, 3]
  [1, 2, 2]
  
  \\ between 2 and 4 parts less than 5, fill with zeros
  ? forpart(v=5,print(Vec(v)),[0,5],[2,4])
  [0, 0, 1, 4]
  [0, 0, 2, 3]
  [0, 1, 1, 3]
  [0, 1, 2, 2]
  [1, 1, 1, 2]

The behaviour is unspecified if X is modified inside the loop.

The library syntax is forpart(void *data, long (*call)(void*,GEN), long k, GEN a, GEN n).


forprime(p = a,{b},seq)

Evaluates seq, where the formal variable p ranges over the prime numbers between the real numbers a to b, including a and b if they are prime. More precisely, the value of p is incremented to nextprime(p + 1), the smallest prime strictly larger than p, at the end of each iteration. Nothing is done if a > b.

  ? forprime(p = 4, 10, print(p))
  5
  7
Omitting b means we will run through all primes >= a, starting an infinite loop; it is expected that the user will break out of the loop himself at some point, using break or return.

Note that the value of p cannot be modified within seq:

  ? forprime(p = 2, 10, p = [])
   ***   at top-level: forprime(p=2,10,p=[])
   ***                                   ^---
   ***   prime index read-only: was changed to [].


forstep(X = a,b,s,seq)

Evaluates seq, where the formal variable X goes from a to b, in increments of s. Nothing is done if s > 0 and a > b or if s < 0 and a < b. s must be in R^* or a vector of steps [s_1,...,s_n]. In the latter case, the successive steps are used in the order they appear in s.

  ? forstep(x=5, 20, [2,4], print(x))
  5
  7
  11
  13
  17
  19


forsubgroup(H = G,{bound},seq)

Evaluates seq for each subgroup H of the abelian group G (given in SNF form or as a vector of elementary divisors).

If bound is present, and is a positive integer, restrict the output to subgroups of index less than bound. If bound is a vector containing a single positive integer B, then only subgroups of index exactly equal to B are computed

The subgroups are not ordered in any obvious way, unless G is a p-group in which case Birkhoff's algorithm produces them by decreasing index. A subgroup is given as a matrix whose columns give its generators on the implicit generators of G. For example, the following prints all subgroups of index less than 2 in G = Z/2Z g_1 x Z/2Z g_2:

  ? G = [2,2]; forsubgroup(H=G, 2, print(H))
  [1; 1]
  [1; 2]
  [2; 1]
  [1, 0; 1, 1]

The last one, for instance is generated by (g_1, g_1 + g_2). This routine is intended to treat huge groups, when subgrouplist is not an option due to the sheer size of the output.

For maximal speed the subgroups have been left as produced by the algorithm. To print them in canonical form (as left divisors of G in HNF form), one can for instance use

  ? G = matdiagonal([2,2]); forsubgroup(H=G, 2, print(mathnf(concat(G,H))))
  [2, 1; 0, 1]
  [1, 0; 0, 2]
  [2, 0; 0, 1]
  [1, 0; 0, 1]

Note that in this last representation, the index [G:H] is given by the determinant. See galoissubcyclo and galoisfixedfield for applications to Galois theory.

The library syntax is forsubgroup(void *data, long (*call)(void*,GEN), GEN G, GEN bound).


forvec(X = v,seq,{flag = 0})

Let v be an n-component vector (where n is arbitrary) of two-component vectors [a_i,b_i] for 1 <= i <= n. This routine evaluates seq, where the formal variables X[1],..., X[n] go from a_1 to b_1,..., from a_n to b_n, i.e. X goes from [a_1,...,a_n] to [b_1,...,b_n] with respect to the lexicographic ordering. (The formal variable with the highest index moves the fastest.) If flag = 1, generate only nondecreasing vectors X, and if flag = 2, generate only strictly increasing vectors X.

The type of X is the same as the type of v: t_VEC or t_COL.


if(a,{seq1},{seq2})

Evaluates the expression sequence seq1 if a is non-zero, otherwise the expression seq2. Of course, seq1 or seq2 may be empty:

if (a,seq) evaluates seq if a is not equal to zero (you don't have to write the second comma), and does nothing otherwise,

if (a,,seq) evaluates seq if a is equal to zero, and does nothing otherwise. You could get the same result using the ! (not) operator: if (!a,seq).

The value of an if statement is the value of the branch that gets evaluated: for instance

  x = if(n % 4 == 1, y, z);
sets x to y if n is 1 modulo 4, and to z otherwise.

Successive 'else' blocks can be abbreviated in a single compound if as follows:

  if (test1, seq1,
      test2, seq2,
      ...
      testn, seqn,
      seqdefault);
is equivalent to

  if (test1, seq1
           , if (test2, seq2
                      , ...
                        if (testn, seqn, seqdefault)...));
For instance, this allows to write traditional switch / case constructions:

  if (x == 0, do0(),
      x == 1, do1(),
      x == 2, do2(),
      dodefault());

Remark. The boolean operators && and || are evaluated according to operator precedence as explained in Section [Label: se:operators], but, contrary to other operators, the evaluation of the arguments is stopped as soon as the final truth value has been determined. For instance

  if (x != 0 && f(1/x), ...)

is a perfectly safe statement.

Remark. Functions such as break and next operate on loops, such as forxxx, while, until. The if statement is not a loop. (Obviously!)


iferr(seq1,E,seq2{,pred})

Evaluates the expression sequence seq1. If an error occurs, set the formal parameter E set to the error data. If pred is not present or evaluates to true, catch the error and evaluate seq2. Both pred and seq2 can reference E. The error type is given by errname(E), and other data can be accessed using the component function. The code seq2 should check whether the error is the one expected. In the negative the error can be rethrown using error(E) (and possibly caught by an higher iferr instance). The following uses iferr to implement Lenstra's ECM factoring method

  ? ecm(N, B = 1000!, nb = 100)=
    {
      for(a = 1, nb,
        iferr(ellmul(ellinit([a,1]*Mod(1,N)), [0,1]*Mod(1,N), B),
          E, return(gcd(lift(component(E,2)),N)),
          errname(E)=="e_INV" && type(component(E,2)) == "t_INTMOD"))
    }
  ? ecm(2^101-1)
  %2 = 7432339208719

The return value of iferr itself is the value of seq2 if an error occurs, and the value of seq1 otherwise. We now describe the list of valid error types, and the associated error data E; in each case, we list in order the components of E, accessed via component(E,1), component(E,2), etc.

Internal errors, "system" errors.

* "e_ARCH". A requested feature s is not available on this architecture or operating system. E has one component (t_STR): the missing feature name s.

* "e_BUG". A bug in the PARI library, in function s. E has one component (t_STR): the function name s.

* "e_FILE". Error while trying to open a file. E has two components, 1 (t_STR): the file type (input, output, etc.), 2 (t_STR): the file name.

* "e_IMPL". A requested feature s is not implemented. E has one component, 1 (t_STR): the feature name s.

* "e_PACKAGE". Missing optional package s. E has one component, 1 (t_STR): the package name s.

Syntax errors, type errors.

* "e_DIM". The dimensions of arguments x and y submitted to function s does not match up. E.g., multiplying matrices of inconsistent dimension, adding vectors of different lengths,... E has three component, 1 (t_STR): the function name s, 2: the argument x, 3: the argument y.

* "e_FLAG". A flag argument is out of bounds in function s. E has one component, 1 (t_STR): the function name s.

* "e_NOTFUNC". Generated by the PARI evaluator; tried to use a GEN x which is not a t_CLOSURE in a function call syntax (as in f = 1; f(2);). E has one component, 1: the offending GEN x.

* "e_OP". Impossible operation between two objects than cannot be typecast to a sensible common domain for deeper reasons than a type mismatch, usually for arithmetic reasons. As in O(2) + O(3): it is valid to add two t_PADICs, provided the underlying prime is the same; so the addition is not forbidden a priori for type reasons, it only becomes so when inspecting the objects and trying to perform the operation. E has three components, 1 (t_STR): the operator name op, 2: first argument, 3: second argument.

* "e_TYPE". An argument x of function s had an unexpected type. (As in factor("blah").) E has two components, 1 (t_STR): the function name s, 2: the offending argument x.

* "e_TYPE2". Forbidden operation between two objects than cannot be typecast to a sensible common domain, because their types do not match up. (As in Mod(1,2) + Pi.) E has three components, 1 (t_STR): the operator name op, 2: first argument, 3: second argument.

* "e_PRIORITY". Object o in function s contains variables whose priority is incompatible with the expected operation. E.g. Pol([x,1], 'y): this raises an error because it's not possible to create a polynomial whose coefficients involve variables with higher priority than the main variable. E has four components: 1 (t_STR): the function name s, 2: the offending argument o, 3 (t_STR): an operator op describing the priority error, 4 (t_POL): the variable v describing the priority error. The argument satisfies variable(x) op variable(v).

* "e_VAR". The variables of arguments x and y submitted to function s does not match up. E.g., considering the algebraic number Mod(t,t^2+1) in nfinit(x^2+1). E has three component, 1 (t_STR): the function name s, 2 (t_POL): the argument x, 3 (t_POL): the argument y.

Overflows.

* "e_COMPONENT". Trying to access an inexistent component in a vector/matrix/list in a function: the index is less than 1 or greater than the allowed length. E has four components, 1 (t_STR): the function name 2 (t_STR): an operator op ( < or > ), 2 (t_GEN): a numerical limit l bounding the allowed range, 3 (GEN): the index x. It satisfies x op l.

* "e_DOMAIN". An argument is not in the function's domain. E has five components, 1 (t_STR): the function name, 2 (t_STR): the mathematical name of the out-of-domain argument 3 (t_STR): an operator op describing the domain error, 4 (t_GEN): the numerical limit l describing the domain error, 5 (GEN): the out-of-domain argument x. The argument satisfies x op l, which prevents it from belonging to the function's domain.

* "e_MAXPRIME". A function using the precomputed list of prime numbers ran out of primes. E has one component, 1 (t_INT): the requested prime bound, which overflowed primelimit or 0 (bound is unknown).

* "e_MEM". A call to pari_malloc or pari_realloc failed. E has no component.

* "e_OVERFLOW". An object in function s becomes too large to be represented within PARI's hardcoded limits. (As in 2^2^2^10 or exp(1e100), which overflow in lg and expo.) E has one component, 1 (t_STR): the function name s.

* "e_PREC". Function s fails because input accuracy is too low. (As in floor(1e100) at default accuracy.) E has one component, 1 (t_STR): the function name s.

* "e_STACK". The PARI stack overflows. E has no component.

Errors triggered intentionally.

* "e_ALARM". A timeout, generated by the alarm function. E has one component (t_STR): the error message to print.

* "e_USER". A user error, as triggered by error(g_1,...,g_n). E has one component, 1 (t_VEC): the vector of n arguments given to error.

Mathematical errors.

* "e_CONSTPOL". An argument of function s is a constant polynomial, which does not make sense. (As in galoisinit(Pol(1)).) E has one component, 1 (t_STR): the function name s.

* "e_COPRIME". Function s expected coprime arguments, and did receive x,y, which were not. E has three component, 1 (t_STR): the function name s, 2: the argument x, 3: the argument y.

* "e_INV". Tried to invert a non-invertible object x in function s. E has two components, 1 (t_STR): the function name s, 2: the non-invertible x. If x = Mod(a,b) is a t_INTMOD and a is not 0 mod b, this allows to factor the modulus, as gcd(a,b) is a non-trivial divisor of b.

* "e_IRREDPOL". Function s expected an irreducible polynomial, and did receive T, which was not. (As in nfinit(x^2-1).) E has two component, 1 (t_STR): the function name s, 2 (t_POL): the polynomial x.

* "e_MISC". Generic uncategorized error. E has one component (t_STR): the error message to print.

* "e_MODULUS". moduli x and y submitted to function s are inconsistent. As in

     nfalgtobasis(nfinit(t^3-2), Mod(t,t^2+1)

E has three component, 1 (t_STR): the function s, 2: the argument x, 3: the argument x.

* "e_NEGVAL". An argument of function s is a power series with negative valuation, which does not make sense. (As in cos(1/x).) E has one component, 1 (t_STR): the function name s.

* "e_PRIME". Function s expected a prime number, and did receive p, which was not. (As in idealprimedec(nf, 4).) E has two component, 1 (t_STR): the function name s, 2: the argument p.

* "e_ROOTS0". An argument of function s is a zero polynomial, and we need to consider its roots. (As in polroots(0).) E has one component, 1 (t_STR): the function name s.

* "e_SQRTN". Trying to compute an n-th root of x, which does not exist, in function s. (As in sqrt(Mod(-1,3)).) E has two components, 1 (t_STR): the function name s, 2: the argument x.


next({n = 1})

Interrupts execution of current seq, resume the next iteration of the innermost enclosing loop, within the current function call (or top level loop). If n is specified, resume at the n-th enclosing loop. If n is bigger than the number of enclosing loops, all enclosing loops are exited.


return({x = 0})

Returns from current subroutine, with result x. If x is omitted, return the (void) value (return no result, like print).


until(a,seq)

Evaluates seq until a is not equal to 0 (i.e. until a is true). If a is initially not equal to 0, seq is evaluated once (more generally, the condition on a is tested after execution of the seq, not before as in while).


while(a,seq)

While a is non-zero, evaluates the expression sequence seq. The test is made before evaluating the seq, hence in particular if a is initially equal to zero the seq will not be evaluated at all.