source: sage/libs/pari/gen.pyx @ 2555:98bce602990d

Revision 2555:98bce602990d, 178.1 KB checked in by Nick Alexander <ncalexander@…>, 6 years ago (diff)

Add is_pseudoprime to arith and integer; calls PARI's gispseudoprime internally.

Line 
1"""
2PARI C-library interface
3
4AUTHORS:
5    -- William Stein (2006-03-01): updated to work with PARI 2.2.12-beta
6             (this involved changing almost every doc strings, among other
7             things; the precision behavior of PARI seems to change
8             from any version to the next...).
9    -- William Stein (2006-03-06): added newtonpoly
10    -- Justin Walker: contributed some of the function definitions
11    -- Gonzalo Tornari: improvements to conversions; much better error handling.
12"""
13
14import math
15import types
16from sage.misc.misc import xsrange
17import sage.structure.coerce
18import operator
19
20include 'pari_err.pxi'
21include 'setlvalue.pxi'
22include '../../ext/stdsage.pxi'
23
24# The unique running Pari instance.
25cdef PariInstance pari_instance, P
26#pari_instance = PariInstance(200000000, 500000)
27#pari_instance = PariInstance(100000000, 500000)
28pari_instance = PariInstance(75000000, 500000)
29#pari_instance = PariInstance(50000000, 500000)
30P = pari_instance   # shorthand notation
31
32# so Galois groups are represented in a sane way
33# See the polgalois section of the PARI users manual.
34new_galois_format = 1   
35
36# keep track of the stack
37cdef pari_sp stack_avma
38
39# real precision
40cdef unsigned long prec
41prec = GP_DATA.fmt.sigd
42
43# Also a copy of PARI accessible from external pure python code.
44pari = pari_instance
45
46# temp variables
47cdef GEN t0,t1,t2,t3,t4
48
49cdef t0GEN(x):
50    global t0
51    t0 = P.toGEN(x)
52   
53cdef t1GEN(x):
54    global t1
55    t1 = P.toGEN(x)
56   
57cdef t2GEN(x):
58    global t2
59    t2 = P.toGEN(x)
60   
61cdef t3GEN(x):
62    global t3
63    t3 = P.toGEN(x)
64   
65cdef t4GEN(x):
66    global t4
67    t4 = P.toGEN(x)
68
69cdef class gen:
70    """
71    Python extension class that models the PARI GEN type.
72    """
73    def __init__(self):
74        self.b = 0
75        self.refers_to = {}
76
77    def parent(self):
78        return pari_instance
79       
80    cdef void init(self, GEN g, pari_sp b):
81        """
82            g -- PARI GEN
83            b -- pointer to memory chunk where PARI gen lives
84                 (if nonzero then this memory is freed when the object
85                  goes out of scope)
86        """
87        self.g = g
88        self.b = b
89
90    def __dealloc__(self):
91        if self.b:
92            sage_free(<void*> self.b)
93
94    def __repr__(self):
95        return P.GEN_to_str(self.g)
96
97    def __hash__(self):
98        return hash(P.GEN_to_str(self.g))
99
100    def _testclass(self):
101        import test
102        T = test.testclass()
103        T._init(self)
104        return T
105
106    cdef GEN _gen(self):
107        return self.g
108   
109    def list(self):
110        if typ(self.g) == t_POL:
111            raise NotImplementedError, \
112                "please report, t_POL.list() is broken, should not be used!"
113        if typ(self.g) == t_SER:
114            raise NotImplementedError, \
115                "please report, t_SER.list() is broken, should not be used!"
116        #return list(self.Vecrev())
117        return list(self.Vec())
118       
119    def __reduce__(self):
120        s = str(self)
121        import sage.libs.pari.gen_py
122        return sage.libs.pari.gen_py.pari, (s,)
123
124    def _add(gen self, gen other):
125        _sig_on
126        return P.new_gen(gadd(self.g, other.g))
127
128    def _sub(gen self, gen other):
129        _sig_on
130        return P.new_gen(gsub(self.g, other.g))
131
132    def _mul(gen self, gen other):
133        _sig_on
134        return P.new_gen(gmul(self.g, other.g))
135
136    def _mod(gen self, gen other):
137        _sig_on
138        return P.new_gen(gmod(self.g, other.g))
139
140    def _div(gen self, gen other):
141        _sig_on
142        return P.new_gen(gdiv(self.g, other.g))
143
144    def __add__(self, other):
145        if isinstance(self, gen) and isinstance(other, gen):
146            return self._add(other)
147        return sage.structure.coerce.bin_op(self, other, operator.add)
148
149    def __sub__(self, other):
150        if isinstance(self, gen) and isinstance(other, gen):
151            return self._sub(other)
152        return sage.structure.coerce.bin_op(self, other, operator.sub)
153
154    def __mul__(self, other):
155        if isinstance(self, gen) and isinstance(other, gen):
156            return self._mul(other)
157        return sage.structure.coerce.bin_op(self, other, operator.mul)
158
159    def __div__(self, other):
160        if isinstance(self, gen) and isinstance(other, gen):
161            return self._div(other)
162        return sage.structure.coerce.bin_op(self, other, operator.div)
163
164    def __mod__(self, other):
165        if isinstance(self, gen) and isinstance(other, gen):
166            return self._mod(other)
167        return sage.structure.coerce.bin_op(self, other, operator.mod)
168
169    def __pow__(self, n, m):
170        t0GEN(self)
171        t1GEN(n)
172        _sig_on
173        return P.new_gen(gpow(t0, t1, prec))
174
175    def __neg__(gen self):
176        _sig_on
177        return P.new_gen(gneg(self.g))
178
179    def __xor__(gen self, n):
180        raise RuntimeError, "Use ** for exponentiation, not '^', which means xor\n"+\
181              "in Python, and has the wrong precedence."
182
183    def __rshift__(gen self, long n):
184        _sig_on
185        return P.new_gen(gshift(self.g, -n))
186
187    def __lshift__(gen self, long n):
188        _sig_on       
189        return P.new_gen(gshift(self.g, n))
190
191    def __invert__(gen self):
192        _sig_on       
193        return P.new_gen(ginv(self.g))
194
195    ###########################################
196    # ACCESS
197    ###########################################
198    #def __getattr__(self, attr):
199    def getattr(self, attr):
200        t0GEN(str(self) + '.' + str(attr))
201        return self.new_gen(t0)
202
203    def __getitem__(gen self, n):
204        """
205        Return a *copy* of the nth entry.
206
207        The indexing is 0-based, like in Python.  However, *copying*
208        the nth entry instead of returning reference is different
209        than what one usually does in Python.  However, we do it
210        this way for consistency with the PARI/GP interpreter, which
211        does make copies.
212
213        EXAMPLES:
214            sage: p = pari('1 + 2*x + 3*x^2')
215            sage: p[0]
216            1
217            sage: p[2]
218            3
219            sage: p[100]
220            0
221            sage: p[-1]
222            0
223            sage: q = pari('x^2 + 3*x^3 + O(x^6)')
224            sage: q[3]
225            3
226            sage: q[5]
227            0
228            sage: q[6]
229            Traceback (most recent call last):
230            ...
231            IndexError: index out of bounds
232            sage: m = pari('[1,2;3,4]')
233            sage: m[0]
234            [1, 3]~
235            sage: m[1,0]
236            3
237            sage: l = pari('List([1,2,3])')
238            sage: l[1]
239            2
240            sage: s = pari('"hello, world!"')
241            sage: s[0]
242            'h'
243            sage: s[4]
244            'o'
245            sage: s[12]
246            '!'
247            sage: s[13]
248            Traceback (most recent call last):
249            ...
250            IndexError: index out of bounds
251            sage: v = pari('[1,2,3]')
252            sage: v[0]
253            1
254            sage: c = pari('Col([1,2,3])')
255            sage: c[1]
256            2
257            sage: sv = pari('Vecsmall([1,2,3])')
258            sage: sv[2]
259            3
260            sage: type(sv[2])
261            <type 'int'>
262            sage: tuple(pari(3/5))
263            (3, 5)
264            sage: tuple(pari('1 + 5*I'))
265            (1, 5)
266            sage: tuple(pari('Qfb(1, 2, 3)'))
267            (1, 2, 3)
268            sage: pari(57)[0]
269            Traceback (most recent call last):
270            ...
271            TypeError: unindexable object
272
273        """
274        if typ(self.g) in (t_INT, t_REAL, t_PADIC, t_QUAD):
275            # these are definitely scalar!
276            raise TypeError, "unindexable object"
277
278        if typ(self.g) in (t_INTMOD, t_POLMOD):
279            # if we keep going we would get:
280            #   [0] = modulus
281            #   [1] = lift to t_INT or t_POL
282            # do we want this? maybe the other way around?
283            raise TypeError, "unindexable object"
284
285        #if typ(self.g) in (t_FRAC, t_RFRAC):
286            # generic code gives us:
287            #   [0] = numerator
288            #   [1] = denominator
289
290        #if typ(self.g) == t_COMPLEX:
291            # generic code gives us
292            #   [0] = real part
293            #   [1] = imag part
294
295        #if type(self.g) in (t_QFR, t_QFI):
296            # generic code works ok
297
298        if typ(self.g) == t_POL:
299            return self.polcoeff(n)
300
301        if typ(self.g) == t_SER:
302            bound = valp(self.g) + lg(self.g) - 2
303            if n >= bound:
304                raise IndexError, "index out of bounds"
305            return self.polcoeff(n)
306       
307        if isinstance(n, tuple):
308            if typ(self.g) != t_MAT:
309                raise TypeError, "an integer is required"
310            if len(n) != 2:
311                raise TypeError, "index must be an integer or a 2-tuple (i,j)"
312            i, j = n[0], n[1]
313            if i < 0 or i >= self.nrows():
314                raise IndexError, "row index out of bounds"
315            if j < 0 or j >= self.ncols():
316                raise IndexError, "column index out of bounds"
317            return P.new_ref(gmael(self.g,j+1,i+1), self)
318       
319        if n < 0 or n >= glength(self.g):
320            raise IndexError, "index out of bounds"
321        if typ(self.g) == t_LIST:
322            return P.new_ref(gel(self.g,n+2), self)
323        if typ(self.g) == t_STR:
324            return chr( (<char *>(self.g+1))[n] )
325        if typ(self.g) == t_VECSMALL:
326            return self.g[n+1]
327        return P.new_ref(gel(self.g,n+1), self)
328   
329
330    def __getslice__(self,  Py_ssize_t i,  Py_ssize_t j):
331        """
332        EXAMPLES:
333            sage: v = pari(xrange(20))
334            sage: v[2:5]
335            [2, 3, 4]
336            sage: v[:]
337            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
338            sage: v[10:]
339            [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
340            sage: v[:5]
341            [0, 1, 2, 3, 4]
342            sage: v
343            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
344            sage: v[-1]
345            Traceback (most recent call last):
346            ...
347            IndexError: index out of bounds
348            sage: v[:-3]
349            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
350            sage: v[5:]
351            [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
352        """
353        cdef long l, k
354        l = glength(self.g)
355        if j >= l: j = l
356        if i < 0: i = 0
357        if j <= i: return P.vector(0)
358        v = P.vector(j-i)
359        for k from i <= k < j:
360            v[k-i] = self[k]
361        return v
362
363    def __setitem__(gen self, n, y):
364        r"""
365        Set the nth entry to a reference to y. 
366       
367        \begin{notice}
368        \begin{itemize}
369            \item There is a known BUG: If v is a vector and entry i of v is a vector,
370                       \code{v[i][j] = x}
371               should set entry j of v[i] to x.  Instead it sets it to nonsense.
372               I do not understand why this occurs.  The following is a safe way
373               to do the same thing:
374                        \code{tmp = v[i]; tmp[j] = x    }
375       
376            \item The indexing is 0-based, like everywhere else in Python, but
377               {\em unlike} in GP/PARI.
378           
379            \item Assignment sets the nth entry to a reference to y,
380               assuming y is an object of type gen.  This is the same
381               as in Python, but {\em different} than what happens in the
382               gp interpreter, where assignment makes a copy of y.
383
384            \item Because setting creates references it is {\em possible} to
385               make circular references, unlike in GP.  Do {\em not} do
386               this (see the example below).  If you need circular
387               references, work at the Python level (where they work
388               well), not the PARI object level.
389        \end{itemize}
390        \end{notice}
391
392        EXAMPLES:
393            sage: v = pari(range(10))
394            sage: v
395            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
396            sage: v[0] = 10
397            sage: w = pari([5,8,-20])
398            sage: v
399            [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
400            sage: v[1] = w
401            sage: v
402            [10, [5, 8, -20], 2, 3, 4, 5, 6, 7, 8, 9]
403            sage: w[0] = -30
404            sage: v
405            [10, [-30, 8, -20], 2, 3, 4, 5, 6, 7, 8, 9]
406            sage: t = v[1]; t[1] = 10   # don't do v[1][1] !!! (because of mysterious BUG...)
407            sage: v
408            [10, [-30, 10, -20], 2, 3, 4, 5, 6, 7, 8, 9]
409            sage: w
410            [-30, 10, -20]
411           
412        Finally, we create a circular reference:
413            sage: v = pari([0])
414            sage: w = pari([v])
415            sage: v
416            [0]
417            sage: w
418            [[0]]
419            sage: v[0] = w
420            sage: # Now there is a circular reference.  Trying to access v[0] will crash SAGE.
421
422        """
423        cdef gen x
424        _sig_on
425        x = pari(y)
426        if isinstance(n, tuple):
427            self.refers_to[n] = x
428            i = n[0]
429            j = n[1]
430            if i < 0 or i >= self.nrows():
431                raise IndexError, "row i(=%s) must be between 0 and %s"%(i,self.nrows())
432            if j < 0 or j >= self.ncols():
433                raise IndexError, "column j(=%s) must be between 0 and %s"%(j,self.ncols())
434            (<GEN>(self.g)[j+1])[i+1] = <long> x.g
435            return
436
437        if n < 0 or n >= glength(self.g):
438            raise IndexError, "index (%s) must be between 0 and %s"%(n,glength(self.g)-1)
439       
440        self.refers_to[n] = x       # so python memory manager will work correctly
441                                    # and not free x if PARI part of self is the
442                                    # only thing pointing to it.
443
444        if typ(self.g) == t_POL:
445            n = n + 1
446        (self.g)[n+1] = <long>(x.g)
447
448    def __len__(gen self):
449        return glength(self.g)
450
451       
452
453    ###########################################
454    # ?
455    ###########################################
456   
457    def __cmp__(gen self, gen other):
458        """
459        Comparisons
460
461        Compares the underlying strings unless the inputs
462        are integer, real, or fraction (quotient of integers).
463        """
464        if gegal(self.g, other.g):
465            return 0
466        cdef int tg, to, a
467        tg = typ(self.g)
468        to = typ(other.g)
469
470        cdef int t_g, t_o
471        t_g = typ(self.g); t_o = typ(other.g)
472        if (t_g == t_INT or t_g == t_REAL or t_g == t_FRAC) and \
473           (t_o == t_INT or t_g == t_REAL or t_g == t_FRAC):
474            return gcmp(self.g, other.g)
475
476        return cmp(str(self),str(other))
477
478    def __richcmp__(gen self, other, int op):
479        """
480        EXAMPLES:
481            sage: a = pari(5)
482            sage: b = 10
483            sage: a < b
484            True
485            sage: a <= b
486            True
487            sage: a <= 5
488            True
489            sage: a > b
490            False
491            sage: a >= b
492            False
493            sage: a >= pari(10)
494            False
495            sage: a == 5
496            True
497            sage: a is 5
498            False
499        """
500        cdef int n
501        cdef gen x
502        x = P.adapt(other)
503        n = self.__cmp__(x)
504        if op == 0:
505            return bool(n < 0)
506        elif op == 1:
507            return bool(n <= 0)
508        elif op == 2:
509            return bool(n == 0)
510        elif op == 3:
511            return bool(n != 0)
512        elif op == 4:
513            return bool(n > 0)
514        elif op == 5:
515            return bool(n >= 0)
516
517    def copy(gen self):
518        return P.new_gen(forcecopy(self.g))
519
520
521    ###########################################
522    # Conversion --> Python
523    # Try to convert to a meaningful python object
524    # in various ways
525    ###########################################
526
527    def list_str(gen self):
528        """
529        Return str that might correctly evaluate to a Python-list.
530        """
531        s = str(self)
532        if s[:4] == "Mat(":
533            s = "[" + s[4:-1] + "]"
534        s = s.replace("~","")
535        if s.find(";") != -1:
536            s = s.replace(";","], [")
537            s = "[" + s + "]"
538            return eval(s)
539        else:
540            return eval(s)
541
542    def __hex__(gen self):
543        """
544        Return the hexadecimal digits of self in lower case.
545
546        EXAMPLES:
547            sage: print hex(pari(0))
548            0
549            sage: print hex(pari(15))
550            f
551            sage: print hex(pari(16))
552            10
553            sage: print hex(pari(16938402384092843092843098243))
554            36bb1e3929d1a8fe2802f083
555            sage: print hex(long(16938402384092843092843098243))
556            0x36bb1e3929d1a8fe2802f083L
557            sage: print hex(pari(-16938402384092843092843098243))
558            -36bb1e3929d1a8fe2802f083
559        """
560        cdef GEN x
561        cdef long lx, *xp
562        cdef long w
563        cdef char *s, *sp
564        cdef char *hexdigits
565        hexdigits = "0123456789abcdef"
566        cdef int i, j
567        cdef int size
568        x = self.g
569        if typ(x) != t_INT:
570            raise TypeError, "gen must be of PARI type t_INT"
571        if not signe(x):
572            return "0"
573        lx = lgefint(x)-2  # number of words
574        size = lx*2*BYTES_IN_LONG
575        s = <char *>sage_malloc(size+2) # 1 char for sign, 1 char for '\0'
576        sp = s + size+1
577        sp[0] = 0
578        xp = int_LSW(x)
579        for i from 0 <= i < lx:
580            w = xp[0]
581            for j from 0 <= j < 2*BYTES_IN_LONG:
582                sp = sp-1
583                sp[0] = hexdigits[w & 15]
584                w = w>>4
585            xp = int_nextW(xp)
586        # remove leading zeros!
587        while sp[0] == c'0':
588            sp = sp+1
589        if signe(x) < 0:
590            sp = sp-1
591            sp[0] = c'-'
592        k = sp
593        sage_free(s)
594        return k
595       
596    def __int__(gen self):
597        """
598        Return Python int.  Very fast, and if the number is too large to
599        fit into a C int, a Python long is returned instead.
600
601        EXAMPLES:
602
603            sage: int(pari(0))
604            0
605            sage: int(pari(10))
606            10
607            sage: int(pari(-10))
608            -10
609            sage: int(pari(123456789012345678901234567890))
610            123456789012345678901234567890L
611            sage: int(pari(-123456789012345678901234567890))
612            -123456789012345678901234567890L
613            sage: int(pari(2^31-1))
614            2147483647
615            sage: int(pari(-2^31))
616            -2147483648
617        """
618        cdef GEN x
619        cdef long lx, *xp
620        if  typ(self.g)==t_POL and self.poldegree()<=0:
621            # this is a work around for the case that e.g.
622            # GF(q).random_element() returns zero, which is of type
623            # t_POL(MOD)
624            x = polcoeff0(self.g,0,self.get_var(-1))
625        else:
626            x = self.g
627        if typ(x) != t_INT:
628            raise TypeError, "gen must be of PARI type t_INT or t_POL of degree 0"
629        if not signe(x):
630            return 0
631        lx = lgefint(x)-3   # take 1 to account for the MSW
632        xp = int_MSW(x)
633        # special case 1 word so we return int if it fits
634        if not lx:
635            if   signe(x) |  xp[0] > 0:     # both positive
636                return xp[0]
637            elif signe(x) & -xp[0] < 0:     # both negative
638                return -xp[0]
639        i = <ulong>xp[0]
640        while lx:
641            xp = int_precW(xp)
642            i = i << BITS_IN_LONG | <ulong>xp[0]
643            lx = lx-1
644        if signe(x) > 0:
645            return i
646        else:
647            return -i
648        # NOTE: Could use int_unsafe below, which would be much faster, but
649        # the default PARI prints annoying stuff to the screen when
650        # the number is large.
651
652    def int_unsafe(gen self):
653        """
654        Returns int form of self, but raises an exception if int does
655        not fit into a long integer.
656       
657        This is about 5 times faster than the usual int conversion.
658        """
659        _sig_on
660        return gtolong(self.g)
661       
662    def intvec_unsafe(self):
663        """
664        Returns Python int list form of entries of self, but raises an
665        exception if int does not fit into a long integer.  Here self
666        must be a vector.
667        """
668        cdef int n, L
669        cdef object v
670        cdef GEN g
671        g = self.g
672        if typ(g) != t_VEC:
673            raise TypeError, "gen must be of PARI type t_VEC"
674
675        L = glength(g)
676        v = []
677        for n from 0 <= n < L:
678            v.append(gtolong(<GEN> (g[n+1])))
679        return v
680
681    def python_list_small(gen self):
682        """
683        Return a Python list of the PARI gens.  This object must be of
684        type t_VECSMALL, and the resulting list contains python 'int's
685
686        EXAMPLES:
687            sage: v=pari([1,2,3,10,102,10]).Vecsmall()
688            sage: w = v.python_list_small()
689            sage: w
690            [1, 2, 3, 10, 102, 10]
691            sage: type(w[0])
692            <type 'int'>
693        """
694        cdef long n
695        if typ(self.g) != t_VECSMALL:
696            raise TypeError, "Object (=%s) must be of type t_VECSMALL."%self
697        V = []
698        m = glength(self.g)
699        for n from 0 <= n < m:
700            V.append(self.g[n+1])
701        return V
702
703    def python_list(gen self):
704        """
705        Return a Python list of the PARI gens.  This object must be of
706        type t_VEC
707
708        INPUT: None
709        OUTPUT:
710           list -- Python list whose elements are the
711                   elements of the input gen.
712        EXAMPLES:
713            sage: v=pari([1,2,3,10,102,10])
714            sage: w = v.python_list()
715            sage: w
716            [1, 2, 3, 10, 102, 10]
717            sage: type(w[0])
718            <type 'sage.libs.pari.gen.gen'>
719        """
720        if typ(self.g) != t_VEC:
721            raise TypeError, "Object (=%s) must be of type t_VEC."%self
722        cdef long n, m
723        cdef gen t
724        m = glength(self.g)
725        V = []
726        for n from 0 <= n < m:
727            t = P.new_ref(<GEN> (self.g[n+1]), V)
728            V.append(t)
729        return V
730
731    def python(self, precision=0, bits_prec=None):
732        """
733        Return Python eval of self.
734        """
735        if not bits_prec is None:
736            precision = int(bits_prec * 3.4) + 1
737        import sage.libs.pari.gen_py
738        cdef long orig_prec
739        if precision:
740            orig_prec = P.get_real_precision()
741            P.set_real_precision(precision)
742            x = sage.libs.pari.gen_py.python(self)
743            P.set_real_precision(orig_prec)
744            return x
745        else:
746            return sage.libs.pari.gen_py.python(self)
747
748    def _sage_(self, precision=0):
749        """
750        Return SAGE version of self.
751        """
752        import sage.libs.pari.gen_py
753        cdef long orig_prec
754        if precision:
755            orig_prec = P.get_real_precision()
756            P.set_real_precision(precision)
757            x = sage.libs.pari.gen_py.python(self)
758            P.set_real_precision(orig_prec)
759            return x
760        else:
761            return sage.libs.pari.gen_py.python(self)
762
763    def _eval_(gen self):
764        return self.python()
765   
766    def __long__(gen self):
767        """
768        Return Python long.
769        """
770        return long(int(self))
771   
772    def __float__(gen self):
773        """
774        Return Python float.
775        """
776        cdef double d
777        _sig_on
778        d = gtodouble(self.g)
779        _sig_off
780        return d
781
782    def __bool__(gen self):
783        _sig_on
784        t = bool(self.g != stoi(0))
785        _sig_off
786        return t
787         
788
789
790    ###########################################
791    # arith1.c
792    ###########################################
793    def isprime(gen self, flag=0):
794        """
795        isprime(x, flag=0): Returns True if x is a PROVEN prime
796        number, and False otherwise.
797
798        INPUT:
799            flag -- int
800                    0 (default): use a combination of algorithms.
801                    1: certify primality using the Pocklington-Lehmer Test.
802                    2: certify primality using the APRCL test.
803        OUTPUT:
804            bool -- True or False
805
806        EXAMPLES:
807            sage: pari(9).isprime()
808            False
809            sage: pari(17).isprime()
810            True
811            sage: n = pari(561)    # smallest Carmichael number
812            sage: n.isprime()      # not just a pseudo-primality test!
813            False
814            sage: n.isprime(1)
815            False
816            sage: n.isprime(2)
817            False
818        """
819        _sig_on       
820        t = bool(gisprime(self.g, flag) != stoi(0))
821        _sig_off
822        return t
823
824    def ispseudoprime(gen self, flag=0):
825        """
826        ispseudoprime(x, flag=0): Returns True if x is a pseudo-prime
827        number, and False otherwise.
828
829        INPUT:
830            flag -- int
831                    0 (default): checks whether x is a Baillie-Pomerance-Selfridge-Wagstaff pseudo prime (strong Rabin-Miller pseudo prime for base 2, followed by strong Lucas test for the sequence (P,-1), P smallest positive integer such that P^2 - 4 is not a square mod x).
832                    > 0: checks whether x is a strong Miller-Rabin pseudo prime for flag randomly chosen bases (with end-matching to catch square roots of -1).
833
834        OUTPUT:
835            bool -- True or False
836
837        EXAMPLES:
838            sage: pari(9).ispseudoprime()
839            False
840            sage: pari(17).ispseudoprime()
841            True
842            sage: n = pari(561)     # smallest Carmichael number
843            sage: n.ispseudoprime() # not just any old pseudo-primality test!
844            False
845            sage: n.ispseudoprime(1)
846            False
847        """
848        _sig_on       
849        t = bool(gispseudoprime(self.g, flag) != stoi(0))
850        _sig_off
851        return t
852
853    def ispower(gen self, k=None):
854        r"""
855        Determine whether or not self is a perfect k-th power.
856        If k is not specified, find the largest k so that self
857        is a k-th power.
858
859        NOTE: There is a BUG in the PARI C-library function (at least
860        in PARI 2.2.12-beta) that is used to implement this function!
861        This is in GP:
862        \begin{verbatim}
863           ? p=nextprime(10^100); n=p^100; m=p^2; m^50==n; ispower(n,50)
864        \end{verbatim}
865 
866        INPUT:
867            k -- int (optional)
868
869        OUTPUT:
870            power -- int, what power it is
871            g -- what it is a power of
872           
873        EXAMPLES:
874            sage: pari(9).ispower()
875            (2, 3)
876            sage: pari(17).ispower()
877            (1, 17)
878            sage: pari(17).ispower(2)
879            (False, None)
880            sage: pari(17).ispower(1)
881            (1, 17)
882            sage: pari(2).ispower()
883            (1, 2)
884        """
885        cdef int n
886        cdef GEN x
887       
888        _sig_on
889        if k is None:
890            _sig_on
891            n = isanypower(self.g, &x)
892            if n == 0:
893                _sig_off
894                return 1, self
895            else:
896                return n, P.new_gen(x)
897        else:
898            k = int(k)
899            t0GEN(k)
900            _sig_on
901            n = ispower(self.g, t0, &x)
902            if n == 0:
903                _sig_off
904                return False, None
905            else:
906                return k, P.new_gen(x)
907
908    ###########################################
909    # 1: Standard monadic or dyadic OPERATORS
910    ###########################################
911    def divrem(gen x, y, var=-1):
912        """
913        divrem(x, y, {v}): Euclidean division of x by y giving as a
914            2-dimensional column vector the quotient and the
915            remainder, with respect to v (to main variable if v is
916            omitted).
917        """
918        t0GEN(y)
919        _sig_on       
920        return P.new_gen(divrem(x.g, t0, P.get_var(var)))
921
922    def lex(gen x, y):
923        """
924
925        lex(x,y): Compare x and y lexicographically (1 if x>y, 0 if
926            x==y, -1 if x<y)
927       
928        """
929        t0GEN(y)
930        _sig_on       
931        return lexcmp(x.g, t0)
932
933    def max(gen x, y):
934        """
935        max(x,y): Return the maximum of x and y.
936        """
937        t0GEN(y)
938        _sig_on
939        return P.new_gen(gmax(x.g, t0))
940
941    def min(gen x, y):
942        """
943        min(x,y): Return the minumum of x and y.
944        """
945        t0GEN(y)
946        _sig_on
947        return P.new_gen(gmin(x.g, t0))
948
949    def shift(gen x, long n):
950        """
951        shift(x,n): shift x left n bits if n>=0, right -n bits if n<0.
952        """
953        return P.new_gen(gshift(x.g, n))
954
955    def shiftmul(gen x, long n):
956        """
957        shiftmul(x,n): Return the product of x by $2^n$.
958        """
959        return P.new_gen(gmul2n(x.g, n))
960
961    def sign(gen x):
962        """
963        sign(x): Return the sign of x, where x is of type integer, real
964            or fraction.
965        """
966        return gsigne(x.g)
967
968    def vecmax(gen x):
969        """
970        vecmax(x): Return the maximum of the elements of the vector/matrix x,
971        """
972        _sig_on
973        return P.new_gen(vecmax(x.g))
974
975       
976    def vecmin(gen x):
977        """
978        vecmin(x): Return the maximum of the elements of the vector/matrix x,
979        """
980        _sig_on       
981        return P.new_gen(vecmin(x.g))
982   
983
984
985    ###########################################
986    # 2: CONVERSIONS and similar elementary functions
987    ###########################################
988
989
990    def Col(gen x):
991        """
992        Col(x): Transforms the object x into a column vector.
993       
994        The vector will have only one component, except in the
995        following cases:
996
997           * When x is a vector or a quadratic form, the resulting
998             vector is the initial object considered as a column
999             vector.
1000
1001           * When x is a matrix, the resulting vector is the column of
1002             row vectors comprising the matrix.
1003
1004           * When x is a character string, the result is a column of
1005             individual characters.
1006
1007           * When x is a polynomial, the coefficients of the vector
1008             start with the leading coefficient of the polynomial.
1009
1010           * When x is a power series, only the significant
1011             coefficients are taken into account, but this time by
1012             increasing order of degree.
1013
1014        INPUT:
1015            x -- gen
1016        OUTPUT:
1017            gen
1018        EXAMPLES:
1019            sage: pari('1.5').Col()
1020            [1.500000000000000000000000000]~               # 32-bit
1021            [1.5000000000000000000000000000000000000]~     # 64-bit
1022            sage: pari([1,2,3,4]).Col()
1023            [1, 2, 3, 4]~
1024            sage: pari('[1,2; 3,4]').Col()
1025            [[1, 2], [3, 4]]~
1026            sage: pari('"SAGE"').Col()
1027            ["S", "A", "G", "E"]~
1028            sage: pari('3*x^3 + x').Col()
1029            [3, 0, 1, 0]~
1030            sage: pari('x + 3*x^3 + O(x^5)').Col()
1031            [1, 0, 3, 0]~
1032        """
1033        _sig_on
1034        return P.new_gen(gtocol(x.g))
1035       
1036    def List(gen x):
1037        """
1038        List(x): transforms the PARI vector or list x into a list.
1039
1040        EXAMPLES:
1041            sage: v = pari([1,2,3])
1042            sage: v
1043            [1, 2, 3]
1044            sage: v.type()
1045            't_VEC'
1046            sage: w = v.List()
1047            sage: w
1048            List([1, 2, 3])
1049            sage: w.type()
1050            't_LIST'
1051        """
1052        _sig_on
1053        return P.new_gen(gtolist(x.g))
1054
1055    def Mat(gen x):
1056        """
1057        Mat(x): Returns the matrix defined by x.
1058       
1059           * If x is already a matrix, a copy of x is created and
1060             returned.
1061           
1062           * If x is not a vector or a matrix, this function returns a
1063             1x1 matrix.
1064       
1065           * If x is a row (resp. column) vector, this functions
1066             returns a 1-row (resp. 1-column) matrix, *unless* all
1067             elements are column (resp. row) vectors of the same
1068             length, in which case the vectors are concatenated
1069             sideways and the associated big matrix is returned.
1070
1071        INPUT:
1072            x -- gen
1073        OUTPUT:
1074            gen -- a PARI matrix
1075
1076        EXAMPLES:
1077            sage: x = pari(5)
1078            sage: x.type()
1079            't_INT'
1080            sage: y = x.Mat()
1081            sage: y
1082            Mat(5)
1083            sage: y.type()
1084            't_MAT'
1085            sage: x = pari('[1,2;3,4]')
1086            sage: x.type()
1087            't_MAT'
1088            sage: x = pari('[1,2,3,4]')
1089            sage: x.type()
1090            't_VEC'
1091            sage: y = x.Mat()
1092            sage: y
1093            Mat([1, 2, 3, 4])
1094            sage: y.type()
1095            't_MAT'
1096
1097            sage: v = pari('[1,2;3,4]').Vec(); v
1098            [[1, 3]~, [2, 4]~]
1099            sage: v.Mat()
1100            [1, 2; 3, 4]
1101            sage: v = pari('[1,2;3,4]').Col(); v
1102            [[1, 2], [3, 4]]~
1103            sage: v.Mat()
1104            [1, 2; 3, 4]
1105        """
1106        _sig_on
1107        return P.new_gen(gtomat(x.g))
1108   
1109    def Mod(gen x, y):
1110        """
1111        Mod(x, y): Returns the object x modulo y, denoted Mod(x, y).
1112
1113        The input y must be a an integer or a polynomial:
1114
1115           * If y is an INTEGER, x must also be an integer, a rational
1116             number, or a p-adic number compatible with the modulus y.
1117
1118           * If y is a POLYNOMIAL, x must be a scalar (which is not a polmod),
1119             a polynomial, a rational function, or a power series.
1120
1121        WARNING: This function is not the same as x % y, the result of
1122        which is an integer or a polynomial.
1123
1124        INPUT:
1125            x -- gen
1126            y -- integer or polynomial
1127
1128        OUTPUT:
1129            gen -- intmod or polmod
1130           
1131        EXAMPLES:
1132            sage: z = pari(3)
1133            sage: x = z.Mod(pari(7))
1134            sage: x
1135            Mod(3, 7)
1136            sage: x^2
1137            Mod(2, 7)
1138            sage: x^100
1139            Mod(4, 7)
1140            sage: x.type()
1141            't_INTMOD'
1142
1143            sage: f = pari("x^2 + x + 1")
1144            sage: g = pari("x")
1145            sage: a = g.Mod(f)
1146            sage: a
1147            Mod(x, x^2 + x + 1)
1148            sage: a*a
1149            Mod(-x - 1, x^2 + x + 1)
1150            sage: a.type()
1151            't_POLMOD'
1152        """
1153        t0GEN(y)
1154        _sig_on
1155        return P.new_gen(gmodulcp(x.g,t0))
1156   
1157    def Pol(self, v=-1):
1158        """
1159        Pol(x, {v}): convert x into a polynomial with main variable v
1160        and return the result.
1161
1162           * If x is a scalar, returns a constant polynomial.
1163           
1164           * If x is a power series, the effect is identical
1165              to \kbd{truncate}, i.e.~it chops off the $O(X^k)$.
1166             
1167           * If x is a vector, this function creates the polynomial
1168             whose coefficients are given in x, with x[0]
1169             being the leading coefficient (which can be zero).
1170
1171        WARNING: This is *not* a substitution function. It will not
1172        transform an object containing variables of higher priority
1173        than v:
1174            sage: pari('x+y').Pol('y')
1175            Traceback (most recent call last):
1176            ...
1177            PariError:  (8)
1178
1179        INPUT:
1180            x -- gen
1181            v -- (optional) which variable, defaults to 'x'
1182        OUTPUT:
1183            gen -- a polynomial
1184        EXAMPLES:
1185            sage: v = pari("[1,2,3,4]")
1186            sage: f = v.Pol()
1187            sage: f
1188            x^3 + 2*x^2 + 3*x + 4
1189            sage: f*f
1190            x^6 + 4*x^5 + 10*x^4 + 20*x^3 + 25*x^2 + 24*x + 16
1191           
1192            sage: v = pari("[1,2;3,4]")
1193            sage: v.Pol()
1194            [1, 3]~*x + [2, 4]~
1195        """
1196        _sig_on
1197        return P.new_gen(gtopoly(self.g, P.get_var(v)))
1198   
1199    def Polrev(self, v=-1):
1200        """
1201        Polrev(x, {v}): Convert x into a polynomial with main variable
1202        v and return the result.  This is the reverse of Pol if x is a
1203        vector, otherwise it is identical to Pol.   By "reverse" we mean
1204        that the coefficients are reversed.
1205
1206        INPUT:
1207            x -- gen
1208        OUTPUT:
1209            gen -- a polynomial
1210        EXAMPLES:
1211            sage: v = pari("[1,2,3,4]")
1212            sage: f = v.Polrev()
1213            sage: f
1214            4*x^3 + 3*x^2 + 2*x + 1
1215            sage: v.Pol()
1216            x^3 + 2*x^2 + 3*x + 4
1217            sage: v.Polrev('y')
1218            4*y^3 + 3*y^2 + 2*y + 1
1219           
1220        Note that Polrev does *not* reverse the coefficients of a polynomial!
1221            sage: f
1222            4*x^3 + 3*x^2 + 2*x + 1
1223            sage: f.Polrev()
1224            4*x^3 + 3*x^2 + 2*x + 1
1225            sage: v = pari("[1,2;3,4]")
1226            sage: v.Polrev()
1227            [2, 4]~*x + [1, 3]~
1228        """
1229        _sig_on
1230        return P.new_gen(gtopolyrev(self.g, P.get_var(v)))
1231   
1232    def Qfb(gen a, b, c, D=0):
1233        """
1234        Qfb(a,b,c,{D=0.}): Returns the binary quadratic form
1235        $$
1236                   ax^2 + bxy + cy^2.
1237        $$
1238        The optional D is 0 by default and initializes Shanks's
1239        distance if $b^2 - 4ac > 0$.
1240
1241        NOTE: Negative definite forms are not implemented, so use their
1242        positive definitine counterparts instead.  (I.e., if f is a
1243        negative definite quadratic form, then -f is positive
1244        definite.)
1245
1246        INPUT:
1247            a -- gen
1248            b -- gen
1249            c -- gen
1250            D -- gen (optional, defaults to 0)
1251        OUTPUT:
1252            gen -- binary quadratic form
1253        EXAMPLES:
1254            sage: pari(3).Qfb(7, 2)
1255            Qfb(3, 7, 2, 0.E-250)               # 32-bit
1256            Qfb(3, 7, 2, 0.E-693)               # 64-bit
1257        """
1258        t0GEN(b); t1GEN(c); t2GEN(D)
1259        _sig_on       
1260        return P.new_gen(Qfb0(a.g, t0, t1, t2, prec))
1261       
1262   
1263    def Ser(gen x, v=-1):
1264        """
1265        Ser(x,{v=x}): Create a power series from x with main variable v
1266        and return the result.
1267
1268           * If x is a scalar, this gives a constant power series with
1269             precision given by the default series precision, as returned
1270             by get_series_precision().
1271             
1272           * If x is a polynomial, the precision is the greatest of
1273             get_series_precision() and the degree of the polynomial.
1274
1275           * If x is a vector, the precision is similarly given, and
1276             the coefficients of the vector are understood to be the
1277             coefficients of the power series starting from the
1278             constant term (i.e.~the reverse of the function Pol).
1279
1280        WARNING: This is *not* a substitution function. It will not
1281        transform an object containing variables of higher priority than v.
1282
1283        INPUT:
1284            x -- gen
1285            v -- PARI variable (default: x)
1286        OUTPUT:
1287            gen -- PARI object of PARI type t_SER
1288        EXAMPLES:
1289            sage: pari(2).Ser()
1290            2 + O(x^16)
1291            sage: x = pari([1,2,3,4,5])
1292            sage: x.Ser()
1293            1 + 2*x + 3*x^2 + 4*x^3 + 5*x^4 + O(x^5)
1294            sage: f = x.Ser('v'); print f
1295            1 + 2*v + 3*v^2 + 4*v^3 + 5*v^4 + O(v^5)
1296            sage: pari(1)/f
1297            1 - 2*v + v^2 + O(v^5)
1298            sage: pari(1).Ser()
1299            1 + O(x^16)
1300        """
1301        _sig_on
1302        return P.new_gen(gtoser(x.g, P.get_var(v)))
1303       
1304   
1305    def Set(gen x):
1306        """
1307        Set(x): convert x into a set, i.e. a row vector of strings in
1308        increasing lexicographic order.
1309
1310        INPUT:
1311            x -- gen
1312        OUTPUT:
1313            gen -- a vector of strings in increasing lexicographic order.
1314        EXAMPLES:
1315            sage: pari([1,5,2]).Set()
1316            ["1", "2", "5"]
1317            sage: pari([]).Set()     # the empty set
1318            []
1319            sage: pari([1,1,-1,-1,3,3]).Set()
1320            ["-1", "1", "3"]
1321            sage: pari(1).Set()
1322            ["1"]
1323            sage: pari('1/(x*y)').Set()
1324            ["1/(y*x)"]
1325            sage: pari('["bc","ab","bc"]').Set()
1326            ["ab", "bc"]
1327        """
1328        _sig_on           
1329        return P.new_gen(gtoset(x.g))
1330
1331
1332    def Str(self):
1333        """
1334        Str(self): Return the print representation of self as a PARI
1335        object is returned.
1336
1337        INPUT:
1338            self -- gen
1339        OUTPUT:
1340            gen -- a PARI gen of type t_STR, i.e., a PARI string
1341        EXAMPLES:
1342            sage: pari([1,2,['abc',1]]).Str()
1343            [1, 2, [abc, 1]]
1344            sage: pari('[1,1, 1.54]').Str()
1345            [1, 1, 1.540000000000000000000000000]        # 32-bit
1346            [1, 1, 1.5400000000000000000000000000000000000]        # 64-bit
1347            sage: pari(1).Str()       # 1 is automatically converted to string rep
1348            1
1349            sage: x = pari('x')       # PARI variable "x"
1350            sage: x.Str()             # is converted to string rep.
1351            x
1352            sage: x.Str().type()
1353            't_STR'
1354        """
1355        cdef char* c
1356        _sig_on
1357        c = GENtostr(self.g)
1358        v = self.new_gen(strtoGENstr(c))
1359        free(c)
1360        return v
1361
1362
1363    def Strchr(gen x):
1364        """
1365        Strchr(x): converts x to a string, translating each integer
1366        into a character (in ASCII).
1367
1368        NOTE: Vecsmall is (essentially) the inverse to Strchr().
1369
1370        INPUT:
1371            x -- PARI vector of integers
1372        OUTPUT:
1373            gen -- a PARI string
1374        EXAMPLES:
1375            sage: pari([65,66,123]).Strchr()
1376            AB{
1377            sage: pari('"SAGE"').Vecsmall()   # pari('"SAGE"') --> PARI t_STR
1378            Vecsmall([83, 65, 71, 69])
1379            sage: _.Strchr()
1380            SAGE
1381            sage: pari([83, 65, 71, 69]).Strchr()
1382            SAGE
1383        """
1384        _sig_on       
1385        return P.new_gen(Strchr(x.g))
1386   
1387    def Strexpand(gen x):
1388        """
1389        Strexpand(x): Concatenate the entries of the vector x into a
1390        single string, performing tilde expansion.
1391
1392        NOTE: I have no clue what the point of this function is. -- William
1393        """
1394        if x.type() != 't_VEC':
1395            raise TypeError, "x must be of type t_VEC."
1396        _sig_on       
1397        return P.new_gen(Strexpand(x.g))
1398       
1399   
1400    def Strtex(gen x):
1401        r"""
1402        Strtex(x): Translates the vector x of PARI gens to TeX format
1403        and returns the resulting concatenated strings as a PARI t_STR.
1404
1405        INPUT:
1406            x -- gen
1407        OUTPUT:
1408            gen -- PARI t_STR (string)
1409        EXAMPLES:
1410            sage: v=pari('x^2')
1411            sage: v.Strtex()
1412            x^2
1413            sage: v=pari(['1/x^2','x'])
1414            sage: v.Strtex()
1415            \frac{1}{x^2}x
1416            sage: v=pari(['1 + 1/x + 1/(y+1)','x-1'])
1417            sage: v.Strtex()
1418            \frac{ \left(y
1419             + 2\right)  x
1420             + \left(y
1421             + 1\right) }{ \left(y
1422             + 1\right)  x}x
1423             - 1
1424        """
1425        if x.type() != 't_VEC':
1426            x = P.vector(1, [x])
1427        _sig_on           
1428        return P.new_gen(Strtex(x.g))
1429       
1430    def printtex(gen x):
1431        return x.Strtex()
1432   
1433    def Vec(gen x):
1434        """
1435        Vec(x): Transforms the object x into a vector.
1436
1437        INPUT:
1438            x -- gen
1439        OUTPUT:
1440            gen -- of PARI type t_VEC
1441        EXAMPLES:
1442            sage: pari(1).Vec()
1443            [1]
1444            sage: pari('x^3').Vec()
1445            [1, 0, 0, 0]
1446            sage: pari('x^3 + 3*x - 2').Vec()
1447            [1, 0, 3, -2]
1448            sage: pari([1,2,3]).Vec()
1449            [1, 2, 3]
1450            sage: pari('ab').Vec()
1451            [1, 0]
1452        """
1453        _sig_on       
1454        return P.new_gen(gtovec(x.g))
1455
1456    def Vecrev(gen x):
1457        """
1458        Vecrev(x): Transforms the object x into a vector.
1459        Identical to Vec(x) except when x is
1460        -- a polynomial, this is the reverse of Vec.
1461        -- a power series, this includes low-order zero coefficients.
1462        -- a laurant series, raises an exception
1463
1464        INPUT:
1465            x -- gen
1466        OUTPUT:
1467            gen -- of PARI type t_VEC
1468        EXAMPLES:
1469            sage: pari(1).Vecrev()
1470            [1]
1471            sage: pari('x^3').Vecrev()
1472            [0, 0, 0, 1]
1473            sage: pari('x^3 + 3*x - 2').Vecrev()
1474            [-2, 3, 0, 1]
1475            sage: pari([1, 2, 3]).Vecrev()
1476            [1, 2, 3]
1477            sage: pari('Col([1, 2, 3])').Vecrev()
1478            [1, 2, 3]
1479            sage: pari('[1, 2; 3, 4]').Vecrev()
1480            [[1, 3]~, [2, 4]~]
1481            sage: pari('ab').Vecrev()
1482            [0, 1]
1483            sage: pari('x^2 + 3*x^3 + O(x^5)').Vecrev()
1484            [0, 0, 1, 3, 0]
1485            sage: pari('x^-2 + 3*x^3 + O(x^5)').Vecrev()
1486            Traceback (most recent call last):
1487            ...
1488            ValueError: Vecrev() is not defined for Laurent series
1489        """
1490        cdef long lx, vx, i
1491        cdef GEN y
1492        if typ(x.g) == t_POL:
1493            lx = lg(x.g)
1494            y = cgetg(lx-1, t_VEC)
1495            for i from 1 <= i <= lx-2:
1496                # no need to copy, since new_gen will deep copy
1497                __set_lvalue__(gel(y,i), gel(x.g,i+1))
1498            return P.new_gen(y)
1499        elif typ(x.g) == t_SER:
1500            lx = lg(x.g)
1501            vx = valp(x.g)
1502            if vx < 0:
1503                raise ValueError, "Vecrev() is not defined for Laurent series"
1504            y = cgetg(vx+lx-1, t_VEC)
1505            for i from 1 <= i <= vx:
1506                __set_lvalue__(gel(y,i), gen_0)
1507            for i from 1 <= i <= lx-2:
1508                # no need to copy, since new_gen will deep copy
1509                __set_lvalue__(gel(y,vx+i), gel(x.g,i+1))
1510            return P.new_gen(y)
1511        else:
1512            return x.Vec()
1513   
1514    def Vecsmall(gen x):
1515        """
1516        Vecsmall(x): transforms the object x into a t_VECSMALL.
1517
1518        INPUT:
1519            x -- gen
1520        OUTPUT:
1521            gen -- PARI t_VECSMALL
1522        EXAMPLES:
1523            sage: pari([1,2,3]).Vecsmall()
1524            Vecsmall([1, 2, 3])
1525            sage: pari('"SAGE"').Vecsmall()
1526            Vecsmall([83, 65, 71, 69])
1527            sage: pari(1234).Vecsmall()
1528            Vecsmall([1234])
1529        """
1530        _sig_on       
1531        return P.new_gen(gtovecsmall(x.g))
1532   
1533    def binary(gen x):
1534        """
1535        binary(x): gives the vector formed by the binary digits of
1536        abs(x), where x is of type t_INT.
1537
1538        INPUT:
1539            x -- gen of type t_INT
1540        OUTPUT:
1541            gen -- of type t_VEC
1542        EXAMPLES:
1543            sage: pari(0).binary()
1544            [0]
1545            sage: pari(-5).binary()
1546            [1, 0, 1]
1547            sage: pari(5).binary()
1548            [1, 0, 1]
1549            sage: pari(2005).binary()
1550            [1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]
1551
1552            sage: pari('"2"').binary()
1553            Traceback (most recent call last):
1554            ...
1555            TypeError: x (=2) must be of type t_INT, but is of type t_STR.
1556        """
1557        if typ(x.g) != t_INT:
1558            raise TypeError, "x (=%s) must be of type t_INT, but is of type %s."%(x,x.type())
1559        _sig_on
1560        return P.new_gen(binaire(x.g))
1561   
1562    def bitand(gen x, y):
1563        """
1564        bitand(x,y): Bitwise and of two integers x and y. Negative
1565        numbers behave as if modulo some large power of 2.
1566
1567        INPUT:
1568            x -- gen  (of type t_INT)
1569            y -- coercible to gen  (of type t_INT)
1570        OUTPUT:
1571            gen -- of type type t_INT
1572        EXAMPLES:
1573            sage: pari(8).bitand(4)
1574            0
1575            sage: pari(8).bitand(8)
1576            8
1577            sage: pari(6).binary()
1578            [1, 1, 0]
1579            sage: pari(7).binary()
1580            [1, 1, 1]
1581            sage: pari(6).bitand(7)
1582            6
1583            sage: pari(19).bitand(-1)
1584            19
1585            sage: pari(-1).bitand(-1)
1586            -1
1587        """
1588        t0GEN(y)
1589        _sig_on
1590        return P.new_gen(gbitand(x.g, t0))
1591       
1592   
1593    def bitneg(gen x, long n=-1):
1594        r"""
1595        bitneg(x,{n=-1}): Bitwise negation of the integer x truncated
1596        to n bits.  n=-1 (the default) represents an infinite sequence
1597        of the bit 1.  Negative numbers behave as if modulo some large
1598        power of 2.
1599
1600        With n=-1, this function returns -n-1.  With n >= 0, it returns
1601        a number a such that  $a\cong -n-1 \pmod{2^n}$.
1602
1603        INPUT:
1604            x -- gen (t_INT)
1605            n -- long, default = -1
1606        OUTPUT:
1607            gen -- t_INT
1608        EXAMPLES:
1609            sage: pari(10).bitneg()
1610            -11
1611            sage: pari(1).bitneg()
1612            -2
1613            sage: pari(-2).bitneg()
1614            1
1615            sage: pari(-1).bitneg()
1616            0
1617            sage: pari(569).bitneg()
1618            -570
1619            sage: pari(569).bitneg(10)
1620            454
1621            sage: 454 % 2^10
1622            454
1623            sage: -570 % 2^10
1624            454
1625        """
1626        _sig_on
1627        return P.new_gen(gbitneg(x.g,n))
1628   
1629   
1630    def bitnegimply(gen x, y):
1631        """
1632        bitnegimply(x,y): Bitwise negated imply of two integers x and
1633        y, in other words, x BITAND BITNEG(y). Negative numbers behave
1634        as if modulo big power of 2.
1635
1636        INPUT:
1637            x -- gen  (of type t_INT)
1638            y -- coercible to gen  (of type t_INT)
1639        OUTPUT:
1640            gen -- of type type t_INT
1641        EXAMPLES:
1642            sage: pari(14).bitnegimply(0)   
1643            14
1644            sage: pari(8).bitnegimply(8)
1645            0
1646            sage: pari(8+4).bitnegimply(8)
1647            4
1648        """
1649        t0GEN(y)
1650        _sig_on
1651        return P.new_gen(gbitnegimply(x.g, t0))
1652
1653   
1654    def bitor(gen x, y):
1655        """
1656        bitor(x,y): Bitwise or of two integers x and y. Negative
1657        numbers behave as if modulo big power of 2.
1658
1659        INPUT:
1660            x -- gen  (of type t_INT)
1661            y -- coercible to gen  (of type t_INT)
1662        OUTPUT:
1663            gen -- of type type t_INT
1664        EXAMPLES:
1665            sage: pari(14).bitor(0)
1666            14
1667            sage: pari(8).bitor(4)
1668            12
1669            sage: pari(12).bitor(1)
1670            13
1671            sage: pari(13).bitor(1)
1672            13
1673        """
1674        t0GEN(y)
1675        _sig_on
1676        return P.new_gen(gbitor(x.g, t0))
1677
1678   
1679    def bittest(gen x, long n):
1680        """
1681        bittest(x, long n): Returns bit number n (coefficient of $2^n$ in binary)
1682        of the integer x. Negative numbers behave as if modulo a big power of 2.
1683
1684        INPUT:
1685           x -- gen (pari integer)
1686        OUTPUT:
1687           bool -- a Python bool
1688        EXAMPLES:
1689            sage: x = pari(6)
1690            sage: x.bittest(0)
1691            False
1692            sage: x.bittest(1)
1693            True
1694            sage: x.bittest(2)
1695            True
1696            sage: x.bittest(3)
1697            False
1698            sage: pari(-3).bittest(0)
1699            True
1700            sage: pari(-3).bittest(1)
1701            False
1702            sage: [pari(-3).bittest(n) for n in range(10)]
1703            [True, False, True, True, True, True, True, True, True, True]
1704        """
1705        _sig_on
1706        b = bool(bittest(x.g, n))
1707        _sig_off
1708        return b
1709   
1710    def bitxor(gen x, y):
1711        """
1712        bitxor(x,y): Bitwise exclusive or of two integers x and y.
1713        Negative numbers behave as if modulo big power of 2.
1714       
1715        INPUT:
1716            x -- gen  (of type t_INT)
1717            y -- coercible to gen  (of type t_INT)
1718        OUTPUT:
1719            gen -- of type type t_INT
1720        EXAMPLES:
1721            sage: pari(6).bitxor(4)
1722            2
1723            sage: pari(0).bitxor(4)
1724            4
1725            sage: pari(6).bitxor(0)
1726            6
1727        """
1728        t0GEN(y)
1729        _sig_on
1730        return P.new_gen(gbitxor(x.g, t0))
1731
1732   
1733    def ceil(gen x):
1734        """
1735        Return the smallest integer >= x.
1736
1737        INPUT:
1738           x -- gen
1739        OUTPUT:
1740           gen -- integer
1741        EXAMPLES:
1742            sage: pari(1.4).ceil()
1743            2
1744            sage: pari(-1.4).ceil()
1745            -1
1746            sage: pari('x').ceil()
1747            x
1748            sage: pari('x^2+5*x+2.2').ceil()
1749            x^2 + 5*x + 2.200000000000000000000000000             # 32-bit
1750            x^2 + 5*x + 2.2000000000000000000000000000000000000   # 64-bit
1751            sage: pari('3/4').ceil()
1752            1
1753        """
1754        _sig_on
1755        return P.new_gen(gceil(x.g))
1756   
1757    def centerlift(gen x, v=-1):
1758        """
1759        centerlift(x,{v}): Centered lift of x.  This function returns
1760        exactly the same thing as lift, except if x is an integer mod.
1761
1762        INPUT:
1763            x -- gen
1764            v -- var (default: x)
1765        OUTPUT:
1766            gen
1767        EXAMPLES:
1768            sage: x = pari(-2).Mod(5)
1769            sage: x.centerlift()
1770            -2
1771            sage: x.lift()
1772            3
1773            sage: f = pari('x-1').Mod('x^2 + 1')
1774            sage: f.centerlift()
1775            x - 1
1776            sage: f.lift()
1777            x - 1
1778            sage: f = pari('x-y').Mod('x^2+1')
1779            sage: f
1780            Mod(x - y, x^2 + 1)
1781            sage: f.centerlift('x')
1782            x - y
1783            sage: f.centerlift('y')
1784            Mod(x - y, x^2 + 1)
1785        """
1786        _sig_on
1787        return P.new_gen(centerlift0(x.g, P.get_var(v)))
1788
1789   
1790    def changevar(gen x, y):
1791        """
1792        changevar(gen x, y): change variables of x according to the vector y.
1793
1794        WARNING: This doesn't seem to work right at all in SAGE (!).
1795        Use with caution.   *STRANGE*
1796       
1797        INPUT:
1798            x -- gen
1799            y -- gen (or coercible to gen)
1800        OUTPUT:
1801            gen
1802        EXAMPLES:
1803            sage: pari('x^3+1').changevar(pari(['y']))
1804            y^3 + 1
1805        """
1806        t0GEN(y)
1807        _sig_on
1808        return P.new_gen(changevar(x.g, t0))
1809   
1810    def component(gen x, long n):
1811        """
1812        component(x, long n): Return n'th component of the internal
1813        representation of x.  This this function is 1-based
1814        instead of 0-based.
1815
1816        NOTE: For vectors or matrices, it is simpler to use x[n-1]. For
1817        list objects such as is output by nfinit, it is easier to use
1818        member functions.
1819
1820        INPUT:
1821            x -- gen
1822            n -- C long (coercible to)
1823        OUTPUT:
1824            gen
1825        EXAMPLES:
1826            sage: pari([0,1,2,3,4]).component(1)
1827            0
1828            sage: pari([0,1,2,3,4]).component(2)
1829            1
1830            sage: pari([0,1,2,3,4]).component(4)
1831            3
1832            sage: pari('x^3 + 2').component(1)
1833            2
1834            sage: pari('x^3 + 2').component(2)
1835            0
1836            sage: pari('x^3 + 2').component(4)
1837            1
1838           
1839            sage: pari('x').component(0)
1840            Traceback (most recent call last):
1841            ...
1842            PariError:  (8)
1843        """
1844        _sig_on
1845        return P.new_gen(compo(x.g, n))
1846   
1847    def conj(gen x):
1848        """
1849        conj(x): Return the algebraic conjugate of x.
1850
1851        INPUT:
1852            x -- gen
1853        OUTPUT:
1854            gen
1855        EXAMPLES:
1856            sage: pari('x+1').conj()
1857            x + 1
1858            sage: pari('x+I').conj()
1859            x - I
1860            sage: pari('1/(2*x+3*I)').conj()
1861            1/(2*x - 3*I)
1862            sage: pari([1,2,'2-I','Mod(x,x^2+1)', 'Mod(x,x^2-2)']).conj()
1863            [1, 2, 2 + I, Mod(-x, x^2 + 1), Mod(-x, x^2 - 2)]
1864            sage: pari('Mod(x,x^2-2)').conj()
1865            Mod(-x, x^2 - 2)
1866            sage: pari('Mod(x,x^3-3)').conj()
1867            Traceback (most recent call last):
1868            ...
1869            PariError: incorrect type (20)
1870        """
1871        _sig_on
1872        return P.new_gen(gconj(x.g))
1873   
1874    def conjvec(gen x):
1875        """
1876        conjvec(x): Returns the vector of all conjugates of the
1877        algebraic number x.  An algebraic number is a polynomial over
1878        Q modulo an irreducible polynomial.
1879
1880        INPUT:
1881            x -- gen
1882        OUTPUT:
1883            gen
1884        EXAMPLES:
1885            sage: pari('Mod(1+x,x^2-2)').conjvec()
1886            [-0.4142135623730950488016887242, 2.414213562373095048801688724]~                         # 32-bit
1887            [-0.41421356237309504880168872420969807857, 2.4142135623730950488016887242096980786]~     # 64-bit
1888            sage: pari('Mod(x,x^3-3)').conjvec()
1889            [1.442249570307408382321638311, -0.7211247851537041911608191554 + 1.249024766483406479413179544*I, -0.7211247851537041911608191554 - 1.249024766483406479413179544*I]~           # 32-bit
1890            [1.4422495703074083823216383107801095884, -0.72112478515370419116081915539005479419 + 1.2490247664834064794131795437632536350*I, -0.72112478515370419116081915539005479419 - 1.2490247664834064794131795437632536350*I]~       # 64-bit
1891        """
1892        _sig_on
1893        return P.new_gen(conjvec(x.g, prec))
1894   
1895    def denominator(gen x):
1896        """
1897        denominator(x): Return the denominator of x.  When x is a
1898        vector, this is the least common multiple of the denominators
1899        of the components of x.
1900
1901        what about poly?
1902        INPUT:
1903            x -- gen
1904        OUTPUT:
1905            gen
1906        EXAMPLES:
1907            sage: pari('5/9').denominator()
1908            9
1909            sage: pari('(x+1)/(x-2)').denominator()
1910            x - 2
1911            sage: pari('2/3 + 5/8*x + 7/3*x^2 + 1/5*y').denominator()
1912            1
1913            sage: pari('2/3*x').denominator()
1914            1
1915            sage: pari('[2/3, 5/8, 7/3, 1/5]').denominator()
1916            120
1917        """
1918        _sig_on
1919        return P.new_gen(denom(x.g))
1920   
1921    def floor(gen x):
1922        """
1923        floor(x): Return the floor of x, which is the largest integer <= x.
1924        This function also works component-wise on polynomials, vectors, etc.
1925
1926        INPUT:
1927            x -- gen
1928        OUTPUT:
1929            gen
1930        EXAMPLES:
1931            sage: pari('5/9').floor()
1932            0
1933            sage: pari('11/9').floor()
1934            1
1935            sage: pari('1.17').floor()
1936            1
1937            sage: pari('x').floor()
1938            x
1939            sage: pari('x+1.5').floor()
1940            x + 1.500000000000000000000000000             # 32-bit
1941            x + 1.5000000000000000000000000000000000000   # 64-bit
1942            sage: pari('[1.5,2.3,4.99]').floor()
1943            [1, 2, 4]
1944            sage: pari('[[1.1,2.2],[3.3,4.4]]').floor()
1945            [[1, 2], [3, 4]]
1946
1947            sage: pari('"hello world"').floor()
1948            Traceback (most recent call last):
1949            ...
1950            PariError: incorrect type (20)
1951        """
1952        _sig_on
1953        return P.new_gen(gfloor(x.g))
1954   
1955    def frac(gen x):
1956        """
1957        frac(x): Return the fractional part of x, which is x - floor(x).
1958
1959        INPUT:
1960            x -- gen
1961        OUTPUT:
1962            gen
1963        EXAMPLES:
1964            sage: pari('1.7').frac()
1965            0.7000000000000000000000000000            # 32-bit
1966            0.70000000000000000000000000000000000000  # 64-bit
1967            sage: pari('sqrt(2)').frac()
1968            0.4142135623730950488016887242            # 32-bit
1969            0.41421356237309504880168872420969807857  # 64-bit
1970            sage: pari('sqrt(-2)').frac()
1971            Traceback (most recent call last):
1972            ...
1973            PariError: incorrect type (20)
1974        """
1975        _sig_on
1976        return P.new_gen(gfrac(x.g))
1977   
1978    def imag(gen x):
1979        """
1980        imag(x): Return the imaginary part of x.  This function also
1981        works component-wise.
1982
1983        INPUT:
1984            x -- gen
1985        OUTPUT:
1986            gen
1987        EXAMPLES:
1988            sage: pari('1+2*I').imag()
1989            2
1990            sage: pari('sqrt(-2)').imag()
1991            1.414213562373095048801688724              # 32-bit
1992            1.4142135623730950488016887242096980786    # 64-bit
1993            sage: pari('x+I').imag()
1994            1
1995            sage: pari('x+2*I').imag()
1996            2
1997            sage: pari('(1+I)*x^2+2*I').imag()
1998            x^2 + 2
1999            sage: pari('[1,2,3] + [4*I,5,6]').imag()
2000            [4, 0, 0]
2001        """
2002        _sig_on
2003        return P.new_gen(gimag(x.g))
2004   
2005    def length(gen x):
2006        """
2007        length(x): Return the number of non-code words in x.  If x
2008        is a string, this is the number of characters of x.
2009
2010        ?? terminator ?? carriage return ??
2011        """
2012        return glength(x.g)
2013   
2014    def lift(gen x, v=-1):
2015        """
2016        lift(x,{v}): Returns the lift of an element of Z/nZ to Z or
2017        R[x]/(P) to R[x] for a type R if v is omitted.  If v is given,
2018        lift only polymods with main variable v.  If v does not occur
2019        in x, lift only intmods.
2020
2021        INPUT:
2022            x -- gen
2023            v -- (optional) variable
2024        OUTPUT:
2025            gen
2026        EXAMPLES:
2027            sage: x = pari("x")
2028            sage: a = x.Mod('x^3 + 17*x + 3')
2029            sage: a
2030            Mod(x, x^3 + 17*x + 3)
2031            sage: b = a^4; b
2032            Mod(-17*x^2 - 3*x, x^3 + 17*x + 3)
2033            sage: b.lift()
2034            -17*x^2 - 3*x
2035
2036        ??? more examples
2037        """
2038        if v == -1:
2039            _sig_on
2040            return P.new_gen(lift(x.g))
2041        _sig_on
2042        return P.new_gen(lift0(x.g, P.get_var(v)))
2043
2044    def numbpart(gen x):
2045        """
2046        numbpart(x): returns the number of partitions of x.
2047
2048        EXAMPLES:
2049            sage: pari(20).numbpart()
2050            627
2051            sage: pari(100).numbpart()
2052            190569292
2053        """
2054        _sig_on
2055        return P.new_gen(numbpart(x.g))
2056   
2057    def numerator(gen x):
2058        """
2059        numerator(x): Returns the numerator of x.
2060
2061        INPUT:
2062            x -- gen
2063        OUTPUT:
2064            gen
2065        EXAMPLES:
2066
2067        """
2068        return P.new_gen(numer(x.g))
2069   
2070
2071    def numtoperm(gen k, long n):
2072        """
2073        numtoperm(k, n): Return the permutation number k (mod n!) of n
2074        letters, where n is an integer.
2075       
2076        INPUT:
2077            k -- gen, integer
2078            n -- int
2079        OUTPUT:
2080            gen -- vector (permutation of {1,...,n})
2081        EXAMPLES:
2082        """
2083        _sig_on       
2084        return P.new_gen(numtoperm(n, k.g))
2085
2086   
2087    def padicprec(gen x, p):
2088        """
2089        padicprec(x,p): Return the absolute p-adic precision of the object x.
2090
2091        INPUT:
2092            x -- gen
2093        OUTPUT:
2094            int
2095        EXAMPLES:
2096        """
2097        cdef gen _p
2098        _p = pari(p)
2099        if typ(_p.g) != t_INT:
2100            raise TypeError, "p (=%s) must be of type t_INT, but is of type %s."%(
2101                _p, _p.type())
2102        return padicprec(x.g, _p.g)
2103   
2104    def permtonum(gen x):
2105        """
2106        permtonum(x): Return the ordinal (between 1 and n!) of permutation vector x.
2107        ??? Huh ???  say more.  what is a perm vector.  0 to n-1 or 1-n.
2108
2109        INPUT:
2110            x -- gen (vector of integers)
2111        OUTPUT:
2112            gen -- integer
2113        EXAMPLES:
2114        """
2115        if typ(x.g) != t_VEC:
2116            raise TypeError, "x (=%s) must be of type t_VEC, but is of type %s."%(x,x.type())
2117        return P.new_gen(permtonum(x.g))
2118   
2119    def precision(gen x, long n=-1):
2120        """
2121        precision(x,{n}): Change the precision of x to be n, where n
2122        is a C-integer). If n is omitted, output the real precision of x.
2123
2124        INPUT:
2125            x -- gen
2126            n -- (optional) int
2127        OUTPUT:
2128            nothing
2129          or
2130            gen if n is omitted
2131        EXAMPLES:
2132        """
2133        if n <= -1:
2134            return precision(x.g)
2135        return P.new_gen(precision0(x.g, n))
2136   
2137    def random(gen N):
2138        r"""
2139        \code{random(\{N=$2^31$\})}: Return a pseudo-random integer between 0 and $N-1$.
2140
2141        INPUT:
2142            N -- gen, integer
2143        OUTPUT:
2144            gen -- integer
2145        EXAMPLES:
2146        """
2147        if typ(N.g) != t_INT:
2148            raise TypeError, "x (=%s) must be of type t_INT, but is of type %s."%(N,N.type())
2149        _sig_on
2150        return P.new_gen(genrand(N.g))
2151   
2152    def real(gen x):
2153        """
2154        real(x): Return the real part of x.
2155
2156        INPUT:
2157            x -- gen
2158        OUTPUT:
2159            gen
2160        EXAMPLES:
2161        """
2162        _sig_on
2163        return P.new_gen(greal(x.g))
2164   
2165    def round(gen x, estimate=False):
2166        """
2167        round(x,estimat=False):  If x is a real number, returns x rounded
2168        to the nearest integer (rounding up).  If the optional argument
2169        estimate is True, also returns the binary exponent e of the difference
2170        between the original and the rounded value (the "fractional part")
2171        (this is the integer ceiling of log_2(error)).
2172
2173        When x is a general PARI object, this function returns the result
2174        of rounding every coefficient at every level of PARI object.
2175        Note that this is different than what the truncate function
2176        does (see the example below).
2177
2178        One use of round is to get exact results after a long
2179        approximate computation, when theory tells you that the
2180        coefficients must be integers.
2181       
2182        INPUT:
2183            x -- gen
2184            estimate -- (optional) bool, False by default
2185        OUTPUT:
2186            * if estimate == False, return a single gen.
2187            * if estimate == True, return rounded verison of x and
2188              error estimate in bits, both as gens.
2189        EXAMPLES:
2190            sage: pari('1.5').round()
2191            2
2192            sage: pari('1.5').round(True)
2193            (2, -1)
2194            sage: pari('1.5 + 2.1*I').round()
2195            2 + 2*I
2196            sage: pari('1.0001').round(True)
2197            (1, -14)
2198            sage: pari('(2.4*x^2 - 1.7)/x').round()
2199            (2*x^2 - 2)/x
2200            sage: pari('(2.4*x^2 - 1.7)/x').truncate()
2201            2.400000000000000000000000000*x                # 32-bit
2202            2.4000000000000000000000000000000000000*x      # 64-bit
2203        """
2204        cdef int n
2205        if not estimate:
2206            _sig_on
2207            return P.new_gen(ground(x.g))
2208        cdef long e
2209        cdef gen y
2210        _sig_on
2211        y = P.new_gen(grndtoi(x.g, &e))
2212        return y, e
2213   
2214    def simplify(gen x):
2215        """
2216        simplify(x): Simplify the object x as much as possible, and return
2217        the result.
2218
2219        A complex or quadratic number whose imaginary part is an exact 0
2220        (i.e., not an approximate one such as O(3) or 0.E-28) is converted
2221        to its real part, and a a polynomial of degree 0 is converted to
2222        its constant term.  Simplification occurs recursively.
2223
2224        This function is useful before using arithmetic functions, which
2225        expect integer arguments:
2226
2227        EXAMPLES:
2228            sage: y = pari('y')
2229            sage: x = pari('9') + y - y
2230            sage: x
2231            9
2232            sage: x.type()
2233            't_POL'
2234            sage: x.factor()
2235            matrix(0,2)
2236            sage: pari('9').factor()
2237            Mat([3, 2])
2238            sage: x.simplify()
2239            9
2240            sage: x.simplify().factor()
2241            Mat([3, 2])
2242            sage: x = pari('1.5 + 0*I')
2243            sage: x.type()
2244            't_COMPLEX'
2245            sage: x.simplify()
2246            1.500000000000000000000000000                  # 32-bit
2247            1.5000000000000000000000000000000000000        # 64-bit
2248            sage: y = x.simplify()
2249            sage: y.type()
2250            't_REAL'
2251        """
2252        _sig_on
2253        return P.new_gen(simplify(x.g))
2254   
2255    def sizebyte(gen x):
2256        """
2257        sizebyte(x): Return the total number of bytes occupied by the
2258        complete tree of the object x.  Note that this number depends
2259        on whether the computer is 32-bit or 64-bit (see examples).
2260       
2261        INPUT:
2262            x -- gen
2263        OUTPUT:
2264            int (a Python int)
2265        EXAMPLES:
2266            sage: pari('1').sizebyte()
2267            12           # 32-bit
2268            24           # 64-bit
2269            sage: pari('10').sizebyte()
2270            12           # 32-bit
2271            24           # 64-bit
2272            sage: pari('10000000000000').sizebyte()
2273            16           # 32-bit
2274            24           # 64-bit
2275            sage: pari('10^100').sizebyte()
2276            52           # 32-bit
2277            64           # 64-bit
2278            sage: pari('x').sizebyte()
2279            36           # 32-bit
2280            72           # 64-bit
2281            sage: pari('x^20').sizebyte()
2282            264          # 32-bit
2283            528          # 64-bit
2284            sage: pari('[x, 10^100]').sizebyte()
2285            100          # 32-bit
2286            160          # 64-bit
2287        """
2288        return taille2(x.g)
2289   
2290    def sizedigit(gen x):
2291        """
2292
2293        sizedigit(x): Return a quick estimate for the maximal number of
2294        decimal digits before the decimal point of any component of x.
2295
2296        INPUT:
2297            x -- gen
2298        OUTPUT:
2299            int -- Python integer
2300        EXAMPLES:
2301            sage: x = pari('10^100')
2302            sage: x.Str().length()
2303            101
2304            sage: x.sizedigit()
2305            101
2306
2307        Note that digits after the decimal point are ignored.
2308            sage: x = pari('1.234')
2309            sage: x
2310            1.234000000000000000000000000              # 32-bit
2311            1.2340000000000000000000000000000000000    # 64-bit
2312            sage: x.sizedigit()
2313            1
2314
2315        The estimate can be one too big:
2316            sage: pari('7234.1').sizedigit()
2317            4
2318            sage: pari('9234.1').sizedigit()
2319            5
2320        """
2321        return sizedigit(x.g)
2322   
2323    def truncate(gen x, estimate=False):
2324        """
2325        truncate(x,estimate=False):  Return the truncation of x.
2326        If estimate is True, also return the number of error bits.
2327       
2328        When x is in the real numbers, this means that the part
2329        after the decimal point is chopped away, e is the binary
2330        exponent of the difference between the original and truncated
2331        value (the "fractional part").    If x is a rational
2332        function, the result is the integer part (Euclidean
2333        quotient of numerator by denominator) and if requested
2334        the error estimate is 0.
2335
2336        When truncate is applied to a power series (in X), it
2337        transforms it into a polynomial or a rational function with
2338        denominator a power of X, by chopping away the $O(X^k)$.
2339        Similarly, when applied to a p-adic number, it transforms it
2340        into an integer or a rational number by chopping away the
2341        $O(p^k)$.
2342
2343        INPUT:
2344            x -- gen
2345            estimate -- (optional) bool, which is False by default
2346        OUTPUT:
2347            * if estimate == False, return a single gen.
2348            * if estimate == True, return rounded verison of x and
2349              error estimate in bits, both as gens.
2350        OUTPUT:
2351        EXAMPLES:
2352            sage: pari('(x^2+1)/x').round()
2353            (x^2 + 1)/x
2354            sage: pari('(x^2+1)/x').truncate()
2355            x
2356            sage: pari('1.043').truncate()
2357            1
2358            sage: pari('1.043').truncate(True)
2359            (1, -5)
2360            sage: pari('1.6').truncate()
2361            1
2362            sage: pari('1.6').round()
2363            2
2364            sage: pari('1/3 + 2 + 3^2 + O(3^3)').truncate()
2365            34/3
2366            sage: pari('sin(x+O(x^10))').truncate()
2367            1/362880*x^9 - 1/5040*x^7 + 1/120*x^5 - 1/6*x^3 + x
2368            sage: pari('sin(x+O(x^10))').round()   # each coefficient has abs < 1
2369            x + O(x^10)
2370        """
2371        if not estimate:
2372            _sig_on
2373            return P.new_gen(gtrunc(x.g))
2374        cdef long e
2375        cdef gen y
2376        _sig_on
2377        y = P.new_gen(gcvtoi(x.g, &e))
2378        return y, e
2379   
2380    def valuation(gen x, p):
2381        """
2382        valuation(x,p): Return the valuation of x with respect to p.
2383
2384        The valuation is the highest exponent of p dividing x.
2385
2386           * If p is an integer, x must be an integer, an intmod whose
2387             modulus is divisible by p, a rational number, a p-adic
2388             number, or a polynomial or power series in which case the
2389             valuation is the minimal of the valuations of the
2390             coefficients.
2391
2392           * If p is a polynomial, x must be a polynomial or a
2393             rational fucntion.  If p is a monomial then x may also be
2394             a power series.
2395
2396           * If x is a vector, complex or quadratic number, then the
2397             valuation is the minimum of the component valuations.
2398
2399           * If x = 0, the result is $2^31-1$ on 32-bit machines or
2400             $2^63-1$ on 64-bit machines if x is an exact object.
2401             If x is a p-adic number or power series, the result
2402             is the exponent of the zero.
2403
2404        INPUT:
2405            x -- gen
2406            p -- coercible to gen
2407        OUTPUT:
2408            gen -- integer
2409        EXAMPLES:
2410            sage: pari(9).valuation(3)
2411            2
2412            sage: pari(9).valuation(9)
2413            1
2414            sage: x = pari(9).Mod(27); x.valuation(3)
2415            2
2416            sage: pari('5/3').valuation(3)
2417            -1
2418            sage: pari('9 + 3*x + 15*x^2').valuation(3)
2419            1
2420            sage: pari([9,3,15]).valuation(3)
2421            1
2422            sage: pari('9 + 3*x + 15*x^2 + O(x^5)').valuation(3)
2423            1
2424
2425            sage: pari('x^2*(x+1)^3').valuation(pari('x+1'))
2426            3
2427            sage: pari('x + O(x^5)').valuation('x')
2428            1
2429            sage: pari('2*x^2 + O(x^5)').valuation('x')
2430            2
2431
2432            sage: pari(0).valuation(3)   
2433            2147483647            # 32-bit
2434            9223372036854775807   # 64-bit
2435        """
2436        t0GEN(p)
2437        _sig_on
2438        v = ggval(x.g, t0)
2439        _sig_off
2440        return v
2441   
2442    def variable(gen x):
2443        """
2444        variable(x): Return the main variable of the object x, or p
2445        if x is a p-adic number.
2446
2447        This function raises a TypeError exception on scalars, i.e.,
2448        on objects with no variable associated to them.
2449
2450        INPUT:
2451            x -- gen
2452        OUTPUT:
2453            gen
2454        EXAMPLES:
2455            sage: pari('x^2 + x -2').variable()
2456            x
2457            sage: pari('1+2^3 + O(2^5)').variable()
2458            2
2459            sage: pari('x+y0').variable()
2460            x
2461            sage: pari('y0+z0').variable()
2462            y0
2463        """
2464        _sig_on
2465        return P.new_gen(gpolvar(x.g))
2466
2467
2468    ###########################################
2469    # 3: TRANSCENDENTAL functions
2470    # AUTHORS: Pyrex Code, docs -- Justin Walker (justin@mac.com)
2471    #          Examples, docs   -- William Stein
2472    ###########################################
2473   
2474    def abs(gen self):
2475        """
2476        Returns the absolute value of x (its modulus, if x is complex).
2477        Rational functions are not allowed.  Contrary to most transcendental
2478        functions, an exact argument is not converted to a real number before
2479        applying abs and an exact result is returned if possible.
2480
2481        EXAMPLES:
2482            sage: x = pari("-27.1")
2483            sage: x.abs()
2484            27.10000000000000000000000000               # 32-bit
2485            27.100000000000000000000000000000000000     # 64-bit
2486
2487        If x is a polynomial, returns -x if the leading coefficient is real
2488        and negative else returns x.  For a power series, the constant
2489        coefficient is considered instead.
2490
2491        EXAMPLES:
2492            sage: pari('x-1.2*x^2').abs()
2493            1.200000000000000000000000000*x^2 - x              # 32-bit
2494            1.2000000000000000000000000000000000000*x^2 - x    # 64-bit
2495        """
2496        _sig_on       
2497        return P.new_gen(gabs(self.g, prec))
2498   
2499    def acos(gen x):
2500        r"""
2501        The principal branch of $\cos^{-1}(x)$, so that $\Re(\acos(x))$
2502        belongs to $[0,Pi]$. If $x$ is real and $|x| > 1$,
2503        then $\acos(x)$ is complex.
2504
2505        EXAMPLES:
2506            sage: pari('0.5').acos()
2507            1.047197551196597746154214461               # 32-bit
2508            1.0471975511965977461542144610931676281     # 64-bit
2509            sage: pari('1.1').acos()
2510            -0.4435682543851151891329110664*I             # 32-bit
2511            -0.44356825438511518913291106635249808665*I   # 64-bit
2512            sage: pari('1.1+I').acos()
2513            0.8493430542452523259630143655 - 1.097709866825328614547942343*I                         # 32-bit
2514            0.84934305424525232596301436546298780187 - 1.0977098668253286145479423425784723444*I     # 64-bit
2515        """
2516        _sig_on
2517        return P.new_gen(gacos(x.g, prec))
2518
2519    def acosh(gen x):
2520        r"""
2521        The principal branch of $\cosh^{-1}(x)$, so that
2522        $\Im(\acosh(x))$ belongs to $[0,Pi]$. If $x$ is real and $x <
2523        1$, then $\acosh(x)$ is complex.
2524
2525        EXAMPLES:
2526            sage: pari(2).acosh()
2527            1.316957896924816708625046347              # 32-bit
2528            1.3169578969248167086250463473079684440    # 64-bit
2529            sage: pari(0).acosh()
2530            1.570796326794896619231321692*I            # 32-bit
2531            1.5707963267948966192313216916397514421*I  # 64-bit
2532            sage: pari('I').acosh()
2533            0.8813735870195430252326093250 + 1.570796326794896619231321692*I    # 32-bit
2534            0.88137358701954302523260932497979230902 + 1.5707963267948966192313216916397514421*I   # 64-bit
2535        """
2536        _sig_on
2537        return P.new_gen(gach(x.g, prec))
2538
2539    def agm(gen x, y):
2540        r"""
2541        The arithmetic-geometric mean of x and y.  In the case of complex
2542        or negative numbers, the principal square root is always chosen.
2543        p-adic or power series arguments are also allowed.  Note that a p-adic
2544        AGM exists only if x/y is congruent to 1 modulo p (modulo 16 for p=2).
2545        x and y cannot both be vectors or matrices.
2546
2547        EXAMPLES:
2548            sage: pari('2').agm(2)                 
2549            2.000000000000000000000000000             # 32-bit
2550            2.0000000000000000000000000000000000000   # 64-bit
2551            sage: pari('0').agm(1)
2552            0
2553            sage: pari('1').agm(2)
2554            1.456791031046906869186432383             # 32-bit
2555            1.4567910310469068691864323832650819750   # 64-bit
2556            sage: pari('1+I').agm(-3)
2557            -0.9647317222908759112270275374 + 1.157002829526317260939086020*I                        # 32-bit
2558            -0.96473172229087591122702753739366831917 + 1.1570028295263172609390860195427517825*I    # 64-bit
2559        """
2560        t0GEN(y)
2561        _sig_on
2562        return P.new_gen(agm(x.g, t0, prec))
2563
2564    def arg(gen x):
2565        r"""
2566        arg(x): argument of x,such that $-\pi < \arg(x) \leq \pi$.
2567
2568        EXAMPLES:
2569            sage: pari('2+I').arg()               
2570            0.4636476090008061162142562315              # 32-bit
2571            0.46364760900080611621425623146121440203    # 64-bit
2572        """
2573        _sig_on
2574        return P.new_gen(garg(x.g,prec))
2575
2576    def asin(gen x):
2577        r"""
2578        The principal branch of $\sin^{-1}(x)$, so that
2579        $\Re(\asin(x))$ belongs to $[-\pi/2,\pi/2]$. If $x$ is real
2580        and $|x| > 1$ then $\asin(x)$ is complex.
2581
2582        EXAMPLES:
2583            sage: pari(pari('0.5').sin()).asin()
2584            0.5000000000000000000000000000               # 32-bit
2585            0.50000000000000000000000000000000000000     # 64-bit
2586            sage: pari(2).asin()
2587            1.570796326794896619231321692 + 1.316957896924816708625046347*I                      # 32-bit
2588            1.5707963267948966192313216916397514421 + 1.3169578969248167086250463473079684440*I  # 64-bit
2589        """
2590        _sig_on
2591        return P.new_gen(gasin(x.g, prec))
2592
2593    def asinh(gen x):
2594        r"""
2595        The principal branch of $\sinh^{-1}(x)$, so that $\Im(\asinh(x))$ belongs
2596        to $[-\pi/2,\pi/2]$.
2597
2598        EXAMPLES:
2599            sage: pari(2).asinh()
2600            1.443635475178810342493276740                # 32-bit
2601            1.4436354751788103424932767402731052694      # 64-bit
2602            sage: pari('2+I').asinh()
2603            1.528570919480998161272456185 + 0.4270785863924761254806468833*I      # 32-bit
2604            1.5285709194809981612724561847936733933 + 0.42707858639247612548064688331895685930*I      # 64-bit
2605        """
2606        _sig_on
2607        return P.new_gen(gash(x.g, prec))
2608
2609    def atan(gen x):
2610        r"""
2611        The principal branch of $\tan^{-1}(x)$, so that $\Re(\atan(x))$ belongs
2612        to $]-\pi/2, \pi/2[$.
2613
2614        EXAMPLES:
2615            sage: pari(1).atan()
2616            0.7853981633974483096156608458              # 32-bit
2617            0.78539816339744830961566084581987572104    # 64-bit
2618            sage: pari('1.5+I').atan()
2619            1.107148717794090503017065460 + 0.2554128118829953416027570482*I                         # 32-bit
2620            1.1071487177940905030170654601785370401 + 0.25541281188299534160275704815183096744*I     # 64-bit
2621        """
2622        _sig_on
2623        return P.new_gen(gatan(x.g, prec))
2624
2625    def atanh(gen x):
2626        r"""
2627        The principal branch of $\tanh^{-1}(x)$, so that
2628        $\Im(\atanh(x))$ belongs to $]-\pi/2,\pi/2]$.  If $x$ is real
2629        and $|x| > 1$ then $\atanh(x)$ is complex.
2630
2631        EXAMPLES:
2632            sage: pari(0).atanh()
2633            0.E-250   # 32-bit
2634            0.E-693   # 64-bit
2635            sage: pari(2).atanh()
2636            0.5493061443340548456976226185 + 1.570796326794896619231321692*I           # 32-bit
2637            0.54930614433405484569762261846126285232 + 1.5707963267948966192313216916397514421*I     # 64-bit
2638        """
2639        _sig_on
2640        return P.new_gen(gath(x.g, prec))
2641
2642    def bernfrac(gen x):
2643        r"""
2644        The Bernoulli number $B_x$, where $B_0 = 1$, $B_1 = -1/2$,
2645        $B_2 = 1/6,\ldots,$ expressed as a rational number. The
2646        argument $x$ should be of type integer.
2647
2648        EXAMPLES:
2649            sage: pari(18).bernfrac()
2650            43867/798
2651            sage: [pari(n).bernfrac() for n in range(10)]
2652            [1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0]
2653        """
2654        _sig_on
2655        return P.new_gen(bernfrac(x))
2656
2657    def fibonacci(gen x):
2658        r"""
2659        Return the fibonacci number of index x.
2660
2661        EXAMPLES:
2662            sage: pari(18).bernfrac()
2663            43867/798
2664            sage: [pari(n).bernfrac() for n in range(10)]
2665            [1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0]
2666        """
2667        _sig_on
2668        return P.new_gen(fibo(long(x)))
2669
2670    def bernreal(gen x):
2671        r"""
2672        The Bernoulli number $B_x$, as for the function bernfrac, but
2673        $B_x$ is returned as a real number (with the current
2674        precision).
2675
2676        EXAMPLES:
2677            sage: pari(18).bernreal()
2678            54.97117794486215538847117794                  # 32-bit
2679            54.971177944862155388471177944862155388        # 64-bit
2680        """
2681        _sig_on
2682        return P.new_gen(bernreal(x, prec))
2683
2684    def bernvec(gen x):
2685        r"""
2686        Creates a vector containing, as rational numbers, the
2687        Bernoulli numbers $B_0, B_2,\ldots, B_{2x}$.  This routine is
2688        obsolete.  Use bernfrac instead each time you need a Bernoulli
2689        number in exact form.
2690
2691        Note:  this  routine  is  implemented  using  repeated  independent
2692        calls to bernfrac, which is faster than the standard recursion in
2693        exact arithmetic.
2694
2695        EXAMPLES:
2696            sage: pari(8).bernvec()
2697            [1, 1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510]
2698            sage: [pari(2*n).bernfrac() for n in range(9)]
2699            [1, 1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6, -3617/510]
2700        """
2701        _sig_on
2702        return P.new_gen(bernvec(x))
2703
2704    def besselh1(gen nu, x):
2705        r"""
2706        The $H^1$-Bessel function of index $\nu$ and argument $x$.
2707
2708        EXAMPLES:
2709            sage: pari(2).besselh1(3)
2710            0.4860912605858910769078310941 - 0.1604003934849237296757682995*I                        # 32-bit
2711            0.48609126058589107690783109411498403480 - 0.16040039348492372967576829953798091810*I    # 64-bit
2712        """
2713        t0GEN(x)
2714        _sig_on
2715        return P.new_gen(hbessel1(nu.g, t0, prec))
2716
2717    def besselh2(gen nu, x):
2718        r"""
2719        The $H^2$-Bessel function of index $\nu$ and argument $x$.
2720
2721        EXAMPLES:
2722            sage: pari(2).besselh2(3)
2723            0.4860912605858910769078310941 + 0.1604003934849237296757682995*I                         # 32-bit
2724            0.48609126058589107690783109411498403480 + 0.16040039348492372967576829953798091810*I     # 64-bit
2725        """
2726        t0GEN(x)
2727        _sig_on
2728        return P.new_gen(hbessel2(nu.g, t0, prec))
2729
2730    def besselj(gen nu, x):
2731        r"""
2732        Bessel J function (Bessel function of the first kind), with
2733        index $\nu$ and argument $x$.  If $x$ converts to a power
2734        series, the initial factor $(x/2)^{\nu}/\Gamma(\nu+1)$ is
2735        omitted (since it cannot be represented in PARI when $\nu$ is not
2736        integral).
2737
2738        EXAMPLES:
2739            sage: pari(2).besselj(3)
2740            0.4860912605858910769078310941            # 32-bit
2741            0.48609126058589107690783109411498403480  # 64-bit
2742        """
2743        t0GEN(x)
2744        _sig_on
2745        return P.new_gen(jbessel(nu.g, t0, prec))
2746
2747    def besseljh(gen nu, x):
2748        """
2749        J-Bessel function of half integral index (Speherical Bessel
2750        function of the first kind).  More precisely, besseljh(n,x)
2751        computes $J_{n+1/2}(x)$ where n must an integer, and x is any
2752        complex value.  In the current implementation (PARI, version
2753        2.2.11), this function is not very accurate when $x$ is small.
2754
2755        EXAMPLES:
2756            sage: pari(2).besseljh(3)
2757            0.4127100322097159934374967959      # 32-bit
2758            0.41271003220971599343749679594186271499    # 64-bit
2759        """
2760        t0GEN(x)
2761        _sig_on
2762        return P.new_gen(jbesselh(nu.g, t0, prec))
2763
2764    def besseli(gen nu, x):
2765        """
2766        Bessel I function (Bessel function of the second kind), with
2767        index $\nu$ and argument $x$.  If $x$ converts to a power
2768        series, the initial factor $(x/2)^{\nu}/\Gamma(\nu+1)$ is
2769        omitted (since it cannot be represented in PARI when $\nu$ is not
2770        integral).
2771
2772        EXAMPLES:
2773            sage: pari(2).besseli(3)
2774            2.245212440929951154625478386              # 32-bit
2775            2.2452124409299511546254783856342650577    # 64-bit
2776            sage: pari(2).besseli('3+I')
2777            1.125394076139128134398383103 + 2.083138226706609118835787255*I      # 32-bit
2778            1.1253940761391281343983831028963896470 + 2.0831382267066091188357872547036161842*I    # 64-bit
2779        """
2780        t0GEN(x)
2781        _sig_on
2782        return P.new_gen(ibessel(nu.g, t0, prec))
2783
2784    def besselk(gen nu, x, long flag=0):
2785        """
2786        nu.besselk(x, flag=0): K-Bessel function (modified Bessel
2787        function of the second kind) of index nu, which can be
2788        complex, and argument x.
2789
2790        INPUT:
2791            nu -- a complex number
2792            x -- real number (positive or negative)
2793            flag -- default: 0 or 1: use hyperu  (hyperu is much slower for
2794                    small x, and doesn't work for negative x).
2795
2796        WARNING/TODO -- with flag = 1 this function is incredibly slow
2797        (on 64-bit Linux) as it is implemented using it from the C
2798        library, but it shouldn't be (e.g., it's not slow via the GP
2799        interface.)  Why?
2800
2801        EXAMPLES:
2802            sage: pari('2+I').besselk(3)
2803            0.04559077184075505871203211094 + 0.02891929465820812820828883526*I     # 32-bit
2804            0.045590771840755058712032110938791854704 + 0.028919294658208128208288835257608789842*I     # 64-bit
2805
2806            sage: pari('2+I').besselk(-3)
2807            -4.348708749867516799575863067 - 5.387448826971091267230878827*I        # 32-bit
2808            -4.3487087498675167995758630674661864255 - 5.3874488269710912672308788273655523057*I  # 64-bit
2809
2810            sage.: pari('2+I').besselk(300, flag=1)
2811            3.742246033197275082909500148 E-132 + 2.490710626415252262644383350 E-134*I      # 32-bit
2812            3.7422460331972750829095001475885825717 E-132 + 2.4907106264152522626443833495225745762 E-134*I   # 64-bit
2813
2814        """
2815        t0GEN(x)
2816        _sig_on
2817        return P.new_gen(kbessel0(nu.g, t0, flag, prec))
2818
2819    def besseln(gen nu, x):
2820        """
2821        nu.besseln(x): Bessel N function (Spherical Bessel function of
2822        the second kind) of index nu and argument x.
2823
2824        EXAMPLES:
2825            sage: pari('2+I').besseln(3)
2826            -0.2807755669582439141676487005 - 0.4867085332237257928816949747*I     # 32-bit
2827            -0.28077556695824391416764870046044688871 - 0.48670853322372579288169497466916637395*I    # 64-bit
2828        """
2829        t0GEN(x)
2830        _sig_on
2831        return P.new_gen(nbessel(nu.g, t0, prec))
2832
2833    def cos(gen self):
2834        """
2835        The cosine function.
2836
2837        EXAMPLES:
2838            sage: x = pari('1.5')
2839            sage: x.cos()
2840            0.07073720166770291008818985142     # 32-bit
2841            0.070737201667702910088189851434268709084    # 64-bit
2842            sage: pari('1+I').cos()
2843            0.8337300251311490488838853943 - 0.9888977057628650963821295409*I   # 32-bit
2844            0.83373002513114904888388539433509447980 - 0.98889770576286509638212954089268618864*I   # 64-bit
2845            sage: pari('x+O(x^8)').cos()
2846            1 - 1/2*x^2 + 1/24*x^4 - 1/720*x^6 + 1/40320*x^8 + O(x^9)
2847        """
2848        _sig_on
2849        return P.new_gen(gcos(self.g, prec))
2850
2851    def cosh(gen self):
2852        """
2853        The hyperbolic cosine function.
2854
2855        EXAMPLES:
2856            sage: x = pari('1.5')
2857            sage: x.cosh()
2858            2.352409615243247325767667965               # 32-bit
2859            2.3524096152432473257676679654416441702     # 64-bit
2860            sage: pari('1+I').cosh()
2861            0.8337300251311490488838853943 + 0.9888977057628650963821295409*I                       # 32-bit
2862            0.83373002513114904888388539433509447980 + 0.98889770576286509638212954089268618864*I   # 64-bit
2863            sage: pari('x+O(x^8)').cosh()
2864            1 + 1/2*x^2 + 1/24*x^4 + 1/720*x^6 + O(x^8)
2865        """
2866        _sig_on
2867        return P.new_gen(gch(self.g, prec))
2868
2869    def cotan(gen x):
2870        """
2871        The cotangent of x.
2872
2873        EXAMPLES:
2874            sage: pari(5).cotan()
2875            -0.2958129155327455404277671681     # 32-bit
2876            -0.29581291553274554042776716808248528607    # 64-bit
2877
2878        On a 32-bit computer computing the cotangent of $\pi$ doesn't
2879        raise an error, but instead just returns a very large number.
2880        On a 64-bit computer it raises a RuntimeError.
2881       
2882            sage: pari('Pi').cotan() 
2883            1.980704062 E28                      # 32-bit
2884            Traceback (most recent call last):   # 64-bit
2885            ...                                  # 64-bit
2886            PariError: division by zero (46)     # 64-bit
2887        """
2888        _sig_on
2889        return P.new_gen(gcotan(x.g, prec))
2890
2891    def dilog(gen x):
2892        r"""
2893        The principal branch of the dilogarithm of $x$, i.e. the analytic
2894        continuation of the power series $\log_2(x) = \sum_{n>=1} x^n/n^2$.
2895
2896        EXAMPLES:
2897            sage: pari(1).dilog()
2898            1.644934066848226436472415167              # 32-bit
2899            1.6449340668482264364724151666460251892    # 64-bit
2900            sage: pari('1+I').dilog()
2901            0.6168502750680849136771556875 + 1.460362116753119547679775739*I    # 32-bit
2902            0.61685027506808491367715568749225944595 + 1.4603621167531195476797757394917875976*I   # 64-bit
2903        """
2904        _sig_on
2905        return P.new_gen(dilog(x.g, prec))
2906
2907    def eint1(gen x, long n=0):
2908        r"""
2909        x.eint1({n}): exponential integral E1(x):
2910        $$
2911            \int_{x}^{\infty} \frac{e^{-t}}{t} dt
2912        $$
2913        If n is present, output the vector
2914            [eint1(x), eint1(2*x), ..., eint1(n*x)].
2915        This is faster than repeatedly calling eint1(i*x).
2916
2917        REFERENCE: See page 262, Prop 5.6.12, of Cohen's book
2918        "A Course in Computational Algebraic Number Theory".
2919
2920        EXAMPLES:
2921       
2922        """
2923        if n <= 0:
2924            _sig_on           
2925            return P.new_gen(eint1(x.g, prec))
2926        else:
2927            _sig_on
2928            return P.new_gen(veceint1(x.g, stoi(n), prec))
2929
2930    def erfc(gen x):
2931        r"""
2932        Return the complementary error function:
2933             $$(2/\sqrt{\pi}) \int_{x}^{\infty} e^{-t^2} dt.$$
2934
2935        EXAMPLES:
2936            sage: pari(1).erfc()
2937            0.1572992070502851306587793649                # 32-bit
2938            0.15729920705028513065877936491739074070      # 64-bit
2939        """
2940        _sig_on
2941        return P.new_gen(gerfc(x.g, prec))
2942
2943    def eta(gen x, flag=0):
2944        r"""
2945        x.eta({flag=0}): if flag=0, $\eta$ function without the $q^{1/24}$;
2946        otherwise $\eta$ of the complex number $x$ in the upper half plane
2947        intelligently computed using $\SL(2,\Z)$ transformations.
2948
2949        DETAILS: This functions computes the following.  If the input
2950        $x$ is a complex number with positive imaginary part, the
2951        result is $\prod_{n=1}^{\infty} (q-1^n)$, where $q=e^{2 i \pi
2952        x}$.  If $x$ is a power series (or can be converted to a power
2953        series) with positive valuation, the result it
2954        $\prod_{n=1}^{\infty} (1-x^n)$.
2955
2956        EXAMPLES:
2957            sage: pari('I').eta()
2958            0.9981290699259585132799623222             # 32-bit
2959            0.99812906992595851327996232224527387813   # 64-bit
2960        """
2961        if flag == 1:
2962            _sig_on
2963            return P.new_gen(trueeta(x.g, prec))
2964        _sig_on
2965        return P.new_gen(eta(x.g, prec))
2966
2967    def exp(gen self):
2968        """
2969        x.exp(): exponential of x.
2970
2971        EXAMPLES:
2972            sage: pari(0).exp()
2973            1.000000000000000000000000000               # 32-bit
2974            1.0000000000000000000000000000000000000     # 64-bit
2975            sage: pari(1).exp()
2976            2.718281828459045235360287471               # 32-bit
2977            2.7182818284590452353602874713526624978     # 64-bit
2978            sage: pari('x+O(x^8)').exp()
2979            1 + x + 1/2*x^2 + 1/6*x^3 + 1/24*x^4 + 1/120*x^5 + 1/720*x^6 + 1/5040*x^7 + O(x^8)
2980        """
2981        _sig_on       
2982        return P.new_gen(gexp(self.g, prec))
2983
2984    def gamma(gen s, precision=0):
2985        """
2986        s.gamma({precision}): Gamma function at s.
2987       
2988        INPUT:
2989            s -- gen (real or complex number
2990            precision -- optional precisiion
2991
2992        OUTPUT:
2993            gen -- value of the Gamma function at s.
2994
2995        EXAMPLES:
2996            sage: pari(2).gamma()
2997            1.000000000000000000000000000              # 32-bit
2998            1.0000000000000000000000000000000000000    # 64-bit
2999            sage: pari(5).gamma()
3000            24.00000000000000000000000000              # 32-bit
3001            24.000000000000000000000000000000000000    # 64-bit
3002            sage: pari('1+I').gamma()
3003            0.4980156681183560427136911175 - 0.1549498283018106851249551305*I    # 32-bit
3004            0.49801566811835604271369111746219809195 - 0.15494982830181068512495513048388660520*I    # 64-bit
3005        """
3006        if not precision: precision = prec
3007        _sig_on
3008        return P.new_gen(ggamma(s.g, precision))
3009       
3010    def gammah(gen s):
3011        """
3012        x.gammah(): Gamma function evaluated at the argument x+1/2,
3013        for x an integer.
3014       
3015        EXAMPLES:
3016            sage: pari(2).gammah()     
3017            1.329340388179137020473625613               # 32-bit
3018            1.3293403881791370204736256125058588871     # 64-bit
3019            sage: pari(5).gammah()
3020            52.34277778455352018114900849               # 32-bit
3021            52.342777784553520181149008492418193679     # 64-bit
3022            sage: pari('1+I').gammah()
3023            0.5753151880634517207185443722 + 0.08821067754409390991246464371*I     # 32-bit
3024            0.57531518806345172071854437217501119058 + 0.088210677544093909912464643706507454993*I     # 64-bit
3025        """
3026        _sig_on
3027        return P.new_gen(ggamd(s.g, prec))
3028
3029    def hyperu(gen a, b, x):
3030        r"""
3031        a.hyperu(b,x): U-confluent hypergeometric function.
3032
3033        WARNING/TODO: This function is \emph{extremely slow} as
3034        implemented when used from the C library.  If you use the GP
3035        interpreter inteface it is vastly faster, so clearly this
3036        issue could be fixed with a better understanding of GP/PARI.
3037        Volunteers?
3038
3039        EXAMPLES:
3040            sage.: pari(1).hyperu(2,3)
3041            0.3333333333333333333333333333              # 32-bit
3042            0.33333333333333333333333333333333333333    # 64-bit
3043        """
3044        t0GEN(b)
3045        t1GEN(x)
3046        _sig_on
3047        return P.new_gen(hyperu(a.g, t0, t1, prec))
3048       
3049
3050    def incgam(gen s, x, y=None, precision=0):
3051        r"""
3052        s.incgam(x, {y}, {precision}): incomplete gamma function. y
3053        is optional and is the precomputed value of gamma(s).
3054
3055        NOTE: This function works for any complex input (unlike in
3056        older version of PARI).
3057
3058        WARNING/TODO: This function is \emph{extremely slow} as
3059        implemented when used from the C library.  If you use the GP
3060        interpreter inteface it is vastly faster, so clearly this
3061        issue could be fixed with a better understanding of GP/PARI.
3062        Volunteers?
3063
3064        INPUT:
3065            s, x, y -- gens
3066            precision -- option precision
3067
3068        OUTPUT:
3069            gen -- value of the incomplete Gamma function at s.
3070
3071        EXAMPLES:
3072            sage.: pari('1+I').incgam('3-I')
3073            -0.04582978599199457259586742326 + 0.04336968187266766812050474478*I        # 32-bit
3074            -0.045829785991994572595867423261490338705 + 0.043369681872667668120504744775954724733*I    # 64-bit
3075        """
3076        if not precision:
3077            precision = prec
3078        t0GEN(x)
3079        if y is None:
3080            _sig_on
3081            return P.new_gen(incgam(s.g, t0, precision))
3082        else:
3083            t1GEN(y)
3084            _sig_on
3085            return P.new_gen(incgam0(s.g, t0, t1, precision))
3086
3087    def incgamc(gen s, x):
3088        r"""
3089        s.incgamc(x): complementary incomplete gamma function.
3090
3091        The arguments $x$ and $s$ are complex numbers such that $s$ is
3092        not a pole of $\Gamma$ and $|x|/(|s|+1)$ is not much larger
3093        than $1$ (otherwise, the convergence is very slow).  The
3094        function returns the value of the integral $\int_{0}^{x}
3095        e^{-t} t^{s-1} dt.$
3096
3097        EXAMPLES:
3098            sage: pari(1).incgamc(2)
3099            0.8646647167633873081060005050               # 32-bit
3100            0.86466471676338730810600050502751559659     # 64-bit
3101        """
3102        t0GEN(x)
3103        _sig_on
3104        return P.new_gen(incgamc(s.g, t0, prec))
3105
3106   
3107    def log(gen self):
3108        r"""
3109        x.log(): natural logarithm of x.
3110
3111        This function returns the principal branch of the natural
3112        logarithm of $x$, i.e., the branch such that $\Im(\log(x)) \in
3113        ]-\pi, \pi].$ The result is complex (with imaginary part equal
3114        to $\pi$) if $x\in \R$ and $x<0$.  In general, the algorithm
3115        uses the formula
3116        $$
3117            \log(x) \simeq \frac{\pi}{2{\rm agm}(1,4/s)} - m\log(2),
3118        $$
3119        if $s=x 2^m$ is large enough.  (The result is exact to $B$
3120        bits provided that $s>2^{B/2}$.)  At low accuracies, this
3121        function computes $\log$ using the series expansion near $1$.
3122
3123        Note that $p$-adic arguments can also be given as input,
3124        with the convention that $\log(p)=0$.  Hence, in
3125        particular, $\exp(\log(x))/x$ is not in general
3126        equal to $1$ but instead to a $(p-1)th$ root of
3127        unity (or $\pm 1$ if $p=2$) times a power of $p$.
3128
3129        EXAMPLES:
3130            sage: pari(5).log()
3131            1.609437912434100374600759333                 # 32-bit
3132            1.6094379124341003746007593332261876395       # 64-bit
3133            sage: pari('I').log()
3134            0.E-250 + 1.570796326794896619231321692*I             # 32-bit
3135            0.E-693 + 1.5707963267948966192313216916397514421*I   # 64-bit
3136        """
3137        _sig_on       
3138        return P.new_gen(glog(self.g, prec))
3139
3140    def lngamma(gen x):
3141        r"""
3142        x.lngamma(): logarithm of the gamma function of x.
3143
3144        This function returns the principal branch of the logarithm of
3145        the gamma function of $x$.  The function $\log(\Gamma(x))$ is
3146        analytic on the complex plane with non-positive integers
3147        removed.  This function can have much larger inputs than
3148        $\Gamma$ itself.
3149
3150        The $p$-adic analogue of this function is unfortunately not
3151        implemented.
3152
3153        EXAMPLES:
3154            sage: pari(100).lngamma()
3155            359.1342053695753987760440105                # 32-bit
3156            359.13420536957539877604401046028690961      # 64-bit
3157        """
3158        _sig_on
3159        return P.new_gen(glngamma(x.g,prec))
3160
3161    def polylog(gen x, long m, flag=0):
3162        """
3163        x.polylog(m,{flag=0}): m-th polylogarithm of x. flag is
3164        optional, and can be 0: default, 1: D_m~-modified m-th polylog
3165        of x, 2: D_m-modified m-th polylog of x, 3: P_m-modified m-th
3166        polylog of x.
3167
3168        TODO: Add more explanation, copied from the PARI manual.
3169
3170        EXAMPLES:
3171            sage: pari(10).polylog(3)
3172            5.641811414751341250600725771 - 8.328202076980270580884185850*I                          # 32-bit
3173            5.6418114147513412506007257705287671110 - 8.3282020769802705808841858505904310076*I      # 64-bit
3174            sage: pari(10).polylog(3,0)
3175            5.641811414751341250600725771 - 8.328202076980270580884185850*I                          # 32-bit
3176            5.6418114147513412506007257705287671110 - 8.3282020769802705808841858505904310076*I      # 64-bit
3177            sage: pari(10).polylog(3,1)
3178            0.5237784535024110488342571116              # 32-bit
3179            0.52377845350241104883425711161605950842    # 64-bit
3180            sage: pari(10).polylog(3,2)
3181            -0.4004590561634505605364328952             # 32-bit
3182            -0.40045905616345056053643289522452400363   # 64-bit
3183        """
3184        _sig_on
3185        return P.new_gen(polylog0(m, x.g, flag, prec))
3186
3187    def psi(gen x):
3188        r"""
3189        x.psi(): psi-function at x.
3190
3191        Return the $\psi$-function of $x$, i.e., the logarithmic
3192        derivative $\Gamma'(x)/\Gamma(x)$.
3193
3194        EXAMPLES:
3195            sage: pari(1).psi()
3196            -0.5772156649015328606065120901              # 32-bit
3197            -0.57721566490153286060651209008240243104    # 64-bit
3198        """
3199        _sig_on
3200        return P.new_gen(gpsi(x.g, prec))
3201
3202
3203    def sin(gen x):
3204        """
3205        x.sin(): The sine of x.
3206
3207        EXAMPLES:
3208            sage: pari(1).sin()
3209            0.8414709848078965066525023216             # 32-bit
3210            0.84147098480789650665250232163029899962   # 64-bit
3211            sage: pari('1+I').sin()
3212            1.298457581415977294826042366 + 0.6349639147847361082550822030*I                       # 32-bit
3213            1.2984575814159772948260423658078156203 + 0.63496391478473610825508220299150978151*I   # 64-bit
3214        """
3215        _sig_on
3216        return P.new_gen(gsin(x.g, prec))
3217
3218    def sinh(gen self):
3219        """
3220        The hyperbolic sine function.
3221
3222        EXAMPLES:
3223            sage: pari(0).sinh()
3224            0.E-250   # 32-bit
3225            0.E-693   # 64-bit
3226            sage: pari('1+I').sinh()
3227            0.6349639147847361082550822030 + 1.298457581415977294826042366*I                         # 32-bit
3228            0.63496391478473610825508220299150978151 + 1.2984575814159772948260423658078156203*I     # 64-bit
3229        """
3230        _sig_on
3231        return P.new_gen(gsh(self.g, prec))
3232
3233    def sqr(gen x):
3234        """
3235        x.sqr(): square of x. NOT identical to x*x.
3236
3237        TODO: copy extensive notes about this function
3238        from PARI manual.  Put examples below.
3239
3240        EXAMPLES:
3241            sage: pari(2).sqr()
3242            4
3243        """
3244        _sig_on
3245        return P.new_gen(gsqr(x.g))
3246   
3247
3248    def sqrt(gen x, precision=0):
3249        """
3250        x.sqrt({precision}): The square root of x.
3251
3252        EXAMPLES:
3253            sage: pari(2).sqrt()
3254            1.414213562373095048801688724               # 32-bit
3255            1.4142135623730950488016887242096980786     # 64-bit
3256        """
3257        if not precision: precision = prec
3258        _sig_on
3259        return P.new_gen(gsqrt(x.g, precision))
3260
3261    def sqrtn(gen x, n):
3262        r"""
3263        x.sqrtn(n): return the principal branch of the n-th root
3264        of x, i.e., the one such that
3265              $\arg(\sqrt(x)) \in ]-\pi/n, \pi/n]$.
3266        Also returns a second argument which is a suitable root
3267        of unity allowing one to recover all the other roots.
3268        If it was not possible to find such a number, then this
3269        second return value is 0.  If the argument is present and
3270        no square root exists, return 0 instead of raising an error.
3271
3272        NOTE: intmods (modulo a prime) and $p$-adic numbers are
3273        allowed as arguments.
3274
3275        INPUT:
3276            x -- gen
3277            n -- integer
3278        OUTPUT:
3279            gen -- principal n-th root of x
3280            gen -- z that gives the other roots
3281           
3282        EXAMPLES:
3283            sage: s, z = pari(2).sqrtn(5)
3284            sage: z
3285            0.3090169943749474241022934172 + 0.9510565162951535721164393334*I                         # 32-bit
3286            0.30901699437494742410229341718281905886 + 0.95105651629515357211643933337938214340*I     # 64-bit
3287            sage: s
3288            1.148698354997035006798626947               # 32-bit
3289            1.1486983549970350067986269467779275894     # 64-bit
3290            sage: s^5
3291            2.000000000000000000000000000               # 32-bit
3292            2.0000000000000000000000000000000000000     # 64-bit
3293            sage: (s*z)^5
3294            2.000000000000000000000000000 - 1.396701498 E-250*I                      # 32-bit
3295            2.0000000000000000000000000000000000000 - 1.0689317613194482765 E-693*I  # 64-bit
3296        """
3297        # TODO: ???  lots of good examples in the PARI docs ???
3298        cdef GEN zetan
3299        t0GEN(n)
3300        _sig_on
3301        ans = P.new_gen_noclear(gsqrtn(x.g, t0, &zetan, prec))
3302        return ans, P.new_gen(zetan)
3303
3304    def tan(gen x):
3305        """
3306        x.tan() -- tangent of x
3307
3308        EXAMPLES:
3309            sage: pari(2).tan()
3310            -2.185039863261518991643306102                   # 32-bit
3311            -2.1850398632615189916433061023136825434         # 64-bit
3312            sage: pari('I').tan()
3313            0.E-250 + 0.7615941559557648881194582826*I            # 32-bit
3314            0.E-693 + 0.76159415595576488811945828260479359041*I  # 64-bit
3315        """
3316        _sig_on
3317        return P.new_gen(gtan(x.g, prec))
3318
3319    def tanh(gen x):
3320        """
3321        x.tanh() -- hyperbolic tangent of x
3322
3323        EXAMPLES:
3324            sage: pari(1).tanh()
3325            0.7615941559557648881194582826             # 32-bit
3326            0.76159415595576488811945828260479359041   # 64-bit
3327            sage: pari('I').tanh()
3328            0.E-250 + 1.557407724654902230506974807*I              # 32-bit
3329            -5.344658806597241382 E-694 + 1.5574077246549022305069748074583601731*I  # 64-bit
3330        """
3331        _sig_on
3332        return P.new_gen(gth(x.g, prec))
3333
3334    def teichmuller(gen x):
3335        r"""
3336        teichmuller(x): teichmuller character of p-adic number x.
3337
3338        This is the unique $(p-1)$th root of unity congruent to
3339        $x/p^{v_p(x)}$ modulo $p$.
3340
3341        EXAMPLES:
3342            sage: pari('2+O(7^5)').teichmuller()
3343            2 + 4*7 + 6*7^2 + 3*7^3 + O(7^5)
3344        """
3345        _sig_on
3346        return P.new_gen(teich(x.g))
3347
3348    def theta(gen q, z):
3349        """
3350        q.theta(z): Jacobi sine theta-function.
3351
3352        EXAMPLES:
3353            sage: pari('0.5').theta(2)
3354            1.632025902952598833772353216               # 32-bit
3355            1.6320259029525988337723532162682089972     # 64-bit
3356        """
3357        t0GEN(z)
3358        _sig_on
3359        return P.new_gen(theta(q.g, t0, prec))
3360
3361    def thetanullk(gen q, long k):
3362        """
3363        q.thetanullk(k): return the k-th derivative at z=0 of theta(q,z)
3364        EXAMPLES:
3365            sage: pari('0.5').thetanullk(1)
3366            0.5489785325603405618549383537             # 32-bit
3367            0.54897853256034056185493835370857284861   # 64-bit
3368        """
3369        _sig_on
3370        return P.new_gen(thetanullk(q.g, k, prec))
3371
3372    def weber(gen x, flag=0):
3373        r"""
3374        x.weber({flag=0}): One of Weber's f function of x.
3375        flag is optional, and can be
3376           0: default, function f(x)=exp(-i*Pi/24)*eta((x+1)/2)/eta(x)
3377              such that $j=(f^{24}-16)^3/f^{24}$,
3378           1: function f1(x)=eta(x/2)/eta(x) such that
3379              $j=(f1^24+16)^3/f2^{24}$,
3380           2: function f2(x)=sqrt(2)*eta(2*x)/eta(x) such that
3381              $j=(f2^{24}+16)^3/f2^{24}$.
3382
3383        TODO: Add further explanation from PARI manual.
3384
3385        EXAMPLES:
3386            sage: pari('I').weber()
3387            1.189207115002721066717499971 - 6.98350749 E-251*I     # 32-bit
3388            1.1892071150027210667174999705604759153 + 0.E-693*I    # 64-bit
3389            sage: pari('I').weber(1)   
3390            1.090507732665257659207010656             # 32-bit
3391            1.0905077326652576592070106557607079790   # 64-bit
3392            sage: pari('I').weber(2)
3393            1.090507732665257659207010656             # 32-bit
3394            1.0905077326652576592070106557607079790   # 64-bit
3395        """
3396        _sig_on
3397        return P.new_gen(weber0(x.g, flag, prec))
3398   
3399
3400    def zeta(gen s, precision=0):
3401        """
3402        zeta(s): Riemann zeta function at s with s a complex
3403                 or a p-adic number.
3404
3405        TODO: Add extensive explanation from PARI user's manual.
3406
3407        INPUT:
3408            s -- gen (real or complex number)
3409
3410        OUTPUT:
3411            gen -- value of zeta at s.
3412
3413        EXAMPLES:
3414            sage: pari(2).zeta()
3415            1.644934066848226436472415167             # 32-bit
3416            1.6449340668482264364724151666460251892   # 64-bit
3417            sage: pari('Pi^2/6')
3418            1.644934066848226436472415167             # 32-bit
3419            1.6449340668482264364724151666460251892   # 64-bit
3420            sage: pari(3).zeta()
3421            1.202056903159594285399738162             # 32-bit
3422            1.2020569031595942853997381615114499908   # 64-bit
3423        """
3424        if not precision: precision = prec
3425        _sig_on
3426        return P.new_gen(gzeta(s.g, precision))
3427
3428    ###########################################
3429    # 4: NUMBER THEORETICAL functions
3430    ###########################################
3431   
3432    def bezout(gen x, y):
3433        cdef gen u, v, g
3434        cdef GEN U, V, G
3435        t0GEN(y)
3436        _sig_on
3437        G = gbezout(x.g, t0, &U, &V)
3438        _sig_off
3439        g = P.new_gen_noclear(G)
3440        u = P.new_gen_noclear(U)
3441        v = P.new_gen(V)
3442        return g, u, v
3443
3444    def binomial(gen x, long k):
3445        _sig_on
3446        return P.new_gen(binome(x.g, k))
3447
3448    def contfrac(gen x, b=0, long lmax=0):
3449        """
3450        contfrac(x,{b},{lmax}): continued fraction expansion of x (x
3451        rational, real or rational function). b and lmax are both
3452        optional, where b is the vector of numerators of the continued
3453        fraction, and lmax is a bound for the number of terms in the
3454        continued fraction expansion.
3455        """
3456        t0GEN(b)
3457        _sig_on
3458        return P.new_gen(contfrac0(x.g, t0, lmax))
3459
3460    def contfracpnqn(gen x, b=0, long lmax=0):
3461        """
3462        contfracpnqn(x): [p_n,p_{n-1}; q_n,q_{n-1}] corresponding to the continued
3463        fraction x.
3464        """
3465        _sig_on
3466        return P.new_gen(pnqn(x.g))
3467   
3468
3469    def gcd(gen x, y, long flag=0):
3470        """
3471        gcd(x,{y},{flag=0}): greatest common divisor of x and y. flag
3472        is optional, and can be 0: default, 1: use the modular gcd
3473        algorithm (x and y must be polynomials), 2 use the
3474        subresultant algorithm (x and y must be polynomials)
3475        """
3476        t0GEN(y)
3477        _sig_on
3478        return P.new_gen(gcd0(x.g, t0, flag))
3479
3480    def issquare(gen x, find_root=False):
3481        """
3482        issquare(x,{&n}): true(1) if x is a square, false(0) if not.
3483        If find_root is given, also returns the exact square root if
3484        it was computed.
3485        """
3486        cdef GEN G, t
3487        cdef gen g
3488        if find_root:
3489            _sig_on
3490            t = gcarrecomplet(x.g, &G)
3491            _sig_off
3492            v = bool(P.new_gen_noclear(t))
3493            if v:
3494                return v, P.new_gen(G)
3495            else:
3496                return v, None
3497        else:
3498            _sig_on
3499            return P.new_gen(gcarreparfait(x.g))
3500
3501
3502    def issquarefree(gen self):
3503        """
3504        EXAMPLES:
3505            sage: pari(10).issquarefree()
3506            True
3507            sage: pari(20).issquarefree()
3508            False
3509        """
3510        _sig_on
3511        t = bool(issquarefree(self.g))
3512        _sig_off
3513        return t
3514
3515    def lcm(gen x, y):
3516        """
3517        Return the least common multiple of x and y.
3518        EXAMPLES:
3519            sage: pari(10).lcm(15)
3520            30
3521        """
3522        t0GEN(y)
3523        _sig_on
3524        return P.new_gen(glcm(x.g, t0))
3525
3526    def numdiv(gen n):
3527        """
3528        Return the number of divisors of the integer n.
3529
3530        EXAMPLES:
3531            sage: pari(10).numdiv()
3532            4
3533        """
3534        _sig_on
3535        return P.new_gen(gnumbdiv(n.g))
3536
3537    def phi(gen n):
3538        """
3539        Return the Euler phi function of n.
3540        EXAMPLES:
3541            sage: pari(10).phi()
3542            4
3543        """
3544        _sig_on
3545        return P.new_gen(phi(n.g))
3546
3547    def primepi(gen x):
3548        """
3549        Return the number of primes $\leq x$.
3550       
3551        EXAMPLES:
3552            sage: pari(7).primepi()
3553            4
3554            sage: pari(100).primepi()
3555            25
3556            sage: pari(1000).primepi()
3557            168
3558            sage: pari(100000).primepi()
3559            9592
3560        """
3561        _sig_on
3562        return P.new_gen(primepi(x.g))
3563
3564    def sumdiv(gen n):
3565        """
3566        Return the sum of the divisors of $n$.
3567       
3568        EXAMPLES:
3569            sage: pari(10).sumdiv()
3570            18
3571        """
3572        _sig_on
3573        return P.new_gen(sumdiv(n.g))
3574
3575    def sumdivk(gen n, long k):
3576        """
3577        Return the sum of the k-th powers of the divisors of n.
3578       
3579        EXAMPLES:
3580            sage: pari(10).sumdivk(2)
3581            130
3582        """
3583        _sig_on
3584        return P.new_gen(sumdivk(n.g, k))
3585
3586    def xgcd(gen x, y):
3587        """
3588        Returns u,v,d such that d=gcd(x,y) and u*x+v*y=d.
3589       
3590        EXAMPLES:
3591            sage: pari(10).xgcd(15)
3592            (5, -1, 1)
3593        """
3594        return x.bezout(y)
3595
3596
3597    ##################################################
3598    # 5: Elliptic curve functions
3599    ##################################################
3600
3601    def ellinit(self, int flag=0, precision=0):
3602        if not precision:
3603            precision = prec
3604        _sig_on
3605        return P.new_gen(ellinit0(self.g, flag, precision))
3606
3607    def ellglobalred(self):
3608        _sig_on       
3609        return self.new_gen(globalreduction(self.g))
3610
3611    def elladd(self, z0, z1):
3612        """
3613        elladd(self, z0, z1)
3614
3615        Sum of the points z0 and z1 on this elliptic curve.
3616
3617        INPUT:
3618            self -- elliptic curve E
3619            z0 -- point on E
3620            z1 -- point on E
3621           
3622        OUTPUT:
3623            point on E
3624
3625        EXAMPLES:
3626        First we create an elliptic curve:
3627       
3628            sage: e = pari([0, 1, 1, -2, 0]).ellinit()
3629            sage: str(e)[:65]   # first part of output
3630            '[0, 1, 1, -2, 0, 4, -4, 1, -3, 112, -856, 389, 1404928/389, [0.90'
3631           
3632        Next we add two points on the elliptic curve.  Notice that
3633        the Python lists are automatically converted to PARI objects so
3634        you don't have to do that explicitly in your code.
3635       
3636            sage: e.elladd([1,0,1], [-1,1,1])
3637            [-3/4, -15/8]
3638        """
3639        t0GEN(z0); t1GEN(z1)
3640        _sig_on
3641        return self.new_gen(addell(self.g, t0, t1))
3642
3643    def ellak(self, n):
3644        r"""
3645        e.ellak(n): Returns the coefficient $a_n$ of the $L$-function of
3646        the elliptic curve e, i.e. the coefficient of a newform of
3647        weight 2 newform.
3648
3649        \begin{notice}
3650        The curve $e$ {\em must} be a medium or long vector of the type given
3651        by ellinit. For this function to work for every n and not just
3652        those prime to the conductor, e must be a minimal Weierstrass
3653        equation. If this is not the case, use the function
3654        ellminimalmodel first before using ellak (or you will get
3655        INCORRECT RESULTS!)
3656        \end{notice}
3657
3658        INPUT:
3659            e -- a PARI elliptic curve.
3660            n -- integer ..
3661
3662        EXAMPLES:
3663            sage: e = pari([0, -1, 1, -10, -20]).ellinit()
3664            sage: e.ellak(6)
3665            2
3666            sage: e.ellak(2005)       
3667            2
3668            sage: e.ellak(-1)
3669            0
3670            sage: e.ellak(0)
3671            0
3672        """
3673        t0GEN(n)
3674        _sig_on
3675        return self.new_gen(akell(self.g, t0))
3676
3677
3678    def ellan(self, long n):
3679        """
3680        EXAMPLES:
3681            sage: e = pari([0, -1, 1, -10, -20]).ellinit()
3682            sage: e.ellan(3)
3683            [1, -2, -1]
3684            sage: e.ellan(20)
3685            [1, -2, -1, 2, 1, 2, -2, 0, -2, -2, 1, -2, 4, 4, -1, -4, -2, 4, 0, 2]
3686            sage: e.ellan(-1)
3687            []
3688        """
3689        _sig_on
3690        return self.new_gen(anell(self.g, n))
3691
3692    def ellap(self, p):
3693        r"""
3694        e.ellap(p): Returns the prime-indexed coefficient $a_p$ of the
3695        $L$-function of the elliptic curve $e$, i.e. the coefficient of a
3696        newform of weight 2 newform.
3697
3698        \begin{notice}
3699        If p is not prime, this function will return an {\bf incorrect}
3700        answer.
3701
3702        The curve e must be a medium or long vector of the type given
3703        by ellinit. For this function to work for every n and not just
3704        those prime to the conductor, e must be a minimal Weierstrass
3705        equation. If this is not the case, use the function
3706        ellminimalmodel first before using ellak (or you will get
3707        INCORRECT RESULTS!)
3708        \end{notice}
3709
3710        INPUT:
3711            e -- a PARI elliptic curve.
3712            p -- prime integer ..
3713
3714        EXAMPLES:
3715            sage: e = pari([0, -1, 1, -10, -20]).ellinit()
3716            sage: e.ellap(2)
3717            -2
3718            sage: e.ellap(2003)
3719            4
3720            sage: e.ellak(-1)
3721            0
3722        """
3723        t0GEN(p)
3724        _sig_on
3725        return self.new_gen(apell(self.g, t0))
3726
3727
3728    def ellbil(self, z0, z1):
3729        """
3730        EXAMPLES:
3731            sage: e = pari([0,1,1,-2,0]).ellinit()
3732            sage: e.ellbil([1, 0, 1], [-1, 1, 1])
3733            0.4181889844988605856298894582              # 32-bit
3734             0.41818898449886058562988945821587638238   # 64-bit
3735        """
3736##         Increasing the precision does not increase the precision
3737##         result, since quantities related to the elliptic curve were
3738##         computed to low precision.
3739##             sage: set_real_precision(10)
3740##             sage: e.ellbil([1, 0, 1], [-1, 1, 1])
3741##             0.4181889844988605856298894585
3742##         However, if we recompute the elliptic curve after increasing
3743##         the precision, then the bilinear pairing will be computed to
3744##         higher precision as well.
3745##             sage: e = pari([0,1,1,-2,0]).ellinit()
3746##             sage: e.ellbil([1, 0, 1], [-1, 1, 1])
3747##             0.4181889844988605856298894582
3748##             sage: set_real_precision(5)
3749        t0GEN(z0); t1GEN(z1)
3750        _sig_on
3751        return self.new_gen(bilhell(self.g, t0, t1, prec))
3752
3753    def ellchangecurve(self, ch):
3754        """
3755        EXAMPLES:
3756            sage: e = pari([1,2,3,4,5]).ellinit()
3757            sage: e.ellglobalred()
3758            [10351, [1, -1, 0, -1], 1]
3759            sage: f = e.ellchangecurve([1,-1,0,-1])
3760            sage: f[:5]
3761            [1, -1, 0, 4, 3]
3762        """
3763        t0GEN(ch)
3764        _sig_on
3765        return self.new_gen(coordch(self.g, t0))
3766
3767    def elleta(self):
3768        _sig_on
3769        return self.new_gen(elleta(self.g, prec))
3770
3771    def ellheight(self, a, flag=0):
3772        t0GEN(a)
3773        _sig_on
3774        return self.new_gen(ellheight0(self.g, t0, flag, prec))
3775
3776    def ellheightmatrix(self, x):
3777        """
3778        ellheightmatrix(e,x)
3779
3780        Returns the height matrix for vector of points x on elliptic curve e using
3781        theta functions.
3782        """
3783        t0GEN(x)
3784        _sig_on
3785        return self.new_gen(mathell(self.g, t0, prec))
3786
3787    def ellisoncurve(self, x):
3788        t0GEN(x)
3789        _sig_on
3790        t = bool(oncurve(self.g, t0) == 1)
3791        _sig_off
3792        return t
3793
3794    def elllocalred(self, p):
3795        t0GEN(p)
3796        _sig_on
3797        return self.new_gen(elllocalred(self.g, t0))
3798
3799    def elllseries(self, s, A=1):
3800        t0GEN(s); t1GEN(A)
3801        _sig_on
3802        return self.new_gen(lseriesell(self.g, t0, t1, prec))
3803
3804    def ellminimalmodel(self):
3805        """
3806        ellminimalmodel(e): return the standard minimal integral model
3807        of the rational elliptic curve e and the corresponding change
3808        of variables.
3809        INPUT:
3810            e -- gen (that defines an elliptic curve)
3811        OUTPUT:
3812            gen -- minimal model
3813            gen -- change of coordinates
3814        EXAMPLES:
3815            sage: e = pari([1,2,3,4,5]).ellinit()
3816            sage: F, ch = e.ellminimalmodel()
3817            sage: F[:5]
3818            [1, -1, 0, 4, 3]
3819            sage: ch
3820            [1, -1, 0, -1]
3821            sage: e.ellchangecurve(ch)[:5]
3822            [1, -1, 0, 4, 3]
3823        """
3824        cdef GEN x, y
3825        cdef gen model, change
3826        cdef pari_sp t
3827        _sig_on
3828        x = ellminimalmodel(self.g, &y)
3829        change = self.new_gen_noclear(y)
3830        model = self.new_gen(x)
3831        return model, change
3832   
3833    def ellorder(self, x):
3834        t0GEN(x)
3835        _sig_on
3836        return self.new_gen(orderell(self.g, t0))
3837   
3838    def ellordinate(self, x):
3839        t0GEN(x)
3840        _sig_on
3841        return self.new_gen(ordell(self.g, t0, prec))
3842
3843    def ellpointtoz(self, P):
3844        t0GEN(P)
3845        _sig_on
3846        return self.new_gen(zell(self.g, t0, prec))
3847
3848    def ellpow(self, z, n):
3849        t0GEN(z); t1GEN(n)
3850        _sig_on
3851        return self.new_gen(powell(self.g, t0, t1))
3852   
3853    def ellrootno(self, p=1):
3854        t0GEN(p)
3855        _sig_on
3856        return ellrootno(self.g, t0)
3857
3858    def ellsigma(self, z, flag=0):
3859        t0GEN(z)
3860        _sig_on
3861        return self.new_gen(ellsigma(self.g, t0, flag, prec))
3862
3863    def ellsub(self, z1, z2):
3864        t0GEN(z1); t1GEN(z2)
3865        _sig_on
3866        return self.new_gen(subell(self.g, t0, t1))
3867
3868    def elltaniyama(self):
3869        _sig_on
3870        return self.new_gen(taniyama(self.g))
3871
3872    def elltors(self, flag=0):
3873        _sig_on
3874        return self.new_gen(elltors0(self.g, flag))
3875
3876
3877    def ellzeta(self, z):
3878        t0GEN(z)
3879        _sig_on
3880        return self.new_gen(ellzeta(self.g, t0, prec))
3881
3882    def ellztopoint(self, z):
3883        t0GEN(z)
3884        _sig_on
3885        return self.new_gen(pointell(self.g, t0, prec))
3886
3887    def omega(self):
3888        """
3889        e.omega(): return basis for the period lattice of the elliptic curve e.
3890       
3891        EXAMPLES:
3892            sage: e = pari([0, -1, 1, -10, -20]).ellinit()
3893            sage: e.omega()
3894            [1.269209304279553421688794617, 0.6346046521397767108443973084 + 1.458816616938495229330889613*I]   # 32-bit
3895            [1.2692093042795534216887946167545473052, 0.63460465213977671084439730837727365260 + 1.4588166169384952293308896129036752572*I]   # 64-bit
3896        """
3897        return self[14:16]
3898
3899    def disc(self):
3900        """
3901        e.disc(): return the discriminant of the elliptic curve e.
3902       
3903        EXAMPLES:
3904            sage: e = pari([0, -1, 1, -10, -20]).ellinit()
3905            sage: e.disc()
3906            -161051
3907            sage: _.factor()
3908            [-1, 1; 11, 5]
3909        """
3910        return self[11]
3911
3912    def j(self):
3913        """
3914        e.j(): return the j-invariant of the elliptic curve e.
3915       
3916        EXAMPLES:
3917            sage: e = pari([0, -1, 1, -10, -20]).ellinit()
3918            sage: e.j()
3919            -122023936/161051
3920            sage: _.factor()
3921            [-1, 1; 2, 12; 11, -5; 31, 3]
3922        """
3923        return self[12]
3924
3925   
3926   
3927
3928    def ellj(self):
3929        _sig_on
3930        return P.new_gen(jell(self.g, prec))
3931
3932
3933    ###########################################
3934    # 6: Functions related to general NUMBER FIELDS
3935    ###########################################
3936    def bnfcertify(self):
3937        r"""
3938        \code{bnf} being as output by \code{bnfinit}, checks whether
3939        the result is correct, i.e. whether the calculation of the
3940        contents of self are correct without assuming the Generalized
3941        Riemann Hypothesis. If it is correct, the answer is 1. If not,
3942        the program may output some error message, but more probably
3943        will loop indefinitely. In \emph{no} occasion can the program
3944        give a wrong answer (barring bugs of course): if the program
3945        answers 1, the answer is certified.
3946
3947        \note{WARNING! By default, most of the bnf routines depend on
3948        the correctness of a heuristic assumption which is stronger
3949        than GRH.  In order to obtain a provably-correct result you
3950        \emph{must} specify $c=c_2=12$ for the technical optional
3951        parameters to the function. There are known counterexamples
3952        for smaller $c$ (which is the default).}
3953
3954        """
3955        cdef long n
3956        _sig_on
3957        n = certifybuchall(self.g)
3958        _sig_off
3959        return n
3960   
3961    def bnfinit(self, long flag=0, tech=None):
3962        if tech is None:
3963            _sig_on
3964            return P.new_gen(bnfinit0(self.g, flag, <GEN>0, prec))
3965        else:
3966            t0GEN(tech)
3967            _sig_on
3968            return P.new_gen(bnfinit0(self.g, flag, t0, prec))
3969
3970    def bnfisintnorm(self, x):
3971        t0GEN(x)
3972        _sig_on
3973        return self.new_gen(bnfisintnorm(self.g, t0))
3974
3975    def bnfisprincipal(self, x, long flag=1):
3976        t0GEN(x)
3977        _sig_on
3978        return self.new_gen(isprincipalall(self.g, t0, flag))
3979
3980    def bnfnarrow(self):
3981        _sig_on
3982        return self.new_gen(buchnarrow(self.g))
3983
3984    def bnfunit(self):
3985        _sig_on
3986        return self.new_gen(buchfu(self.g))
3987
3988    def dirzetak(self, n):
3989        t0GEN(n)
3990        _sig_on
3991        return self.new_gen(dirzetak(self.g, t0))
3992
3993    def idealadd(self, x, y):
3994        t0GEN(x); t1GEN(y)
3995        _sig_on
3996        return self.new_gen(idealadd(self.g, t0, t1))
3997
3998    def idealdiv(self, x, y, long flag=0):
3999        t0GEN(x); t1GEN(y)
4000        _sig_on
4001        return self.new_gen(idealdiv0(self.g, t0, t1, flag))
4002
4003    def idealfactor(self, x):
4004        t0GEN(x)
4005        _sig_on
4006        return self.new_gen(idealfactor(self.g, t0))
4007
4008    def idealhnf(self, a, b=None):
4009        t0GEN(a)
4010        _sig_on
4011        if b is None:
4012            return self.new_gen(idealhermite(self.g, t0))
4013        else:
4014            t1GEN(b)
4015            return self.new_gen(idealhnf0(self.g, t0, t1))
4016
4017    def idealmul(self, x, y, long flag=0):
4018        t0GEN(x); t1GEN(y)
4019        _sig_on
4020        if flag == 0:
4021            return self.new_gen(idealmul(self.g, t0, t1))
4022        else:
4023            return self.new_gen(idealmulred(self.g, t0, t1, prec))
4024
4025    def idealnorm(self, x):
4026        t0GEN(x)
4027        _sig_on
4028        return self.new_gen(idealnorm(self.g, t0))
4029
4030    def idealtwoelt(self, x, a=None):
4031        t0GEN(x)
4032        _sig_on
4033        if a is None:
4034            return self.new_gen(ideal_two_elt0(self.g, t0, NULL))
4035        else:
4036            t1GEN(a)
4037            return self.new_gen(ideal_two_elt0(self.g, t0, t1))
4038
4039    def idealval(self, x, p):
4040        t0GEN(x); t1GEN(p)
4041        _sig_on
4042        return idealval(self.g, t0, t1)
4043
4044    def nfbasis(self, long flag=0, p=0):
4045        cdef gen _p
4046        cdef GEN g
4047        if p != 0:
4048            _p = self.pari(p)
4049            g = _p.g
4050        else:
4051            g = <GEN>NULL
4052        _sig_on
4053        return self.new_gen(nfbasis0(self.g, flag, g))
4054
4055    def nfgenerator(self):
4056        f = self[0]
4057        x = f.variable()
4058        return x.Mod(f)
4059
4060    def nfinit(self, long flag=0):
4061        _sig_on
4062        return P.new_gen(nfinit0(self.g, flag, prec))
4063
4064    def rnfcharpoly(self, T, a, v='x'):
4065        t0GEN(T); t1GEN(a); t2GEN(v)
4066        _sig_on
4067        return self.new_gen(rnfcharpoly(self.g, t0, t1, gvar(t2)))
4068
4069    def rnfdisc(self, x):
4070        t0GEN(x)
4071        _sig_on
4072        return self.new_gen(rnfdiscf(self.g, t0))
4073
4074    def rnfeltabstorel(self, x):
4075        t0GEN(x)
4076        _sig_on
4077        polymodmod = self.new_gen(rnfelementabstorel(self.g, t0))
4078        return polymodmod.centerlift().centerlift()
4079
4080    def rnfeltreltoabs(self, x):
4081        t0GEN(x)
4082        _sig_on
4083        return self.new_gen(rnfelementreltoabs(self.g, t0))
4084
4085    def rnfequation(self, poly):
4086        t0GEN(poly)
4087        _sig_on
4088        return self.new_gen(rnfequation0(self.g, t0, 0))
4089
4090    def rnfidealabstorel(self, x):
4091        t0GEN(x)
4092        _sig_on
4093        return self.new_gen(rnfidealabstorel(self.g, t0))
4094
4095    def rnfidealadd(self, nf, x, y):
4096        # Note the extra nf parameter, which should be the pari_nf
4097        # corresponding to self.
4098        a = self.rnfidealreltoabs(x)
4099        b = self.rnfidealreltoabs(y)
4100        sum = nf.idealadd(a, b)
4101        return self.rnfidealabstorel(sum)
4102   
4103    def rnfidealhnf(self, x):
4104        t0GEN(x)
4105        _sig_on
4106        return self.new_gen(rnfidealhermite(self.g, t0))
4107
4108    def rnfidealnormrel(self, x):
4109        t0GEN(x)
4110        _sig_on
4111        return self.new_gen(rnfidealnormrel(self.g, t0))
4112
4113    def rnfidealreltoabs(self, x):
4114        t0GEN(x)
4115        _sig_on
4116        return self.new_gen(rnfidealreltoabs(self.g, t0))
4117
4118    def rnfidealtwoelt(self, x):
4119        t0GEN(x)
4120        _sig_on
4121        return self.new_gen(rnfidealtwoelement(self.g, t0))
4122
4123    def rnfinit(self, poly):
4124        """
4125        EXAMPLES:
4126        We construct a relative number field.
4127            sage: f = pari('y^3+y+1')
4128            sage: K = f.nfinit()
4129            sage: x = pari('x'); y = pari('y')
4130            sage: g = x^5 - x^2 + y
4131            sage: L = K.rnfinit(g)   
4132        """
4133        t0GEN(poly)
4134        _sig_on
4135        return P.new_gen(rnfinitalg(self.g, t0, prec))
4136
4137    def rnfisfree(self, poly):
4138        t0GEN(poly)
4139        _sig_on
4140        return rnfisfree(self.g, t0)
4141
4142
4143   
4144
4145
4146    ##################################################
4147    # 7: POLYNOMIALS and power series
4148    ##################################################
4149    def reverse(self):
4150        """
4151        Return the polynomial obtained by reversing the coefficients
4152        of this polynomial.
4153        """
4154        return self.Vec().Polrev()
4155
4156    def deriv(self, v=-1):
4157        _sig_on
4158        return self.new_gen(deriv(self.g, self.get_var(v)))
4159
4160    def eval(self, x):
4161        t0GEN(x)
4162        _sig_on
4163        return self.new_gen(poleval(self.g, t0))
4164
4165    def __call__(self, x):
4166        return self.eval(x)
4167
4168    def factorpadic(self, p, long r=20, long flag=0):
4169        """
4170        self.factorpadic(p,{r=20},{flag=0}): p-adic factorization of the
4171        polynomial x to precision r. flag is optional and may be set
4172        to 0 (use round 4) or 1 (use Buchmann-Lenstra)
4173        """
4174        t0GEN(p)
4175        _sig_on
4176        return self.new_gen(factorpadic0(self.g, t0, r, flag))
4177
4178    def factormod(self, p, long flag=0):
4179        """
4180        x.factormod(p,{flag=0}): factorization mod p of the polynomial
4181        x using Berlekamp. flag is optional, and can be 0: default or
4182        1: simple factormod, same except that only the degrees of the
4183        irreducible factors are given.
4184        """
4185        t0GEN(p)
4186        _sig_on
4187        return self.new_gen(factormod0(self.g, t0, flag))
4188
4189    def intformal(self, y=-1):
4190        """
4191        x.intformal({y}): formal integration of x with respect to the main
4192        variable of y, or to the main variable of x if y is omitted
4193        """
4194        _sig_on
4195        return self.new_gen(integ(self.g, self.get_var(v)))
4196
4197    def padicappr(self, a):
4198        """
4199        x.padicappr(a): p-adic roots of the polynomial x congruent to a mod p
4200        """
4201        t0GEN(a)
4202        _sig_on
4203        return self.new_gen(padicappr(self.g, t0))
4204
4205    def newtonpoly(self, p):
4206        """
4207        self.newtonpoly(p): Newton polygon of polynomial x with respect
4208        to the prime p.
4209        """
4210        t0GEN(p)
4211        _sig_on
4212        return self.new_gen(newtonpoly(self.g, t0))
4213
4214    def polcoeff(self, long n, var=-1):
4215        """
4216        EXAMPLES:
4217            sage: f = pari("x^2 + y^3 + x*y")
4218            sage: f
4219            x^2 + y*x + y^3
4220            sage: f.polcoeff(1)
4221            y
4222            sage: f.polcoeff(3)
4223            0
4224            sage: f.polcoeff(3, "y")
4225            1
4226            sage: f.polcoeff(1, "y")
4227            x
4228        """
4229        _sig_on
4230        return self.new_gen(polcoeff0(self.g, n, self.get_var(var)))
4231
4232    def polcompositum(self, pol2, long flag=0):
4233        t0GEN(pol2)
4234        _sig_on
4235        return self.new_gen(polcompositum0(self.g, t0, flag))
4236
4237    def poldegree(self, var=-1):
4238        """
4239        f.poldegree(var={x}): Return the degree of this polynomial.
4240        """
4241        _sig_on
4242        n = poldegree(self.g, self.get_var(var))
4243        _sig_off
4244        return n
4245
4246    def poldisc(self, var=-1):
4247        """
4248        f.poldist(var={x}):  Return the discriminant of this polynomial.
4249        """
4250        _sig_on
4251        return self.new_gen(poldisc0(self.g, self.get_var(var)))
4252
4253    def poldiscreduced(self):
4254        _sig_on
4255        return self.new_gen(reduceddiscsmith(self.g))
4256
4257    def polgalois(self):
4258        """
4259        f.polgalois(): Galois group of the polynomial f
4260        """
4261        _sig_on
4262        return self.new_gen(galois(self.g, prec))
4263       
4264    def polhensellift(self, y, p, long e):
4265        """
4266        self.polhensellift(y, p, e): lift the factorization y of
4267        self modulo p to a factorization modulo $p^e$ using Hensel
4268        lift. The factors in y must be pairwise relatively prime
4269        modulo p.
4270        """
4271        t0GEN(y)
4272        t1GEN(p)
4273        _sig_on
4274        return self.new_gen(polhensellift(self.g, t0, t1, e))
4275
4276    def polisirreducible(self):
4277        """
4278        f.polisirreducible(): Returns True if f is an irreducible
4279        non-constant polynomial, or False if f is reducible or
4280        constant.
4281        """
4282        _sig_on
4283        return bool(self.new_gen(gisirreducible(self.g)))
4284       
4285       
4286    def pollead(self, v=-1):
4287        """
4288        self.pollead({v}): leading coefficient of polynomial or series
4289        self, or self itself if self is a scalar. Error
4290        otherwise. With respect to the main variable of self if v is
4291        omitted, with respect to the variable v otherwise
4292        """
4293        _sig_on
4294        return self.new_gen(pollead(self.g, self.get_var(v)))
4295
4296    def polrecip(self):
4297        _sig_on
4298        return self.new_gen(polrecip(self.g))
4299   
4300    def polresultant(self, y, var=-1, flag=0):
4301        t0GEN(y)
4302        _sig_on
4303        return self.new_gen(polresultant0(self.g, t0, self.get_var(var), flag))
4304
4305    def polroots(self, flag=0):
4306        """
4307        polroots(x,{flag=0}): complex roots of the polynomial x. flag
4308        is optional, and can be 0: default, uses Schonhage's method modified
4309        by Gourdon, or 1: uses a modified Newton method.
4310        """
4311        _sig_on
4312        return self.new_gen(roots0(self.g, flag, prec))
4313   
4314    def polrootsmod(self, p, flag=0):
4315        t0GEN(p)
4316        _sig_on
4317        return self.new_gen(rootmod0(self.g, t0, flag))
4318
4319    def polrootspadic(self, p, r=20):
4320        t0GEN(p)
4321        _sig_on
4322        return self.new_gen(rootpadic(self.g, t0, r))
4323
4324    def polrootspadicfast(self, p, r=20):
4325        t0GEN(p)
4326        _sig_on
4327        return self.new_gen(rootpadicfast(self.g, t0, r))
4328
4329    def polsturm(self, a, b):
4330        t0GEN(a)
4331        t1GEN(b)
4332        _sig_on
4333        n = sturmpart(self.g, t0, t1)
4334        _sig_off
4335        return n
4336
4337    def polsylvestermatrix(self, g):
4338        t0GEN(g)
4339        _sig_on
4340        return self.new_gen(sylvestermatrix(self.g, t0))
4341
4342    def polsym(self, long n):
4343        _sig_on
4344        return self.new_gen(polsym(self.g, n))
4345
4346    def serconvol(self, g):
4347        t0GEN(g)
4348        _sig_on
4349        return self.new_gen(convol(self.g, t0))
4350
4351    def serlaplace(self):
4352        _sig_on
4353        return self.new_gen(laplace(self.g))
4354
4355    def serreverse(self):
4356        """
4357        serreverse(f): reversion of the power series f.
4358
4359        If f(t) is a series in t with valuation 1, find the
4360        series g(t) such that g(f(t)) = t.
4361
4362        EXAMPLES:
4363            sage: f = pari('x+x^2+x^3+O(x^4)'); f
4364            x + x^2 + x^3 + O(x^4)
4365            sage: g = f.serreverse(); g
4366            x - x^2 + x^3 + O(x^4)
4367            sage: f.subst('x',g)
4368            x + O(x^4)
4369            sage: g.subst('x',f)
4370            x + O(x^4)       
4371        """
4372        _sig_on
4373        return self.new_gen(recip(self.g))
4374   
4375    def thueinit(self, flag=0):
4376        _sig_on
4377        return self.new_gen(thueinit(self.g, flag, prec))
4378
4379
4380
4381   
4382
4383    ###########################################
4384    # 8: Vectors, matrices, LINEAR ALGEBRA and sets
4385    ###########################################
4386
4387    def vecextract(self, y, z=None):
4388        r"""
4389        self.vecextract(y,{z}): extraction of the components of the
4390        matrix or vector x according to y and z. If z is omitted, y
4391        designates columns, otherwise y corresponds to rows and z to
4392        columns. y and z can be vectors (of indices), strings
4393        (indicating ranges as in"1..10") or masks
4394        (integers whose binary representation indicates the indices
4395        to extract, from left to right 1, 2, 4, 8, etc.)
4396
4397        \note{This function uses the PARI row and column indexing,
4398        so the first row or column is indexed by 1 instead of 0.}
4399        """
4400        t0GEN(y)
4401        if z is None:
4402            _sig_on
4403            return P.new_gen(extract(self.g, t0))
4404        else:
4405            t1GEN(z)
4406            _sig_on
4407            return P.new_gen(extract0(self.g, t0, t1))
4408
4409    def ncols(self):
4410        """
4411        Return the number of rows of self.
4412
4413        EXAMPLES:
4414            sage: pari('matrix(19,8)').ncols()
4415            8       
4416        """
4417        cdef long n
4418        _sig_on
4419        n = glength(self.g)
4420        _sig_off
4421        return n
4422
4423    def nrows(self):
4424        """
4425        Return the number of rows of self.
4426
4427        EXAMPLES:
4428            sage: pari('matrix(19,8)').nrows()
4429            19
4430        """
4431        cdef long n
4432        _sig_on
4433        n = glength(<GEN>(self.g[1]))
4434        _sig_off
4435        return n
4436
4437    def mattranspose(self):
4438        """
4439        Transpose of the matrix self.
4440       
4441        EXAMPLES:
4442            sage: pari('[1,2,3; 4,5,6;  7,8,9]').mattranspose()
4443            [1, 4, 7; 2, 5, 8; 3, 6, 9]       
4444        """
4445        _sig_on       
4446        return self.new_gen(gtrans(self.g)).Mat()
4447
4448    def matadjoint(self):
4449        """
4450        matadjoint(x): adjoint matrix of x.
4451
4452        EXAMPLES:
4453            sage: pari('[1,2,3; 4,5,6;  7,8,9]').matadjoint()
4454            [-3, 6, -3; 6, -12, 6; -3, 6, -3]
4455            sage: pari('[a,b,c; d,e,f; g,h,i]').matadjoint()
4456            [(i*e - h*f), (-i*b + h*c), (f*b - e*c); (-i*d + g*f), i*a - g*c, -f*a + d*c; (h*d - g*e), -h*a + g*b, e*a - d*b]           
4457        """
4458        _sig_on       
4459        return self.new_gen(adj(self.g)).Mat()
4460
4461    def qflllgram(self, long flag=0):
4462        """
4463        qflllgram(x,{flag=0}): LLL reduction of the lattice whose gram
4464        matrix is x (gives the unimodular transformation matrix). flag
4465        is optional and can be 0: default,1: lllgramint algorithm for
4466        integer matrices, 4: lllgramkerim giving the kernel and the
4467        LLL reduced image, 5: lllgramkerimgen same when the matrix has
4468        polynomial coefficients, 8: lllgramgen, same as qflllgram when
4469        the coefficients are polynomials.
4470        """
4471        _sig_on
4472        return self.new_gen(qflllgram0(self.g,flag,prec)).Mat()
4473
4474    def lllgram(self):
4475        return self.qflllgram(0)
4476
4477    def lllgramint(self):
4478        return self.qflllgram(1)
4479
4480    def qfminim(self, B, max, long flag=0):
4481        """
4482        qfminim(x,{bound},{maxnum},{flag=0}): number of vectors of
4483        square norm <= bound, maximum norm and list of vectors for the
4484        integral and definite quadratic form x; minimal non-zero
4485        vectors if bound=0. flag is optional, and can be 0: default;
4486        1: returns the first minimal vector found (ignore maxnum); 2:
4487        as 0 but uses a more robust, slower implementation, valid for
4488        non integral quadratic forms.
4489        """
4490        _sig_on
4491        t0GEN(B)
4492        t1GEN(max)
4493        return self.new_gen(qfminim0(self.g,t0,t1,flag,precdl))
4494
4495    def qfrep(self, B, long flag=0):
4496        """
4497        qfrep(x,B,{flag=0}): vector of (half) the number of vectors of
4498        norms from 1 to B for the integral and definite quadratic form
4499        x. Binary digits of flag mean 1: count vectors of even norm
4500        from 1 to 2B, 2: return a t_VECSMALL instead of a t_VEC.
4501        """
4502        _sig_on
4503        t0GEN(B)
4504        return self.new_gen(qfrep0(self.g,t0,flag))
4505       
4506    def matker(self, long flag=0):
4507        """
4508        Return a basis of the kernel of this matrix.
4509
4510        INPUT:
4511            flag -- optional; may be set to
4512                0: default;
4513                non-zero: x is known to have integral entries.
4514
4515        EXAMPLES:
4516            sage: pari('[1,2,3;4,5,6;7,8,9]').matker()
4517            [1; -2; 1]
4518
4519        With algorithm 1, even if the matrix has integer entries the
4520        kernel need nto be saturated (which is weird):
4521            sage: pari('[1,2,3;4,5,6;7,8,9]').matker(1)
4522            [3; -6; 3]
4523            sage: pari('matrix(3,3,i,j,i)').matker()
4524            [-1, -1; 1, 0; 0, 1]           
4525            sage: pari('[1,2,3;4,5,6;7,8,9]*Mod(1,2)').matker()
4526            [Mod(1, 2); Mod(0, 2); 1]           
4527        """
4528        _sig_on       
4529        return self.new_gen(matker0(self.g, flag))
4530
4531    def matkerint(self, long flag=0):
4532        """
4533        Return the integer kernel of a matrix.
4534
4535        This is the LLL-reduced Z-basis of the kernel of the matrix x
4536        with integral entries.
4537
4538        INPUT:
4539            flag -- optional, and may be set to
4540                   0: default, uses a modified LLL,
4541                   1: uses matrixqz.
4542                   
4543        EXAMPLES:
4544            sage: pari('[2,1;2,1]').matker()
4545            [-1/2; 1]
4546            sage: pari('[2,1;2,1]').matkerint()
4547            [-1; 2]
4548
4549        This is worrisome (so be careful!):
4550            sage: pari('[2,1;2,1]').matkerint(1)
4551            Mat(1)       
4552        """
4553        _sig_on       
4554        return self.new_gen(matkerint0(self.g, flag))
4555
4556    def matdet(self, long flag=0):
4557        """
4558        Return the determinant of this matrix.
4559
4560        INPUT:
4561            flag  -- (optional) flag
4562                     0: using Gauss-Bareiss.
4563                     1: use classical gaussian elimination (slightly better for integer entries)
4564
4565        EXAMPLES:
4566            sage: pari('[1,2; 3,4]').matdet(0)
4567            -2
4568            sage: pari('[1,2; 3,4]').matdet(1)
4569            -2
4570        """
4571        _sig_on       
4572        return self.new_gen(det0(self.g, flag))
4573
4574    def trace(self):
4575        """
4576        Return the trace of this PARI object.
4577
4578        EXAMPLES:
4579            sage: pari('[1,2; 3,4]').trace() 
4580            5
4581        """
4582        _sig_on       
4583        return self.new_gen(gtrace(self.g))
4584
4585    def mathnf(self, flag=0):
4586        """
4587        A.mathnf({flag=0}): (upper triangular) Hermite normal form of
4588        A, basis for the lattice formed by the columns of A.
4589
4590        INPUT:
4591            flag -- optional, value range from 0 to 4 (0 if
4592            omitted), meaning :
4593                0: naive algorithm
4594                1: Use Batut's algorithm -- output 2-component vector
4595                   [H,U] such that H is the  HNF of A, and U is a
4596                   unimodular matrix such that xU=H.
4597                3: Use Batut's algorithm. Output [H,U,P] where P is
4598                   a permutation matrix such that P A U = H.
4599                4: As 1, using a heuristic variant of LLL reduction
4600                   along the way.
4601
4602        EXAMPLES:
4603            sage: pari('[1,2,3; 4,5,6;  7,8,9]').mathnf()
4604            [6, 1; 3, 1; 0, 1]
4605        """
4606        _sig_on
4607        return self.new_gen(mathnf0(self.g, flag))
4608
4609    def matsnf(self, flag=0):
4610        """
4611        x.matsnf({flag=0}): Smith normal form (i.e. elementary
4612        divisors) of the matrix x, expressed as a vector d. Binary
4613        digits of flag mean 1: returns [u,v,d] where d=u*x*v,
4614        otherwise only the diagonal d is returned, 2: allow polynomial
4615        entries, otherwise assume x is integral, 4: removes all
4616        information corresponding to entries equal to 1 in d.
4617
4618        EXAMPLES:
4619            sage: pari('[1,2,3; 4,5,6;  7,8,9]').matsnf()
4620            [0, 3, 1]
4621        """
4622        _sig_on
4623        return self.new_gen(matsnf0(self.g, flag))
4624
4625    def matfrobenius(self, flag=0):
4626        r"""
4627        M.matfrobenius({flag=0}): Return the Frobenius form of the
4628        square matrix M. If flag is 1, return only the elementary
4629        divisors (a list of polynomials). If flag is 2, return a
4630        two-components vector [F,B] where F is the Frobenius form and
4631        B is the basis change so that $M=B^{-1} F B$.
4632
4633        EXAMPLES:
4634            sage: a = pari('[1,2;3,4]')
4635            sage: a.matfrobenius()
4636            [0, 2; 1, 5]
4637            sage: a.matfrobenius(flag=1)
4638            [x^2 - 5*x - 2]
4639            sage: a.matfrobenius(2)
4640            [[0, 2; 1, 5], [1, -1/3; 0, 1/3]]
4641            sage: v = a.matfrobenius(2)
4642            sage: v[0]
4643            [0, 2; 1, 5]
4644            sage: v[1]^(-1)*v[0]*v[1]
4645            [1, 2; 3, 4]
4646
4647        We let t be the matrix of $T_2$ acting on modular symbols of level 43,
4648        which was computed using \code{ModularSymbols(43,sign=1).T(2).matrix()}:
4649       
4650            sage: t = pari('[3, -2, 0, 0; 0, -2, 0, 1; 0, -1, -2, 2; 0, -2, 0, 2]')
4651            sage: t.matfrobenius()
4652            [0, 0, 0, -12; 1, 0, 0, -2; 0, 1, 0, 8; 0, 0, 1, 1]
4653            sage: t.charpoly('x')
4654            x^4 - x^3 - 8*x^2 + 2*x + 12
4655            sage: t.matfrobenius(1)
4656            [x^4 - x^3 - 8*x^2 + 2*x + 12]
4657
4658        AUTHOR:
4659           -- 2006-04-02: Martin Albrecht
4660        """
4661        _sig_on
4662        return self.new_gen(matfrobenius(self.g, flag, 0))
4663
4664
4665    ###########################################
4666    # 9: SUMS, products, integrals and similar functions
4667    ###########################################
4668
4669
4670    ###########################################
4671    # polarit2.c
4672    ###########################################
4673    def factor(gen self, limit=-1):
4674        """
4675        Return the factorization of x.
4676
4677        lim is optional and can be set whenever x is of (possibly
4678        recursive) rational type. If lim is set return partial
4679        factorization, using primes up to lim (up to primelimit if
4680        lim=0).
4681
4682        EXAMPLES:
4683            sage: pari('x^10-1').factor()
4684            [x - 1, 1; x + 1, 1; x^4 - x^3 + x^2 - x + 1, 1; x^4 + x^3 + x^2 + x + 1, 1]
4685            sage: pari(2^100-1).factor()
4686            [3, 1; 5, 3; 11, 1; 31, 1; 41, 1; 101, 1; 251, 1; 601, 1; 1801, 1; 4051, 1; 8101, 1; 268501, 1]
4687
4688        PARI doesn't have an algorithm for factoring multivariate polynomials:
4689       
4690            sage: pari('x^3 - y^3').factor()
4691            Traceback (most recent call last):
4692            ...
4693            PariError: sorry, (15)
4694        """
4695        _sig_on
4696        return P.new_gen(factor0(self.g, limit))
4697   
4698
4699    ###########################################
4700    # misc (classify when I know where they go)
4701    ###########################################
4702
4703    def hilbert(x, y, p):
4704        t0GEN(y)
4705        t1GEN(p)
4706        _sig_on
4707        return hil0(x.g, t0, t1)
4708       
4709    def chinese(self, y):
4710        t0GEN(y)
4711        _sig_on
4712        return P.new_gen(chinese(self.g, t0))
4713
4714    def order(self):
4715        _sig_on       
4716        return P.new_gen(order(self.g))
4717   
4718    def znprimroot(self):
4719        _sig_on       
4720        return P.new_gen(ggener(self.g))
4721       
4722    def __abs__(self):
4723        return self.abs()
4724   
4725    def norm(gen self):
4726        _sig_on       
4727        return P.new_gen(gnorm(self.g))
4728   
4729    def nextprime(gen self):
4730        """
4731        nextprime(x): smallest pseudoprime >= x
4732        """
4733        #NOTE: This is much faster than MAGMA's NextPrime with Proof := False.
4734        _sig_on       
4735        return P.new_gen(gnextprime(self.g))
4736
4737    def subst(self, var, y):
4738        """
4739        EXAMPLES:
4740           sage: x = pari("x"); y = pari("y")
4741           sage: f = pari('x^3 + 17*x + 3')
4742           sage: f.subst(x, y)
4743           y^3 + 17*y + 3
4744           sage: f.subst(x, "z")
4745           z^3 + 17*z + 3
4746           sage: f.subst(x, "z")^2
4747           z^6 + 34*z^4 + 6*z^3 + 289*z^2 + 102*z + 9
4748           sage: f.subst(x, "x+1")
4749           x^3 + 3*x^2 + 20*x + 21
4750           sage: f.subst(x, "xyz")
4751           xyz^3 + 17*xyz + 3
4752           sage: f.subst(x, "xyz")^2
4753           xyz^6 + 34*xyz^4 + 6*xyz^3 + 289*xyz^2 + 102*xyz + 9
4754        """
4755        cdef long n
4756        n = P.get_var(var)       
4757        t0GEN(y)
4758        _sig_on       
4759        return P.new_gen(gsubst(self.g, n, t0))
4760
4761    def substpol(self, y, z):
4762        t0GEN(y)
4763        t1GEN(z)
4764        _sig_on
4765        return self.new_gen(gsubstpol(self.g, t0, t1))
4766
4767    def taylor(self, v=-1):
4768        _sig_on
4769        return self.new_gen(tayl(self.g, self.get_var(v), precdl))
4770
4771    def thue(self, rhs, ne):
4772        t0GEN(rhs)
4773        t1GEN(ne)
4774        _sig_on
4775        return self.new_gen(thue(self.g, t0, t1))
4776
4777    def charpoly(self, var=-1, flag=0):
4778        """
4779        charpoly(A,{v=x},{flag=0}): det(v*Id-A) = characteristic
4780        polynomial of A using the comatrix. flag is optional and may
4781        be set to 1 (use Lagrange interpolation) or 2 (use Hessenberg
4782        form), 0 being the default.
4783        """
4784        _sig_on       
4785        return P.new_gen(charpoly0(self.g, P.get_var(var), flag))
4786
4787
4788    def kronecker(gen self, y):
4789        t0GEN(y)
4790        _sig_on       
4791        return P.new_gen(gkronecker(self.g, t0))
4792
4793
4794    def type(gen self):
4795        return str(type_name(typ(self.g)))
4796   
4797
4798    def polinterpolate(self, ya, x):
4799        """
4800        self.polinterpolate({ya},{x},{&e}): polynomial interpolation
4801        at x according to data vectors self, ya (i.e. return P such
4802        that P(self[i]) = ya[i] for all i).  Also return an error
4803        estimate on the returned value.
4804        """
4805        t0GEN(ya)
4806        t1GEN(x)
4807        cdef GEN dy, g
4808        _sig_on
4809        g = polint(self.g, t0, t1, &dy)
4810        _sig_off
4811        dif = self.new_gen_noclear(dy)
4812        return self.new_gen(g), dif
4813
4814    def algdep(self, long n, bit=0):
4815        """
4816        EXAMPLES:
4817            sage: n = pari.set_real_precision (200)
4818            sage: w1 = pari('z1=2-sqrt(26); (z1+I)/(z1-I)')
4819            sage: f = w1.algdep(12); f
4820            545*x^11 - 297*x^10 - 281*x^9 + 48*x^8 - 168*x^7 + 690*x^6 - 168*x^5 + 48*x^4 - 281*x^3 - 297*x^2 + 545*x
4821            sage: f(w1)
4822            7.75513996 E-200 + 5.70672991 E-200*I     # 32-bit
4823            3.780069700150794274 E-209 - 9.362977321012524836 E-211*I   # 64-bit
4824            sage: f.factor()
4825            [x, 1; x + 1, 2; x^2 + 1, 1; x^2 + x + 1, 1; 545*x^4 - 1932*x^3 + 2790*x^2 - 1932*x + 545, 1]
4826            sage: pari.set_real_precision(n)
4827            200
4828        """
4829        cdef long b
4830        b = bit
4831        _sig_on
4832        return self.new_gen(algdep0(self.g, n, b, prec))
4833
4834    def concat(self, y):
4835        t0GEN(y)
4836        _sig_on
4837        return self.new_gen(concat(self.g, t0))
4838
4839    def lindep(self, flag=0):
4840        _sig_on
4841        return self.new_gen(lindep0(self.g, flag, prec))
4842
4843    def listinsert(self, obj, long n):
4844        t0GEN(obj)
4845        _sig_on
4846        return self.new_gen(listinsert(self.g, t0, n))
4847
4848    def listput(self, obj, long n):
4849        t0GEN(obj)
4850        _sig_on
4851        return self.new_gen(listput(self.g, t0, n))
4852
4853
4854
4855    def elleisnum(self, long k, int flag=0):
4856        """
4857        om.elleisnum(k, {flag=0}, {prec}): om=[om1,om2] being a
4858            2-component vector giving a basis of a lattice L and k an
4859            even positive integer, computes the numerical value of the
4860            Eisenstein series of weight k. When flag is non-zero and
4861            k=4 or 6, this gives g2 or g3 with the correct
4862            normalization.
4863
4864        INPUT:
4865            om -- gen, 2-component vector giving a basis of a lattice L
4866            k  -- int (even positive)
4867            flag -- int (default 0)
4868            pref -- precision
4869
4870        OUTPUT:
4871            gen -- numerical value of E_k
4872
4873        EXAMPLES:
4874            sage: e = pari([0,1,1,-2,0]).ellinit()
4875            sage: om = e.omega()
4876            sage: om
4877            [2.490212560855055075321357792, 1.971737701551648204422407698*I]                       # 32-bit
4878            [2.4902125608550550753213577919423024602, 1.9717377015516482044224076981513423349*I]   # 64-bit
4879            sage: om.elleisnum(2)
4880            -5.288649339654257621791534695              # 32-bit
4881            -5.2886493396542576217915346952045657616    # 64-bit
4882            sage: om.elleisnum(4)
4883            112.0000000000000000000000000               # 32-bit
4884            112.00000000000000000000000000000000000     # 64-bit
4885            sage: om.elleisnum(100)
4886            2.153142485760776361127070349 E50              # 32-bit
4887            2.1531424857607763611270703492586704424 E50    # 64-bit
4888        """
4889        _sig_on
4890        return self.new_gen(elleisnum(self.g, k, flag, prec))
4891
4892    def ellwp(self, z='z', long n=20, long flag=0):
4893        """
4894        ellwp(E, z,{flag=0}): Return the complex value of the Weierstrass
4895        P-function at z on the lattice defined by e.
4896
4897        INPUT:
4898            E -- list OR elliptic curve
4899                  list -- [om1, om2], which are Z-generators for a lattice
4900                  elliptic curve -- created using ellinit
4901                   
4902            z -- (optional) complex number  OR string (default = "z")
4903                   complex number -- any number in the complex plane
4904                   string (or PARI variable) -- name of a variable.
4905                 
4906            n -- int (optional: default 20) if z is a variable, compute up to at least o(z^n).
4907           
4908            flag -- int: 0 (default): compute only P(z)
4909                         1 compute [P(z),P'(z)]
4910                         2 consider om or E as an elliptic curve and use P-function to
4911                           compute the point on E (with the Weierstrass equation for E)
4912                           P(z)
4913                           for that curve (identical to ellztopoint in this case).
4914                   
4915        OUTPUT:
4916            gen -- complex number or list of two complex numbers
4917
4918        EXAMPLES:
4919
4920        We first define the elliptic curve X_0(11):
4921            sage: E = pari([0,-1,1,-10,-20]).ellinit()
4922
4923        Compute P(1).
4924            sage: E.ellwp(1)
4925            13.96586952574849779469497770 + 1.465441833 E-249*I                       # 32-bit
4926            13.965869525748497794694977695009324221 + 5.607702583566084181 E-693*I    # 64-bit
4927
4928        Compute P(1+I), where I = sqrt(-1).
4929            sage: E.ellwp(pari("1+I"))
4930            -1.115106825655550879209066492 + 2.334190523074698836184798794*I                       # 32-bit
4931            -1.1151068256555508792090664916218413986 + 2.3341905230746988361847987936140321964*I   # 64-bit
4932            sage: E.ellwp("1+I")
4933            -1.115106825655550879209066492 + 2.334190523074698836184798794*I                       # 32-bit
4934            -1.1151068256555508792090664916218413986 + 2.3341905230746988361847987936140321964*I   # 64-bit
4935
4936        The series expansion, to the default 20 precision:
4937            sage: E.ellwp()
4938            z^-2 + 31/15*z^2 + 2501/756*z^4 + 961/675*z^6 + 77531/41580*z^8 + 1202285717/928746000*z^10 + 2403461/2806650*z^12 + 30211462703/43418875500*z^14 + 3539374016033/7723451736000*z^16 + 413306031683977/1289540602350000*z^18 + O(z^20)
4939
4940        Compute the series for wp to lower precision:
4941            sage: E.ellwp(n=4)
4942            z^-2 + 31/15*z^2 + O(z^4)
4943
4944        Next we use the version where the input is generators for a lattice:
4945            sage: pari(['1.2692', '0.63 + 1.45*I']).ellwp(1)
4946            13.96561469366894364802003736 + 0.0006448292728105361474541633318*I                        # 32-bit
4947            13.965614693668943648020037358850990554 + 0.00064482927281053614745416280316868200698*I    # 64-bit
4948
4949        With flag 1 compute the pair P(z) and P'(z):
4950            sage: E.ellwp(1, flag=1)
4951            [13.96586952574849779469497770 + 1.465441833 E-249*I, 50.56193008800727525558465690 + 4.46944479 E-249*I]    # 32-bit
4952            [13.965869525748497794694977695009324221 + 5.607702583566084181 E-693*I, 50.561930088007275255584656898892400699 + 1.7102908181111172423 E-692*I]   # 64-bit
4953
4954        With flag=2, the computed pair is (x,y) on the curve instead of [P(z),P'(z)]:
4955            sage: E.ellwp(1, flag=2)
4956            [14.29920285908183112802831103 + 1.465441833 E-249*I, 50.06193008800727525558465690 + 4.46944479 E-249*I]    # 32-bit
4957            [14.299202859081831128028311028342657555 + 5.607702583566084181 E-693*I, 50.061930088007275255584656898892400699 + 1.7102908181111172423 E-692*I]   # 64-bit
4958        """
4959        t0GEN(z)
4960        if n < 0:
4961            n = 0
4962        if n%2 == 1:
4963            n = n + 1
4964        _sig_on
4965        return self.new_gen(ellwp0(self.g, t0, flag, prec, (n+2)/2))
4966
4967    def ellchangepoint(self, y):
4968        """
4969        self.ellchangepoint(y): change data on point or vector of points self
4970                             on an elliptic curve according to y=[u,r,s,t]
4971
4972        EXAMPLES:
4973            sage: e = pari([0,1,1,-2,0]).ellinit()
4974            sage: x = pari([1,0,1])
4975            sage: e.ellisoncurve([1,4,4])
4976            False
4977            sage: e.ellisoncurve(x)
4978            True
4979            sage: f = e.ellchangecurve([1,2,3,-1])
4980            sage: f[:5]   # show only first five entries
4981            [6, -2, -1, 17, 8]
4982            sage: x.ellchangepoint([1,2,3,-1])
4983            [-1, 4]
4984            sage: f.ellisoncurve([-1,4])
4985            True
4986        """
4987        t0GEN(y)
4988        _sig_on
4989        return self.new_gen(pointch(self.g, t0))
4990
4991    ##################################################
4992    # Technical functions that can be used by other
4993    # classes that derive from gen.
4994    ##################################################
4995    cdef gen pari(self, object x):
4996        return pari(x)
4997
4998    cdef gen new_gen(self, GEN x):
4999        return P.new_gen(x)
5000
5001    cdef gen new_gen_noclear(self, GEN x):
5002        return P.new_gen_noclear(x)
5003
5004    cdef GEN _deepcopy_to_python_heap(self, GEN x, pari_sp* address):
5005        return P.deepcopy_to_python_heap(x, address)
5006
5007    cdef int get_var(self, v):
5008        return P.get_var(v)
5009
5010   
5011
5012cdef unsigned long num_primes
5013
5014cdef class PariInstance:
5015    def __init__(self, long size=16000000, unsigned long maxprime=500000):
5016        """
5017        Initialize the PARI system.
5018
5019        INPUT:
5020            size -- long, the number of bytes for the initial PARI stack
5021                    (see note below)
5022            maxprime -- unsigned long, upper limit on a precomputed prime
5023                        number table  (default: 500000)
5024
5025        NOTES:
5026
5027            * In py_pari, the PARI stack is different than in gp or the
5028              PARI C library.  In Python, instead of the PARI stack
5029              holding the results of all computations, it *only* holds the
5030              results of an individual computation.  Each time a new
5031              Python/PARI object is computed, it it copied to its own
5032              space in the Python heap, and the memory it occupied on the
5033              PARI stack is freed.  Thus it is not necessary to make the
5034              stack very large.  Also, unlike in PARI, if the stack does
5035              overflow, in most cases the PARI stack is automatically
5036              increased and the relevant step of the computation rerun.
5037
5038              This design obviously involves some performance penalties
5039              over the way PARI works, but it scales much better and is
5040              far more robus for large projects.
5041
5042            * If you do not want prime numbers, put maxprime=2, but be
5043              careful because many PARI functions require this table.  If
5044              you get the error message "not enough precomputed primes",
5045              increase this parameter.
5046
5047        """
5048        if bot:
5049            return  # pari already initialized.
5050       
5051        global initialized, num_primes, ZERO, ONE, TWO, avma, top, bot
5052
5053        #print "Initializing PARI (size=%s, maxprime=%s)"%(size,maxprime)
5054        pari_init(1024, maxprime)
5055
5056        _sig_on
5057        init_stack(size)
5058        _sig_off
5059
5060        GP_DATA.fmt.prettyp = 0
5061
5062        # Take control of SIGSEGV back from PARI.
5063        import signal
5064        signal.signal(signal.SIGSEGV, signal.SIG_DFL)
5065
5066        # We do the following, since otherwise the IPython pager
5067        # causes sage to crash when it is exited early.  This is
5068        # because when PARI was initialized it set a trap for this
5069        # signal.
5070        import signal
5071        signal.signal(signal.SIGPIPE, _my_sigpipe)
5072        initialized = 1
5073        stack_avma = avma
5074        num_primes = maxprime
5075        self.ZERO = self(0)    # todo: gen_0
5076        self.ONE = self(1)
5077        self.TWO = self(2)
5078
5079    def __repr__(self):
5080        return "Interface to the PARI C library"
5081
5082    def default(self, variable, value=None):
5083        if not value is None:
5084            return self('default(%s, %s)'%(variable, value))
5085        return self('default(%s)'%variable)
5086
5087    def set_debug_level(self, level):
5088        """
5089        Set the debug PARI C library variable.
5090        """
5091        self.default('debug', int(level))
5092
5093    def get_debug_level(self):
5094        """
5095        Set the debug PARI C library variable.
5096        """
5097        return int(self.default('debug'))
5098
5099    cdef GEN toGEN(self, x) except NULL:
5100        cdef gen _x
5101        if isinstance(x, gen):
5102            _x = x
5103            return _x.g
5104        s = str(x)
5105        cdef GEN g
5106        _sig_on
5107        g = flisseq(s)
5108        _sig_off
5109        return g
5110       
5111
5112    def set_real_precision(self, long n):
5113        """
5114        Sets the PARI default real precision, both for creation of
5115        new objects and for printing.  This is the number of digits
5116        *IN DECIMAL* that real numbers are printed or computed to
5117        by default.
5118
5119        Returns the previous PARI real precision.
5120        """
5121        cdef unsigned long k
5122        global prec
5123       
5124        k = GP_DATA.fmt.sigd
5125        s = str(n)
5126        _sig_on
5127        sd_realprecision(s, 2)
5128        prec = GP_DATA.fmt.sigd
5129        _sig_off
5130        return int(k)  # Python int
5131
5132    def get_real_precision(self):
5133        return GP_DATA.fmt.sigd
5134
5135    def set_series_precision(self, long n):
5136        global precdl
5137        precdl = n
5138
5139    def get_series_precision(self):
5140        return precdl
5141       
5142
5143    ###########################################
5144    # Create a gen from a GEN object.
5145    # This *steals* a reference to the GEN, as it
5146    # frees the memory the GEN occupied.
5147    ###########################################
5148
5149    cdef gen new_gen(self, GEN x):
5150        """
5151        Create a new gen, then free the *entire* stack.
5152        """
5153        cdef gen g
5154        g = _new_gen(x)
5155       
5156        global top, avma
5157        avma = top
5158        _sig_off
5159        return g
5160
5161    cdef gen new_gen_noclear(self, GEN x):
5162        """
5163        Create a new gen, but don't free any memory on the stack and
5164        don't call _sig_off.
5165        """
5166        return _new_gen(x)
5167
5168
5169    cdef GEN deepcopy_to_python_heap(self, GEN x, pari_sp* address):
5170        return deepcopy_to_python_heap(x, address)
5171
5172    cdef gen new_ref(self, GEN x, g):
5173        cdef gen p
5174        p = gen()
5175        p.init(x, 0)
5176        p.refers_to[-1] = g  # so underlying memory won't get deleted
5177                             # out from under us.
5178        return p
5179
5180    cdef gen adapt(self, s):
5181        if isinstance(s, gen):
5182            return s
5183        return pari(s)
5184
5185    def __call__(self, s):
5186        """
5187        Create the PARI object got by evaluating s using PARI.
5188        """
5189        cdef pari_sp prev_avma
5190        global avma
5191
5192        prev_avma = avma
5193
5194        if isinstance(s, gen):
5195            return s
5196        try:
5197            return s._pari_()
5198        except AttributeError:
5199            pass
5200        if isinstance(s, (types.ListType, types.XRangeType,
5201                            types.TupleType, xsrange)):
5202            v = self.vector(len(s))
5203            for i, x in enumerate(s):
5204                v[i] = self(x)
5205            return v
5206        elif isinstance(s, bool):
5207            if s:
5208                return self.ONE
5209            return self.ZERO
5210
5211        cdef GEN g
5212        t = str(s)
5213        _sig_str('evaluating PARI string')
5214        g = gp_read_str(t)
5215        _sig_off
5216        return self.new_gen(g)
5217       
5218    def _coerce_(self, x):
5219        """
5220        Implicit canonical coercion into a PARI object.
5221        """
5222        try:
5223            return self(x)
5224        except (TypeError, AttributeError):
5225            raise TypeError, "no canonical coercion of %s into PARI"%x
5226        if isinstance(x, gen):
5227            return x
5228        raise TypeError, "x must be a PARI object"
5229
5230    def new_with_prec(self, s, long precision=0):
5231        r"""
5232        pari.new_with_bits_prec(self, s, precision) creates s as a PARI gen
5233        with at lest precision decimal \emph{digits} of precision.
5234        """
5235        global prec
5236        cdef unsigned long old_prec
5237        old_prec = prec
5238        if not precision:
5239            precision = prec
5240        self.set_real_precision(precision)
5241        x = self(s)
5242        self.set_real_precision(old_prec)
5243        return x
5244       
5245    def new_with_bits_prec(self, s, long precision=0):
5246        r"""
5247        pari.new_with_bits_prec(self, s, precision) creates s as a PARI gen
5248        with (at most) precision \emph{bits} of precision.
5249        """
5250        global prec
5251       
5252        cdef unsigned long old_prec
5253        old_prec = prec
5254        precision = long(precision / 3.4)+1     # be safe, since log_2(10) = 3.3219280948873626
5255        if not precision:
5256            precision = prec
5257        self.set_real_precision(precision)
5258        x = self(s)
5259        self.set_real_precision(old_prec)
5260        return x
5261       
5262
5263
5264    cdef int get_var(self, v):
5265        """
5266        Converts a Python string into a PARI variable reference number.
5267        Or if v = -1, returns -1.
5268        """
5269        if v != -1:
5270            s = str(v)
5271            return fetch_user_var(s)
5272        return -1
5273
5274
5275    ############################################################
5276    # conversion between GEN and string types
5277    # Note that string --> GEN evaluates the string in PARI,
5278    # where GEN_to_str returns a Python string.
5279    ############################################################
5280    cdef object GEN_to_str(self, GEN g):
5281        cdef char* c
5282        cdef int n
5283        _sig_on
5284        c = GENtostr(g)
5285        _sig_off
5286        s = str(c)
5287        free(c)
5288        return s
5289
5290
5291    ############################################################
5292    # Initialization
5293    ############################################################
5294
5295    def allocatemem(self, silent=False):
5296        r"""
5297        Double the \emph{PARI} stack.
5298        """
5299        if not silent:
5300            print "Doubling the PARI stack."
5301        init_stack(0)
5302
5303    def pari_version(self):
5304        return str(PARIVERSION)
5305
5306    def init_primes(self, _M):
5307        """
5308        Recompute the primes table including at least all primes up to
5309        M (but possibly more).
5310
5311        EXAMPLES:
5312            sage: pari.init_primes(200000)
5313        """
5314        cdef unsigned long M
5315        M = _M
5316        global diffptr, num_primes
5317        if M <= num_primes:
5318            return
5319        #if not silent:
5320        #    print "Extending PARI prime table up to %s"%M
5321        free(<void*> diffptr)
5322        num_primes = M
5323        diffptr = initprimes(M)
5324
5325
5326    ##############################################
5327    ## Support for GP Scripts
5328    ##############################################
5329
5330
5331    def read(self, filename):
5332        r"""
5333        Read a script from the named filename into the interpreter, where
5334        s is a string.  The functions defined in the script are then
5335        available for use from SAGE/PARI.
5336
5337        EXAMPLE:
5338
5339            If foo.gp is a script that contains
5340            \begin{verbatim}
5341                {foo(n) =
5342                    n^2
5343                }
5344            \end{verbatim}
5345            and you type \code{read("foo.gp")}, then the command
5346            \code{pari("foo(12)")} will create the Python/PARI gen which
5347            is the integer 144.
5348
5349        CONSTRAINTS:   
5350            The PARI script must *not* contain the following function calls:
5351
5352                 print, default, ???    (please report any others that cause trouble)
5353        """
5354        F = open(filename).read()
5355        while True:
5356            i = F.find("}")
5357            if i == -1:
5358                _read_script(F)
5359                break
5360            s = F[:i+1]           
5361            _read_script(s)
5362            F = F[i+1:]
5363        return
5364
5365    ##############################################
5366
5367    def prime_list(self, long n):
5368        """
5369        prime_list(n): returns list of the first n primes
5370
5371        To extend the table of primes use pari.init_primes(M).
5372
5373        INPUT:
5374            n -- C long
5375        OUTPUT:
5376            gen -- PARI list of first n primes
5377           
5378        EXAMPLES:
5379            sage: pari.prime_list(0)
5380            []
5381            sage: pari.prime_list(-1)
5382            []
5383            sage: pari.prime_list(3)
5384            [2, 3, 5]
5385            sage: pari.prime_list(10)
5386            [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
5387            sage: pari.prime_list(20)
5388            [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
5389            sage: len(pari.prime_list(1000))
5390            1000
5391        """
5392        if n >= 2:
5393            self.nth_prime(n)
5394        _sig_on
5395        return self.new_gen(primes(n))
5396
5397    def primes_up_to_n(self, long n):
5398        """
5399        Return the primes <= n as a pari list.
5400        """
5401        if n <= 1:
5402            return pari([])
5403        self.init_primes(n+1)
5404        return self.prime_list(pari(n).primepi())
5405       
5406##         cdef long k
5407##         k = (n+10)/math.log(n)
5408##         p = 2
5409##         while p <= n:
5410##             p = self.nth_prime(k)
5411##             k = 2
5412##         v = self.prime_list(k)
5413##         return v[:pari(n).primepi()]
5414       
5415    def __nth_prime(self, long n):
5416        """
5417        nth_prime(n): returns the n-th prime, where n is a C-int
5418        """
5419        global num_primes
5420
5421        if n <= 0:
5422            raise ArithmeticError, "nth prime meaningless for negative n (=%s)"%n
5423        cdef GEN g
5424        _sig_on
5425        g = prime(n)
5426        return self.new_gen(g)
5427
5428
5429    def nth_prime(self, long n):
5430        try:
5431            return self.__nth_prime(n)
5432        except PariError:
5433            self.init_primes(max(2*num_primes,20*n))
5434            return self.nth_prime(n)
5435
5436    def euler(self):
5437        """
5438        Return Euler's constant to the current real precision.
5439
5440        EXAMPLES:
5441            sage: pari.euler()
5442            0.5772156649015328606065120901             # 32-bit
5443            0.57721566490153286060651209008240243104   # 64-bit
5444            sage: orig = pari.get_real_precision(); orig
5445            28         # 32-bit
5446            38         # 64-bit
5447            sage: _ = pari.set_real_precision(50)
5448            sage: pari.euler()
5449            0.57721566490153286060651209008240243104215933593992
5450
5451        We restore precision to the default.
5452            sage: pari.set_real_precision(orig)
5453            50
5454
5455        Euler is returned to the original precision:
5456            sage: pari.euler()
5457            0.5772156649015328606065120901              # 32-bit
5458            0.57721566490153286060651209008240243104    # 64-bit
5459        """
5460        if not precision:
5461            precision = prec
5462        _sig_on
5463        consteuler(precision)
5464        return self.new_gen(geuler)
5465
5466    def pi(self):
5467        """
5468        Return the value of the constant pi = 3.1415 to the current
5469        real precision.
5470
5471        EXAMPLES:
5472            sage: pari.pi()                       
5473            3.141592653589793238462643383             # 32-bit
5474            3.1415926535897932384626433832795028842   # 64-bit
5475            sage: orig_prec = pari.set_real_precision(5)
5476            sage: pari.pi()
5477            3.1416
5478
5479            sage: pari.get_real_precision()
5480            5
5481            sage: _ = pari.set_real_precision(40)
5482            sage: pari.pi()
5483            3.141592653589793238462643383279502884197
5484
5485
5486        We restore precision to the default.
5487            sage: _ = pari.set_real_precision(orig_prec)
5488
5489        Note that pi is now computed to the original precision:
5490       
5491            sage: pari.pi()
5492            3.141592653589793238462643383              # 32-bit
5493            3.1415926535897932384626433832795028842    # 64-bit
5494        """
5495        if not precision:
5496            precision = prec
5497        _sig_on
5498        constpi(precision)
5499        return self.new_gen(gpi)
5500
5501    def pollegendre(self, long n, v=-1):
5502        """
5503        pollegendre(n,{v=x}): legendre polynomial of degree n (n
5504        C-integer), in variable v
5505        """
5506        _sig_on
5507        return self.new_gen(legendre(n, self.get_var(v)))
5508
5509    def poltchebi(self, long n, v=-1):
5510        _sig_on
5511        return self.new_gen(tchebi(n, self.get_var(v)))
5512       
5513    def factorial(self, long n):
5514        """
5515        Return the factorial of the integer n as a PARI gen.
5516        """
5517        _sig_on
5518        return self.new_gen(mpfact(n))
5519
5520    def polcyclo(self, long n, v=-1):
5521        _sig_on
5522        return self.new_gen(cyclo(n, self.get_var(v)))
5523
5524    def polsubcyclo(self, long n, long d, v=-1):
5525        _sig_on
5526        return self.new_gen(polsubcyclo(n, d, self.get_var(v)))
5527
5528    def polzagier(self, long n, long m):
5529        _sig_on
5530        return self.new_gen(polzag(n, m))
5531
5532    def listcreate(self, long n):
5533        _sig_on
5534        return self.new_gen(listcreate(n))
5535
5536    def vector(self, long n, entries=None):
5537        """
5538        vector(long n, entries=None):
5539        Create and return the length n PARI vector with given list of entries.
5540        """
5541        cdef gen v
5542        _sig_on
5543        v = self.new_gen(zerovec(n))
5544        if entries != None:
5545            if len(entries) != n:
5546                raise IndexError, "length of entries (=%s) must equal n (=%s)"%\
5547                      (len(entries), n)
5548            for i, x in enumerate(entries):
5549                v[i] = x
5550        return v
5551
5552    def matrix(self, long m, long n, entries=None):
5553        """
5554        matrix(long m, long n, entries=None):
5555        Create and return the m x n PARI matrix with given list of entries.
5556        """
5557        cdef int i, j, k
5558        cdef gen A
5559        _sig_on   
5560        A = self.new_gen(zeromat(m,n)).Mat()
5561        if entries != None:
5562            if len(entries) != m*n:
5563                raise IndexError, "len of entries (=%s) must be %s*%s=%s"%(len(entries),m,n,m*n)
5564            k = 0
5565            for i from 0 <= i < m:
5566                for j from 0 <= j < n:
5567                    A[i,j] = entries[k]
5568                    k = k + 1
5569        return A
5570
5571    def finitefield_init(self, p, long n, var=-1):
5572        """
5573        finitefield_init(p, long n, var="x"): Return a polynomial f(x) so
5574        that the extension of F_p of degree n is k = F_p[x]/(f).  Moreover,
5575        the element x (mod f) of k is a generator for the multiplicative
5576        group of k.
5577
5578        INPUT:
5579            p -- int, a prime number
5580            n -- int, positive integer
5581            var -- str, default to "x", but could be any pari variable.
5582        OUTPUT:
5583            pari polynomial mod p -- defines field
5584        EXAMPLES:
5585            sage: pari.finitefield_init(97,1)
5586            Mod(1, 97)*x + Mod(92, 97)
5587
5588        The last entry in each of the following two lines is
5589        determined by a random algorithm.
5590            sage: pari.finitefield_init(7,2)       # random
5591            Mod(1, 7)*x^2 + Mod(6, 7)*x + Mod(3, 7)
5592            sage: pari.finitefield_init(2,3)       # random
5593            Mod(1, 2)*x^3 + Mod(1, 2)*x^2 + Mod(1, 2)
5594        """
5595        cdef gen _p, _f2, s
5596        cdef int err
5597        cdef long x
5598        cdef GEN v, g
5599        _p = self(int(p))
5600        if n < 1:
5601            raise ArithmeticError, "Degree n (=%s) must be at least 1."%n
5602        if _p < 2 or not _p.isprime():
5603            raise ArithmeticError, "Prime p (=%s) must be prime."%_p
5604        x = self.get_var(var)
5605        if n == 1:
5606            _sig_on
5607            return self.new_gen(ffinit(_p.g, n, x)) - _p.znprimroot()
5608        _sig_on   
5609        f = self.new_gen(ffinit(_p.g, n, x))
5610        _f2 = f.lift()
5611        _sig_on
5612        g = FpXQ_gener(_f2.g, _p.g)
5613        s = self.new_gen(g)*self.ONE.Mod(p)
5614        return s.Mod(f).charpoly(var)
5615
5616
5617    ##############################################
5618
5619
5620cdef int init_stack(size_t size) except -1:
5621    cdef size_t s
5622
5623    global top, bot, avma, stack_avma
5624
5625    # delete this if get core dumps and change the 2* to a 1* below.
5626    if bot:
5627        sage_free(<void*>bot)
5628
5629    if size == 0:
5630        size = 2*(top-bot)
5631
5632    # if size == -1, then allocate the biggest chunk possible
5633    if size == -1:
5634        s = 4294967295
5635        while True:
5636            s = fix_size(s)
5637            bot = <pari_sp> sage_malloc(s)
5638            if bot:
5639                break
5640            s = s/2
5641    else:
5642        # Decide on size
5643        s = fix_size(size)
5644        # Alocate memory for new stack using Python's memory allocator.
5645        # As explained in the python/C api reference, using this instead
5646        # of malloc is much better (and more platform independent, etc.)
5647        bot = <pari_sp> sage_malloc(s)
5648        if not bot:
5649            raise MemoryError, "Unable to allocate %s bytes memory for PARI."%(<long>size)
5650    #endif
5651
5652    top = bot + s
5653    avma = top
5654    stack_avma = avma
5655
5656
5657def _my_sigpipe(signum, frame):
5658    # If I do anything, it messes up Ipython's pager.
5659    pass
5660
5661cdef size_t fix_size(size_t a):
5662    cdef size_t b
5663    b = a - (a & (BYTES_IN_LONG-1))     # sizeof(long) | b <= a 
5664    if b < 1024:
5665        b = 1024
5666    return b
5667
5668cdef GEN deepcopy_to_python_heap(GEN x, pari_sp* address):
5669    cdef size_t s
5670    cdef pari_sp tmp_bot, tmp_top, tmp_avma
5671    global avma, bot, top
5672    cdef GEN h
5673
5674    tmp_top = top
5675    tmp_bot = bot
5676    tmp_avma = avma
5677
5678    h = forcecopy(x)
5679    s = <size_t> (tmp_avma - avma)
5680
5681    #print "Allocating %s bytes for PARI/Python object"%(<long> s)
5682    bot = <pari_sp> sage_malloc(s)
5683    top = bot + s
5684    avma = top
5685    h = forcecopy(x)
5686    address[0] = bot
5687
5688    # Restore the stack to how it was before x was created.
5689    top = tmp_top
5690    bot = tmp_bot
5691    avma = tmp_avma
5692    return h
5693
5694cdef gen _new_gen(GEN x):
5695    cdef GEN h
5696    cdef pari_sp address
5697    cdef gen y
5698    _sig_on
5699    h = deepcopy_to_python_heap(x, &address)
5700    y = gen()   
5701    y.init(h, address)
5702    _sig_off
5703    return y
5704
5705def min(x,y):
5706    """
5707    min(x,y): Return the minimum of x and y.
5708    """
5709    if x <= y:
5710        return x
5711    return y
5712
5713def max(x,y):
5714    """
5715    max(x,y): Return the maximum of x and y.
5716    """
5717    if x >= y:
5718        return x
5719    return y
5720
5721cdef int _read_script(char* s) except -1:
5722    _sig_on
5723    gp_read_str(s)
5724    _sig_off
5725
5726    # We set top to avma, so the script's affects won't be undone
5727    # when we call new_gen again.
5728    global top, avma
5729    top = avma
5730    return 0
5731
5732
5733#######################
5734# Base gen class
5735#######################
5736
5737
5738cdef extern from "pari/pari.h":
5739    char *errmessage[]
5740    int user
5741    int errpile
5742    int noer
5743
5744def __errmessage(d):
5745    if d <= 0 or d > noer:
5746        return "unknown"
5747    return errmessage[d]
5748
5749# FIXME: we derive PariError from RuntimeError, for backward
5750# compatibility with code that catches the latter. Once this is
5751# in production, we should change the base class to StandardError.
5752from exceptions import RuntimeError
5753
5754# can we have "cdef class" ?
5755# because of the inheritance, need to somehow "import" the builtin
5756# exception class...
5757class PariError (RuntimeError):
5758
5759    errmessage = staticmethod(__errmessage)
5760
5761    def __repr__(self):
5762        return "PariError(%d)"%self.args[0]
5763
5764    def __str__(self):
5765        return "%s (%d)"%(self.errmessage(self.args[0]),self.args[0])
5766
5767# We expose a trap function to C.
5768# If this function returns without raising an exception,
5769# the code is retried.
5770# This is a proof-of-concept example.
5771# THE TRY CODE IS NOT REENTRANT -- NO CALLS TO PARI FROM HERE !!!
5772#              - Gonzalo Tornario
5773
5774cdef void _pari_trap "_pari_trap" (long errno, long retries) except *:
5775    if retries > 100:
5776        raise RuntimeError, "_pari_trap recursion too deep"
5777    if errno == errpile:
5778        P.allocatemem()
5779        raise RuntimeError, "The PARI stack overflowed.  It has automaticallyed been doubled using pari.allocatemem().  Please retry your computation, possibly after you manually call pari.allocatemem() a few times."
5780   
5781        #print "Stack overflow! (%d retries so far)"%retries
5782        #print " enlarge the stack."
5783        P.allocatemem(silent=True)
5784    elif errno == user:
5785        raise Exception, "PARI user exception"
5786    else:
5787        raise PariError, errno
5788
5789
Note: See TracBrowser for help on using the repository browser.