Ticket #10596: trac_10596.patch

File trac_10596.patch, 41.2 KB (added by aapitzsch, 9 years ago)
  • sage/rings/arith.py

    # HG changeset patch
    # User André Apitzsch <andre.apitzsch@st.ovgu.de>
    # Date 1322318713 -3600
    # Node ID 8040305b41cbf03a9c8ef3393883cccfc0b6da9f
    # Parent  8dc202870ff7395b379a982cbc72f7e1e7979686
    trac 10596: misc improvements to integer.pyx
    
    diff --git a/sage/rings/arith.py b/sage/rings/arith.py
    a b  
    24412441        sage: odd_part(factorial(31))
    24422442        122529844256906551386796875
    24432443    """
    2444     n = ZZ(n)
    2445     return n._shift_helper(n.valuation(2), -1)
     2444    if not isinstance(n, integer.Integer):
     2445        n = ZZ(n)
     2446    return n.odd_part()
    24462447
    24472448def prime_to_m_part(n,m):
    24482449    """
  • sage/rings/integer.pyx

    diff --git a/sage/rings/integer.pyx b/sage/rings/integer.pyx
    a b  
    9797    sage: 'sage'*Integer(3)
    9898    'sagesagesage'
    9999
    100 COERCIONS: Returns version of this integer in the multi-precision
    101 floating real field R.
    102 
    103 ::
     100COERCIONS:
     101
     102Returns version of this integer in the multi-precision floating
     103real field R::
    104104
    105105    sage: n = 9390823
    106106    sage: RR = RealField(200)
    107107    sage: RR(n)
    108108    9.3908230000000000000000000000000000000000000000000000000000e6
    109109
    110 
    111110"""
    112111#*****************************************************************************
    113112#       Copyright (C) 2004,2006 William Stein <wstein@gmail.com>
     
    291290    cdef Integer temp
    292291    cdef int v_int
    293292    if power_index < 5:
    294         # It turns out that simple repeated division is very fast for relatively few digits.
    295         # I don't think this is a real algorithmic statement, it's an annoyance introduced by memory allocation.
    296         # I think that manual memory management with mpn_* would make the divide & conquer approach even faster, but the code would be much more complicated.
     293        # It turns out that simple repeated division is very fast for
     294        # relatively few digits.  I don't think this is a real algorithmic
     295        # statement, it's an annoyance introduced by memory allocation.
     296        # I think that manual memory management with mpn_* would make the
     297        # divide & conquer approach even faster, but the code would be much
     298        # more complicated.
    297299        _digits_naive(v,l,offset,power_list[0],digits)
    298300    else:
    299301        mpz_init(mpz_quot)
     
    431433        The class ``Integer`` is implemented in Cython, as a
    432434        wrapper of the GMP ``mpz_t`` integer type.
    433435   
    434    
    435436    EXAMPLES::
    436437   
    437438        sage: Integer(010)
     
    597598            ...
    598599            TypeError: Unable to coerce PARI x to an Integer       
    599600        """
    600 
    601601        # TODO: All the code below should somehow be in an external
    602602        # cdef'd function.  Then e.g., if a matrix or vector or
    603603        # polynomial is getting filled by mpz_t's, it can use the
     
    799799            return (<Integer>x)._xor(y)
    800800        return bin_op(x, y, operator.xor)
    801801       
    802        
    803802    def __richcmp__(left, right, int op):
    804803        """
    805804        cmp for integers
     
    927926        set_mpz(z,self.value)
    928927        return z
    929928
    930 
    931929    def list(self):
    932930        """
    933931        Return a list with this integer in it, to be compatible with the
     
    941939        """
    942940        return [ self ]
    943941
    944 
    945942    def  __dealloc__(self):
    946943        mpz_clear(self.value)
    947944
     
    12451242       
    12461243        INPUT:
    12471244       
    1248        
    12491245        -  ``base`` - integer (default: 10)
    12501246       
    12511247        -  ``digits`` - optional indexable object as source for
     
    13931389                z = the_integer_ring._zero_element
    13941390            l = [z]*(s if s >= padto else padto)
    13951391            for i from 0<= i < s:
    1396                 if mpz_tstbit(self_abs.value,i):  # mpz_tstbit seems to return 0 for the high-order bit of negative numbers?!
     1392                # mpz_tstbit seems to return 0 for the high-order bit of
     1393                # negative numbers?!
     1394                if mpz_tstbit(self_abs.value,i):
    13971395                    l[i] = o
    13981396        else:
    13991397            s = mpz_sizeinbase(self.value, 2)
    14001398            do_sig_on = (s > 256)
    14011399            if do_sig_on: sig_on()
    14021400
    1403             #   We use a divide and conquer approach (suggested
    1404             # by the prior author, malb?, of the digits method)
    1405             # here: for base b, compute b^2, b^4, b^8,
    1406             # ... (repeated squaring) until you get larger
    1407             # than your number; then compute (n // b^256,
    1408             # n % b ^ 256) (if b^512 > number) to split
    1409             # the number in half and recurse
    1410 
    1411             #   Pre-computing the exact number of digits up-front is actually faster (especially for large
    1412             # values of self) than trimming off trailing zeros after the fact.  It also seems that it would
     1401            # We use a divide and conquer approach (suggested by the prior
     1402            # author, malb?, of the digits method) here: for base b, compute
     1403            # b^2, b^4, b^8, ... (repeated squaring) until you get larger
     1404            # than your number; then compute (n // b^256, n % b^256)
     1405            # (if b^512 > number) to split the number in half and recurse
     1406
     1407            # Pre-computing the exact number of digits up-front is actually
     1408            # faster (especially for large values of self) than trimming off
     1409            # trailing zeros after the fact.  It also seems that it would
    14131410            # avoid duplicating the list in memory with a list-slice.
    14141411            z = the_integer_ring._zero_element if digits is None else digits[0]
    14151412            s = self_abs.exact_log(_base)
    14161413            l = [z]*(s+1 if s+1 >= padto else padto)
    14171414
    1418             # set up digits for optimal access once we get inside the worker functions
     1415            # set up digits for optimal access once we get inside the worker
     1416            # functions
    14191417            if not digits is None:
    14201418                # list objects have fastest access in the innermost loop
    14211419                if not PyList_CheckExact(digits):
    14221420                    digits = [digits[i] for i in range(_base)]
    14231421            elif mpz_cmp_ui(_base.value,s) < 0 and mpz_cmp_ui(_base.value,10000):
    1424                 # We can get a speed boost by pre-allocating digit values in big cases
    1425                 # We do this we have more digits than the base and the base is not too
    1426                 # extremely large (currently, "extremely" means larger than 10000 --
    1427                 # that's very arbitrary.)
     1422                # We can get a speed boost by pre-allocating digit values in
     1423                # big cases.
     1424                # We do this we have more digits than the base and the base
     1425                # is not too extremely large (currently, "extremely" means
     1426                # larger than 10000 -- that's very arbitrary.)
    14281427                if mpz_sgn(self.value) > 0:
    14291428                    digits = [Integer(i) for i in range(_base)]
    14301429                else:
     
    14461445                for power_index from 1 <= power_index < i:
    14471446                    power_list[power_index] = power_list[power_index-1]**2
    14481447
    1449                 #   Note that it may appear that the recursive calls to _digit_internal would be assigning
    1450                 # list elements i in l for anywhere from 0<=i<(1<<power_index).  However, this is not
    1451                 # the case due to the optimization of skipping assigns assigning zero.
     1448                # Note that it may appear that the recursive calls to
     1449                # _digit_internal would be assigning list elements i in l for
     1450                # anywhere from 0<=i<(1<<power_index).  However, this is not
     1451                # the case due to the optimization of skipping assigns
     1452                # assigning zero.
    14521453                _digits_internal(self.value,l,0,i-1,power_list,digits)
    14531454
    14541455            if do_sig_on: sig_off()
     
    14631464       
    14641465        INPUT:
    14651466       
    1466        
    14671467        -  ``base`` - integer (default: 10)
    14681468       
    1469        
    14701469        EXAMPLES::
    14711470       
    14721471            sage: n = 52
     
    14781477            sage: n = 15
    14791478            sage: n.ndigits(2)
    14801479            4
    1481             sage: n=1000**1000000+1
     1480            sage: n = 1000**1000000+1
    14821481            sage: n.ndigits()
    14831482            3000001
    1484             sage: n=1000**1000000-1
     1483            sage: n = 1000**1000000-1
    14851484            sage: n.ndigits()
    14861485            3000000
    1487             sage: n=10**10000000-10**9999990
     1486            sage: n = 10**10000000-10**9999990
    14881487            sage: n.ndigits()
    14891488            10000000
    14901489        """
    14911490        cdef Integer temp
    1492         if mpz_cmp_si(self.value,0) == 0:
     1491
     1492        if mpz_sgn(self.value) == 0:
    14931493            temp = PY_NEW(Integer)
    1494             mpz_set_ui(temp.value,0)
     1494            mpz_set_ui(temp.value, 0)
    14951495            return temp
    1496         elif mpz_cmp_si(self.value,0) > 0:
    1497             temp=self.exact_log(base)
    1498             mpz_add_ui(temp.value,temp.value,1)
     1496
     1497        if mpz_sgn(self.value) > 0:
     1498            temp = self.exact_log(base)
     1499            mpz_add_ui(temp.value, temp.value, 1)
    14991500            return temp
    15001501        else:
    15011502            return self.abs().exact_log(base) + 1
     
    17061707            sage: Integer(32) / Integer(32)
    17071708            1
    17081709        """
    1709         # this is vastly faster than doing it here, since here
     1710        # This is vastly faster than doing it here, since here
    17101711        # we can't cimport rationals.
    17111712        return the_integer_ring._div(self, right)
    17121713
     
    17761777        else:
    17771778            return bin_op(x, y, operator.floordiv)
    17781779
    1779 
    17801780    def __pow__(self, n, modulus):
    17811781        r"""
    17821782        Computes `\text{self}^n`
     
    18691869            from sage.rings.finite_rings.integer_mod import Mod
    18701870            return Mod(self, modulus) ** n
    18711871       
    1872        
    18731872        if not PY_TYPE_CHECK(self, Integer):
    18741873            if isinstance(self, str):
    18751874                return self * n
     
    19091908        else:
    19101909            return x
    19111910
    1912 
    19131911    def nth_root(self, int n, bint truncate_mode=0):
    19141912        r"""
    19151913        Returns the (possibly truncated) n'th root of self.
    19161914       
    19171915        INPUT:
    19181916       
    1919        
    19201917        -  ``n`` - integer >= 1 (must fit in C int type).
    19211918       
    19221919        -  ``truncate_mode`` - boolean, whether to allow truncation if
    19231920           self is not an n'th power.
    19241921       
    1925        
    1926         OUTPUT: If truncate_mode is 0 (default), then returns the
    1927         exact n'th root if self is an n'th power, or raises a
    1928         ValueError if it is not.
     1922        OUTPUT:
     1923       
     1924        If truncate_mode is 0 (default), then returns the exact n'th root
     1925        if self is an n'th power, or raises a ValueError if it is not.
    19291926       
    19301927        If truncate_mode is 1, then if either n is odd or self is
    19311928        positive, returns a pair (root, exact_flag) where root is the
     
    20282025
    20292026    cpdef size_t _exact_log_log2_iter(self,Integer m):
    20302027        """
    2031         This is only for internal use only.  You should expect it to crash and burn for
    2032         negative or other malformed input.  In particular, if the base `2\leq m<4` the log2
    2033         approximation of m is 1 and certain input causes endless loops.  Along these lines,
    2034         it is clear that this function is most useful for m with a relatively large number
     2028        This is only for internal use only.  You should expect it to crash
     2029        and burn for negative or other malformed input.  In particular, if
     2030        the base `2 \leq m < 4` the log2 approximation of m is 1 and certain
     2031        input causes endless loops.  Along these lines, it is clear that
     2032        this function is most useful for m with a relatively large number
    20352033        of bits.
    20362034
    2037         For ``small`` values (which I'll leave quite ambiguous), this function is a fast
    2038         path for exact log computations.  Any integer division with such input tends to
    2039         dominate the runtime.  Thus we avoid division entirely in this function.
     2035        For ``small`` values (which I'll leave quite ambiguous), this function
     2036        is a fast path for exact log computations.  Any integer division with
     2037        such input tends to dominate the runtime.  Thus we avoid division
     2038        entirely in this function.
    20402039
    20412040        AUTHOR::
    20422041
     
    20582057        cdef mpz_t accum
    20592058        cdef mpz_t temp_exp
    20602059
    2061         if mpz_cmp_si(m.value,4)<0:
     2060        if mpz_cmp_si(m.value,4) < 0:
    20622061            raise ValueError, "This is undefined or possibly non-convergent with this algorithm."
    20632062
    20642063        n_log2=mpz_sizeinbase(self.value,2)-1
     
    20722071            mpz_set_ui(accum,1)
    20732072            l = 0
    20742073            while l_min != l_max:
    2075                 #print "self=...",m,l_min,l_max
     2074                # print "self=...",m,l_min,l_max
    20762075                if l_min + 1 == l_max:
    20772076                    mpz_pow_ui(temp_exp,m.value,l_min+1-l)
    2078                     mpz_mul(accum,accum,temp_exp) # this might over-shoot and make accum > self, but we'll know that it's only over by a factor of m^1.
     2077                    # This might over-shoot and make accum > self, but
     2078                    # we'll know that it's only over by a factor of m^1.
     2079                    mpz_mul(accum,accum,temp_exp)
    20792080                    if mpz_cmp(self.value,accum) >= 0:
    20802081                        l_min += 1
    20812082                    break
     
    20832084                mpz_mul(accum,accum,temp_exp)
    20842085                l = l_min
    20852086
    2086                 #Let x=n_log2-(mpz_sizeinbase(accum,2)-1) and y=m_log2.  Now, with x>0 and y>0, we have the
    2087                 #following observation.  If floor((x-1)/(y+1))=0, then x-1<y+1 which implies that x/y<1+2/y. 
    2088                 #So long as y>=2, this means that floor(x/y)<=1.  This shows that this iteration is forced to
    2089                 #converge for input m>=4.  If m=3, we can find input so that floor((x-1)/(y+1))=0 and floor(x/y)=2
    2090                 #which results in non-convergence.
    2091 
    2092                 # We need the additional '-1' in the l_min computation because mpz_sizeinbase(accum,2)-1 is smaller than the true log_2(accum)
     2087                # Let x=n_log2-(mpz_sizeinbase(accum,2)-1) and y=m_log2.
     2088                # Now, with x>0 and y>0, we have the following observation.
     2089                # If floor((x-1)/(y+1))=0, then x-1<y+1 which implies that
     2090                # x/y<1+2/y. 
     2091                # So long as y>=2, this means that floor(x/y)<=1.  This shows
     2092                # that this iteration is forced to converge for input m >= 4.
     2093                # If m=3, we can find input so that floor((x-1)/(y+1))=0 and
     2094                # floor(x/y)=2 which results in non-convergence.
     2095
     2096                # We need the additional '-1' in the l_min computation
     2097                # because mpz_sizeinbase(accum,2)-1 is smaller than the
     2098                # true log_2(accum)
    20932099                l_min=l+(n_log2-(mpz_sizeinbase(accum,2)-1)-1)/(m_log2+1)
    20942100                l_max=l+(n_log2-(mpz_sizeinbase(accum,2)-1))/m_log2
    20952101            mpz_clear(temp_exp)
     
    20992105
    21002106    cpdef size_t _exact_log_mpfi_log(self,m):
    21012107        """
    2102         This is only for internal use only.  You should expect it to crash and burn for
    2103         negative or other malformed input.
    2104 
    2105         I avoid using this function until the input is large.  The overhead associated
    2106         with computing the floating point log entirely dominates the runtime for small values.
    2107         Note that this is most definitely not an artifact of format conversion.  Tricks
    2108         with log2 approximations and using exact integer arithmetic are much better for
    2109         small input.
     2108        This is only for internal use only.  You should expect it to crash
     2109        and burn for negative or other malformed input.
     2110
     2111        I avoid using this function until the input is large.  The overhead
     2112        associated with computing the floating point log entirely dominates
     2113        the runtime for small values.  Note that this is most definitely not
     2114        an artifact of format conversion.  Tricks with log2 approximations
     2115        and using exact integer arithmetic are much better for small input.
    21102116
    21112117        AUTHOR::
    21122118
     
    21402146            # I'm not sure what to do now
    21412147            upper = 0
    21422148        lower = rif_log.lower().floor()
    2143         # since the log function is monotonic increasing, lower and upper bracket our desired answer
     2149        # since the log function is monotonic increasing, lower
     2150        # and upper bracket our desired answer
    21442151
    21452152        # if upper - lower == 1: "we are done"
    21462153        if upper - lower == 2:
    2147             # You could test it by checking rif_m**(lower+1), but I think that's a waste of time since it won't be conclusive
    2148             # We must test with exact integer arithmetic which takes all the bits of self into account.
     2154            # You could test it by checking rif_m**(lower+1), but I think
     2155            # that's a waste of time since it won't be conclusive.
     2156            # We must test with exact integer arithmetic which takes all
     2157            # the bits of self into account.
    21492158            sig_off()
    21502159            if self >= m**(lower+1):
    21512160                return lower + 1
     
    21912200
    21922201    def exact_log(self, m):
    21932202        r"""
    2194         Returns the largest integer `k` such that
    2195         `m^k \leq \text{self}`, i.e., the floor of
    2196         `\log_m(\text{self})`.
     2203        Returns the largest integer `k` such that `m^k \leq \text{self}`,
     2204        i.e., the floor of `\log_m(\text{self})`.
    21972205       
    21982206        This is guaranteed to return the correct answer even when the usual
    21992207        log function doesn't have sufficient precision.
    22002208       
    22012209        INPUT:
    22022210       
    2203        
    22042211        -  ``m`` - integer >= 2
    22052212       
    2206        
    22072213        AUTHORS:
    22082214
    22092215        - David Harvey (2006-09-15)
     
    22712277        cdef size_t n_log2
    22722278        cdef size_t m_log2
    22732279        cdef size_t guess # this will contain the final answer
    2274         cdef bint guess_filled = 0  # this variable is only used in one branch below.
     2280        cdef bint guess_filled = 0  # this variable is only used in one branch below
    22752281        cdef mpz_t z
    22762282        if PY_TYPE_CHECK(m,Integer):
    22772283            _m=<Integer>m
     
    22862292        n_log2=mpz_sizeinbase(self.value,2)-1
    22872293        m_log2=mpz_sizeinbase(_m.value,2)-1
    22882294        if mpz_divisible_2exp_p(_m.value,m_log2):
    2289             # Here, m is a power of 2 and the correct answer is found by a log 2 approximation.
     2295            # Here, m is a power of 2 and the correct answer is found
     2296            # by a log 2 approximation.
    22902297            guess = n_log2/m_log2 # truncating division
    22912298        elif n_log2/(m_log2+1) == n_log2/m_log2:
    2292             # In this case, we have an upper bound and lower bound which give the same answer, thus, the correct answer.
     2299            # In this case, we have an upper bound and lower bound which
     2300            # give the same answer, thus, the correct answer.
    22932301            guess = n_log2/m_log2
    22942302        elif m_log2 < 8: # i.e. m<256
    22952303            # if the base m is at most 256, we can use mpz_sizeinbase
     
    23142322                    guess =  guess - 1
    23152323            if not guess_filled:
    23162324                # At this point, either
    2317                 #  1)  self is close enough to a perfect power of m that we need an exact comparison, or
    2318                 #  2)  the numbers are small enough that converting to the interval field is more work than the exact comparison.
     2325                #  1)  self is close enough to a perfect power of m that we
     2326                #      need an exact comparison, or
     2327                #  2)  the numbers are small enough that converting to the
     2328                #      interval field is more work than the exact comparison.
    23192329                compare = _m**guess
    23202330                if self < compare:
    23212331                    guess = guess - 1
    23222332        elif n_log2 < 5000:
    2323             # for input with small exact log, it's very fast to work in exact integer arithmetic starting from log2 approximations
     2333            # for input with small exact log, it's very fast to work in exact
     2334            # integer arithmetic starting from log2 approximations
    23242335            guess = self._exact_log_log2_iter(_m)
    23252336        else:
    2326             # finally, we are out of easy cases
    2327             # this subroutine uses interval arithmetic to guess and check the exact log.
     2337            # finally, we are out of easy cases this subroutine uses interval
     2338            # arithmetic to guess and check the exact log.
    23282339            guess = self._exact_log_mpfi_log(_m)
    23292340
    2330         result = <Integer>PY_NEW(Integer)
     2341        result = PY_NEW(Integer)
    23312342        mpz_set_ui(result.value,guess)
    23322343        return result
    23332344
     
    23432354       
    23442355        INPUT:
    23452356       
    2346        
    23472357        -  ``m`` - default: natural log base e
    23482358       
    23492359        -  ``prec`` - integer (default: None): if None, returns
    23502360           symbolic, else to given bits of precision as in RealField
    23512361       
    2352        
    23532362        EXAMPLES::
    23542363       
    23552364            sage: Integer(124).log(5)
     
    24682477       
    24692478        INPUT:
    24702479       
    2471        
    24722480        -  ``m`` - Integer
    24732481       
    2474        
    24752482        OUTPUT: Integer
    24762483       
    24772484        EXAMPLES::
     
    25562563            raise ValueError, "n must be nonzero"
    25572564        f = self.factor()
    25582565
    2559         # All of the declarations below are for optimizing the word-sized case.
    2560         # Operations are performed in c as far as possible without overflow before
    2561         # moving to python objects.
     2566        # All of the declarations below are for optimizing the word-sized
     2567        # case.  Operations are performed in c as far as possible without
     2568        # overflow before moving to python objects.
    25622569        cdef long long p_c, pn_c, apn_c
    25632570        cdef long all_len, sorted_len, prev_len
    25642571        cdef long long* ptr
     
    25992606                sage_free(ptr)
    26002607                fits_c = False
    26012608
    2602             # The two cases below are essentially the same algorithm, one operating
    2603             # on Integers in Python lists, the other on long longs.
     2609            # The two cases below are essentially the same algorithm, one
     2610            # operating on Integers in Python lists, the other on long longs.
    26042611            if fits_c:
    26052612               
    26062613                pn_c = p_c = p
     
    26982705            sage: abs(z) == abs(1)
    26992706            True
    27002707        """
    2701         cdef Integer x
    2702         x = PY_NEW(Integer)
     2708        cdef Integer x = PY_NEW(Integer)
    27032709        mpz_abs(x.value, self.value)
    27042710        return x
    27052711
     
    27412747            sage: a % b
    27422748            59
    27432749         """
    2744         cdef Integer z = <Integer>PY_NEW(Integer)
     2750        cdef Integer z = PY_NEW(Integer)
    27452751        cdef long yy, res
    27462752
    27472753        # first case: Integer % Integer
     
    27812787            except ValueError:
    27822788                return bin_op(x, y, operator.mod)
    27832789
    2784 
    27852790    def quo_rem(Integer self, other):
    27862791        """
    27872792        Returns the quotient and the remainder of self divided by other.
     
    27902795       
    27912796        INPUT:
    27922797       
    2793        
    27942798        -  ``other`` - the integer the divisor
    27952799       
    2796        
    27972800        OUTPUT:
    27982801       
    27992802       
     
    28012804       
    28022805        -  ``r`` - the remainder of self/other
    28032806       
    2804        
    28052807        EXAMPLES::
    28062808       
    28072809            sage: z = Integer(231)
     
    33973399            return sage.rings.infinity.infinity
    33983400        if mpz_cmp_ui(p.value, 2) < 0:
    33993401            raise ValueError, "You can only compute the valuation with respect to a integer larger than 1."
    3400         cdef Integer v
    3401         v = PY_NEW(Integer)
     3402
     3403        cdef Integer v = PY_NEW(Integer)
    34023404        cdef mpz_t u
    34033405        mpz_init(u)
    34043406        sig_on()
     
    34393441       
    34403442        INPUT:
    34413443       
    3442        
    34433444        -  ``p`` - an integer at least 2.
    34443445       
    3445        
    34463446        EXAMPLE::
    34473447       
    34483448            sage: n = 60
     
    34643464        """
    34653465        return self._valuation(Integer(p))
    34663466
     3467    # Alias for valuation
     3468    ord = valuation
     3469
    34673470    def val_unit(self, p):
    34683471        r"""
    34693472        Returns a pair: the p-adic valuation of self, and the p-adic unit
     
    34713474       
    34723475        INPUT:
    34733476       
    3474        
    34753477        -  ``p`` - an integer at least 2.
    34763478       
    3477        
    34783479        OUTPUT:
    34793480       
    3480        
    3481         -  ``v_p(self)`` - the p-adic valuation of
    3482            ``self``
    3483        
    3484         -  ``u_p(self)`` - ``self`` /
    3485            `p^{v_p(\mathrm{self})}`
    3486        
     3481        -  ``v_p(self)`` - the p-adic valuation of ``self``
     3482       
     3483        -  ``u_p(self)`` - ``self`` / `p^{v_p(\mathrm{self})}`
    34873484       
    34883485        EXAMPLE::
    34893486       
     
    35013498        """
    35023499        return self._val_unit(Integer(p))
    35033500
    3504     def ord(self, p=None):
    3505         """
    3506         Synonym for valuation
     3501    def odd_part(self):
     3502        r"""
     3503        The odd part of the integer `n`. This is `n / 2^v`,
     3504        where `v = \mathrm{valuation}(n,2)`.
     3505
     3506        IMPLEMENTATION:
     3507
     3508        Currently returns 0 when self is 0.  This behaviour is fairly arbitrary,
     3509        and in Sage 4.6 this special case was not handled at all, eventually
     3510        propagating a TypeError.  The caller should not rely on the behaviour
     3511        in case self is 0.
    35073512       
    35083513        EXAMPLES::
    35093514       
    3510             sage: n=12
    3511             sage: n.ord(3)
     3515            sage: odd_part(5)
     3516            5
     3517            sage: odd_part(4)
    35123518            1
    3513         """
    3514         return self.valuation(p)
     3519            sage: odd_part(factorial(31))
     3520            122529844256906551386796875
     3521        """
     3522        cdef Integer odd
     3523        cdef unsigned long bits
     3524
     3525        if mpz_cmpabs_ui(self.value, 1) <= 0:
     3526            return self
     3527
     3528        odd  = PY_NEW(Integer)
     3529        bits = mpz_scan1(self.value, 0)
     3530        mpz_tdiv_q_2exp(odd.value, self.value, bits)
     3531        return odd
    35153532
    35163533    cdef Integer _divide_knowing_divisible_by(Integer self, Integer right):
    35173534        r"""
     
    35793596            sage: n._lcm(150)
    35803597            300
    35813598        """
    3582         cdef Integer z
    3583         z = PY_NEW(Integer)
     3599        cdef Integer z = PY_NEW(Integer)
    35843600        sig_on()
    35853601        mpz_lcm(z.value, self.value, n.value)
    35863602        sig_off()
     
    36053621        """
    36063622        Return the numerator of this integer.
    36073623       
    3608         EXAMPLE::
     3624        EXAMPLES::
    36093625       
    36103626            sage: x = 5
    36113627            sage: x.numerator()
     
    37093725                sign = ONE
    37103726            return sign / Integer(-k-n).multifactorial(k)
    37113727               
    3712         # compute the actual product, optimizing the number of large multiplications
     3728        # compute the actual product, optimizing the number of large
     3729        # multiplications
    37133730        cdef int i,j
    37143731       
    37153732        # we need (at most) log_2(#factors) concurrent sub-products
     
    37493766
    37503767        return z
    37513768
    3752        
    37533769    def gamma(self):
    37543770        r"""
    3755         The gamma function on integers is the factorial function (shifted
    3756         by one) on positive integers, and `\pm \infty` on
    3757         non-positive integers.
     3771        The gamma function on integers is the factorial function (shifted by
     3772        one) on positive integers, and `\pm \infty` on non-positive integers.
    37583773       
    37593774        EXAMPLES::
    37603775       
     
    38233838       
    38243839    def is_one(self):
    38253840        r"""
    3826         Returns ``True`` if the integer is `1`,
    3827         otherwise ``False``.
     3841        Returns ``True`` if the integer is `1`, otherwise ``False``.
    38283842       
    38293843        EXAMPLES::
    38303844       
     
    38373851
    38383852    def __nonzero__(self):
    38393853        r"""
    3840         Returns ``True`` if the integer is not `0`,
    3841         otherwise ``False``.
     3854        Returns ``True`` if the integer is not `0`, otherwise ``False``.
    38423855       
    38433856        EXAMPLES::
    38443857       
     
    38633876
    38643877    def is_unit(self):
    38653878        r"""
    3866         Returns ``true`` if this integer is a unit, i.e., 1 or
    3867         `-1`.
     3879        Returns ``true`` if this integer is a unit, i.e., 1 or `-1`.
    38683880       
    38693881        EXAMPLES::
    38703882       
     
    38763888            1 True
    38773889            2 False
    38783890        """
    3879         return mpz_cmp_si(self.value, -1) == 0 or mpz_cmp_si(self.value, 1) == 0
     3891        return mpz_cmpabs_ui(self.value, 1) == 0
    38803892
    38813893    def is_square(self):
    38823894        r"""
    3883         Returns ``True`` if self is a perfect square
     3895        Returns ``True`` if self is a perfect square.
    38843896       
    38853897        EXAMPLES::
    38863898       
     
    38933905
    38943906    def is_power(self):
    38953907        r"""
    3896         Returns ``True`` if self is a perfect power, ie if
    3897         there exist integers a and b, `b > 1` with
    3898         `self = a^b`.
     3908        Returns ``True`` if self is a perfect power, i.e. if there exist
     3909        integers `a` and `b`, `b > 1` with `self = a^b`.
    38993910       
    39003911        EXAMPLES::
    39013912       
     
    39113922        Returns a non-zero int if there is an integer b with
    39123923        `\mathtt{self} = n^b`.
    39133924       
    3914         For more documentation see ``is_power_of``
     3925        For more documentation see ``is_power_of``.
    39153926       
    39163927        AUTHORS:
    39173928
     
    42244235            sage: z.is_irreducible()
    42254236            True
    42264237        """
    4227         n = self if self>=0 else -self
     4238        n = self if self >= 0 else -self
    42284239        return bool(n._pari_().isprime())
    42294240
    42304241    def is_pseudoprime(self):
     
    42604271            sage: (-4).is_perfect_power()
    42614272            False
    42624273
    4263         This is a test to make sure we workaround a bug in GMP. (See
    4264         trac \#4612.)
     4274        This is a test to make sure we work around a bug in GMP,
     4275        see trac \#4612.
    42654276
    42664277        ::
    42674278
     
    42704281        """
    42714282        cdef mpz_t tmp
    42724283        cdef int res
    4273         if mpz_sgn(self.value) == -1:
     4284        if mpz_sgn(self.value) < 0:
    42744285            if mpz_cmp_si(self.value, -1) == 0:
    42754286                return True
    42764287            mpz_init(tmp)
    4277             mpz_mul_si(tmp, self.value, -1)
     4288            mpz_neg(tmp, self.value)
    42784289            while mpz_perfect_square_p(tmp):
    42794290                mpz_sqrt(tmp, tmp)
    42804291            res = mpz_perfect_power_p(tmp)
     
    43694380       
    43704381    def kronecker(self, b):
    43714382        r"""
    4372         Calculate the Kronecker symbol
    4373         `\left(\frac{self}{b}\right)` with the Kronecker extension
    4374         `(self/2)=(2/self)` when self odd, or `(self/2)=0`
    4375         when `self` even.
     4383        Calculate the Kronecker symbol `\left(\frac{self}{b}\right)`
     4384        with the Kronecker extension `(self/2)=(2/self)` when `self` is odd,
     4385        or `(self/2)=0` when `self` is even.
    43764386       
    43774387        EXAMPLES::
    43784388       
     
    44194429
    44204430    def squarefree_part(self, long bound=-1):
    44214431        r"""
    4422         Return the square free part of `x` (=self), i.e., the
    4423         unique integer `z` that `x = z y^2`, with
    4424         `y^2` a perfect square and `z` square-free.
    4425        
    4426         Use ``self.radical()`` for the product of the primes
    4427         that divide self.
     4432        Return the square free part of `x` (=self), i.e., the unique integer
     4433        `z` that `x = z y^2`, with `y^2` a perfect square and `z` square-free.
     4434       
     4435        Use ``self.radical()`` for the product of the primes that divide self.
    44284436       
    44294437        If self is 0, just returns 0.
    44304438       
     
    44634471        cdef Integer z
    44644472        cdef long even_part, p, p2
    44654473        cdef char switch_p
    4466         if mpz_cmp_ui(self.value, 0) == 0:
     4474        if mpz_sgn(self.value) == 0:
    44674475            return self
    44684476        if 0 <= bound < 2:
    44694477            return self
    44704478        elif 2 <= bound <= 10000:
    4471             z = <Integer>PY_NEW(Integer)
     4479            z = PY_NEW(Integer)
    44724480            even_part = mpz_scan1(self.value, 0)
    44734481            mpz_fdiv_q_2exp(z.value, self.value, even_part ^ (even_part&1))
    44744482            sig_on()
     
    45244532       
    45254533        INPUT:
    45264534       
    4527        
    45284535        -  ``proof`` - bool or None (default: None, see
    45294536           proof.arithmetic or sage.structure.proof) Note that the global Sage
    45304537           default is proof=True
    45314538       
    4532        
    45334539        EXAMPLES::
    45344540       
    45354541            sage: Integer(100).next_prime()
     
    45624568            n += 2
    45634569        return integer_ring.ZZ(n)
    45644570   
    4565 
    45664571    def additive_order(self):
    45674572        """
    45684573        Return the additive order of self.
     
    46904695        """
    46914696        Return string that evaluates in Magma to this element.
    46924697
    4693         For small integers we just use base 10.  For large integers we use base 16,
    4694         but use Magma's StringToInteger command, which (for no good reason)
    4695         is much faster than 0x[string literal].  We only use base 16 for integers
    4696         with at least 10000 binary digits, since e.g., for a large list of
    4697         small integers the overhead of calling StringToInteger can be a killer.
     4698        For small integers we just use base 10.  For large integers we use
     4699        base 16, but use Magma's StringToInteger command, which (for no
     4700        good reason) is much faster than 0x[string literal].  We only use
     4701        base 16 for integers with at least 10000 binary digits, since e.g.,
     4702        for a large list of small integers the overhead of calling
     4703        StringToInteger can be a killer.
    46984704
    46994705        EXAMPLES:
    47004706            sage: (117)._magma_init_(magma)           # optional - magma
     
    48044810        """
    48054811        if mpz_sgn(self.value) < 0:
    48064812            raise ValueError, "square root of negative integer not defined."
    4807         cdef Integer x
    4808         x = PY_NEW(Integer)
     4813
     4814        cdef Integer x = PY_NEW(Integer)
    48094815
    48104816        sig_on()
    48114817        mpz_sqrt(x.value, self.value)
     
    48414847       
    48424848        INPUT:
    48434849       
    4844        
    48454850        -  ``prec`` - integer (default: None): if None, returns
    48464851           an exact square root; otherwise returns a numerical square root if
    48474852           necessary, to the given bits of precision.
     
    48544859        -  ``all`` - bool (default: False); if True, return all
    48554860           square roots of self, instead of just one.
    48564861       
    4857        
    48584862        EXAMPLES::
    48594863       
    48604864            sage: Integer(144).sqrt()
     
    49294933       
    49304934        INPUT:
    49314935       
    4932        
    49334936        -  ``self`` - integer
    49344937       
    49354938        -  ``n`` - integer
     
    49374940        -  ``minimal`` - boolean (default false), whether to
    49384941           compute minimal cofactors (see below)
    49394942       
    4940        
    4941         OUTPUT: A triple (g, s, t), where `g` is the non-negative
    4942         gcd of self and `n`, and `s` and `t` are
    4943         cofactors satisfying the Bezout identity
     4943        OUTPUT:
     4944       
     4945        A triple (g, s, t), where `g` is the non-negative gcd of self
     4946        and `n`, and `s` and `t` are cofactors satisfying the Bezout identity
    49444947       
    49454948        .. math::
    49464949       
    49474950             g = s \cdot \mbox{\rm self} + t \cdot n.
    49484951       
    4949        
    4950        
    49514952        .. note::
    49524953
    4953            If minimal is False, then there is no guarantee that the
    4954            returned cofactors will be minimal in any sense; the only
    4955            guarantee is that the Bezout identity will be satisfied
    4956            (see examples below).
    4957        
    4958            If minimal is True, the cofactors will satisfy the
    4959            following conditions. If either self or `n` are zero,
    4960            the trivial solution is returned. If both self and
    4961            `n` are nonzero, the function returns the unique
    4962            solution such that `0 \leq s < |n|/g` (which then
    4963            must also satisfy
    4964            `0 \leq |t| \leq |\mbox{\rm self}|/g`).
     4954           If minimal is False, then there is no guarantee that the returned
     4955           cofactors will be minimal in any sense; the only guarantee is that
     4956           the Bezout identity will be satisfied (see examples below).
     4957           
     4958           If minimal is True, the cofactors will satisfy the following
     4959           conditions. If either self or `n` are zero, the trivial solution
     4960           is returned. If both self and `n` are nonzero, the function returns
     4961           the unique solution such that `0 \leq s < |n|/g` (which then must
     4962           also satisfy `0 \leq |t| \leq |\mbox{\rm self}|/g`).
    49654963       
    49664964        EXAMPLES::
    49674965       
     
    51355133        n *= sign
    51365134
    51375135        # Now finally call into MPIR to do the shifting.
    5138         cdef Integer z = <Integer>PY_NEW(Integer)
     5136        cdef Integer z = PY_NEW(Integer)
    51395137        if n < 0:
    51405138            mpz_fdiv_q_2exp(z.value, self.value, -n)
    51415139        else:
     
    52065204        return (<Integer>x)._shift_helper(y, -1)
    52075205
    52085206    cdef _and(Integer self, Integer other):
    5209         cdef Integer x
    5210         x = PY_NEW(Integer)
     5207        cdef Integer x = PY_NEW(Integer)
    52115208        mpz_and(x.value, self.value, other.value)
    52125209        return x
    52135210
     
    52275224            return (<Integer>x)._and(y)
    52285225        return bin_op(x, y, operator.and_)
    52295226
    5230 
    52315227    cdef _or(Integer self, Integer other):
    5232         cdef Integer x
    5233         x = PY_NEW(Integer)
     5228        cdef Integer x = PY_NEW(Integer)
    52345229        mpz_ior(x.value, self.value, other.value)
    52355230        return x
    52365231
     
    52485243            return (<Integer>x)._or(y)
    52495244        return bin_op(x, y, operator.or_)
    52505245
    5251 
    52525246    def __invert__(self):
    52535247        """
    52545248        Return the multiplicative inverse of self, as a rational number.
     
    52615255            sage: n.__invert__()
    52625256            1/10
    52635257        """
    5264         return one/self    # TODO: optimize
     5258        return one / self
    52655259       
    52665260    def inverse_of_unit(self):
    52675261        """
     
    52835277            ...
    52845278            ZeroDivisionError: Inverse does not exist.
    52855279        """
    5286         if mpz_cmp_si(self.value, 1) == 0 or mpz_cmp_si(self.value, -1) == 0:
     5280        if mpz_cmpabs_ui(self.value, 1) == 0:
    52875281            return self
    52885282        else:
    52895283            raise ZeroDivisionError, "Inverse does not exist."
    52905284
    52915285    def inverse_mod(self, n):
    52925286        """
    5293         Returns the inverse of self modulo `n`, if this inverse
    5294         exists. Otherwise, raises a ``ZeroDivisionError``
    5295         exception.
     5287        Returns the inverse of self modulo `n`, if this inverse exists.
     5288        Otherwise, raises a ``ZeroDivisionError`` exception.
    52965289       
    52975290        INPUT:
    52985291       
    5299        
    53005292        -  ``self`` - Integer
    53015293       
    53025294        -  ``n`` - Integer, or ideal of integer ring
    53035295       
    5304        
    53055296        OUTPUT:
    53065297       
    53075298        -  ``x`` - Integer such that x\*self = 1 (mod m), or
     
    53745365            left, right = canonical_coercion(self, n)
    53755366            return left.gcd(right)
    53765367        cdef Integer m = as_Integer(n)
    5377         cdef Integer g = <Integer>PY_NEW(Integer)
     5368        cdef Integer g = PY_NEW(Integer)
    53785369        sig_on()
    53795370        mpz_gcd(g.value, self.value, m.value)
    53805371        sig_off()
     
    53825373
    53835374    def crt(self, y, m, n):
    53845375        """
    5385         Return the unique integer between `0` and `mn` that
    5386         is congruent to the integer modulo `m` and to `y`
    5387         modulo `n`. We assume that `m` and `n` are
    5388         coprime.
     5376        Return the unique integer between `0` and `mn` that is congruent to
     5377        the integer modulo `m` and to `y` modulo `n`. We assume that `m` and
     5378        `n` are coprime.
    53895379       
    53905380        EXAMPLES::
    53915381       
     
    54045394        if not g.is_one():
    54055395            raise ArithmeticError, "CRT requires that gcd of moduli is 1."
    54065396        # Now s*m + t*n = 1, so the answer is x + (y-x)*s*m, where x=self.
    5407         return (self + (_y-self)*s*_m) % (_m*_n)
     5397        return (self + (_y - self) * s * _m) % (_m * _n)
    54085398
    54095399    def test_bit(self, long index):
    54105400        r"""
    54115401        Return the bit at ``index``.
    54125402       
     5403        If the index is negative, returns 0.
     5404       
     5405        Although internally a sign-magnitude representation is used
     5406        for integers, this method pretends to use a two's complement
     5407        representation.  This is illustrated with a negative integer
     5408        below.
     5409       
    54135410        EXAMPLES::
    54145411       
    54155412            sage: w = 6
     
    54195416            1
    54205417            sage: w.test_bit(-1)
    54215418            0
     5419            sage: x = -20
     5420            sage: x.str(2)
     5421            '-10100'
     5422            sage: x.test_bit(4)
     5423            0
     5424            sage: x.test_bit(5)
     5425            1
     5426            sage: x.test_bit(6)
     5427            1
    54225428        """
    54235429        if index < 0:
    54245430            return 0
     
    55115517   
    55125518    INPUT:
    55135519   
    5514    
    55155520    -  ``v`` - list or tuple
    55165521   
    5517    
    55185522    OUTPUT: integer
    55195523   
    55205524    EXAMPLES::
     
    55565560       
    55575561    return z
    55585562
    5559 
    5560 
    55615563def GCD_list(v):
    55625564    r"""
    55635565    Return the GCD of a list v of integers. Elements of v are converted
     
    55675569   
    55685570    INPUT:
    55695571   
    5570    
    55715572    -  ``v`` - list or tuple
    55725573   
    5573    
    55745574    OUTPUT: integer
    55755575   
    55765576    EXAMPLES::
     
    56345634        ...
    56355635        TypeError: expected string or Unicode object, sage.rings.integer.Integer found
    56365636    """
    5637     cdef Integer r
    5638     r = PY_NEW(Integer)
     5637    cdef Integer r = PY_NEW(Integer)
    56395638    r._reduce_set(s)
    56405639    return r
    56415640   
     
    56795678    def _repr_type(self):
    56805679        return "Native"
    56815680
    5682 
    56835681############### INTEGER CREATION CODE #####################
    56845682
    56855683# We need a couple of internal GMP datatypes.
     
    59445942    integer_pool_size = 0
    59455943    integer_pool_count = 0
    59465944    sage_free(integer_pool)
     5945
  • sage/rings/integer_ring.pyx

    diff --git a/sage/rings/integer_ring.pyx b/sage/rings/integer_ring.pyx
    a b  
    280280        raise TypeError, 'len() of unsized object'
    281281
    282282    def _div(self, integer.Integer left, integer.Integer right):
    283         cdef rational.Rational x
    284         x = PY_NEW(rational.Rational)
    285         if mpz_cmp_si(right.value, 0) == 0:
     283        cdef rational.Rational x = PY_NEW(rational.Rational)
     284        if mpz_sgn(right.value) == 0:
    286285            raise ZeroDivisionError, 'Rational division by zero'
    287         mpq_set_num(x.value, left.value)
    288         mpq_set_den(x.value, right.value)
     286        mpz_set(mpq_numref(x.value), left.value)
     287        mpz_set(mpq_denref(x.value), right.value)
    289288        mpq_canonicalize(x.value)
    290289        return x
    291290