Ticket #10596: trac-10596-461rc0.patch

File trac-10596-461rc0.patch, 42.9 KB (added by spancratz, 10 years ago)

Version for 4.6.1.rc0

  • sage/rings/arith.py

    diff -r 777e70039438 sage/rings/arith.py
    a b  
    23782378        sage: odd_part(factorial(31))
    23792379        122529844256906551386796875
    23802380    """
    2381     n = ZZ(n)
    2382     return n._shift_helper(n.valuation(2), -1)
     2381    if not isinstance(n, integer.Integer):
     2382        n = ZZ(n)
     2383    return n.odd_part()
    23832384
    23842385def prime_to_m_part(n,m):
    23852386    """
  • sage/rings/integer.pyx

    diff -r 777e70039438 sage/rings/integer.pyx
    a b  
    9393    sage: 'sage'*Integer(3)
    9494    'sagesagesage'
    9595
    96 COERCIONS: Returns version of this integer in the multi-precision
    97 floating real field R.
    98 
    99 ::
     96COERCIONS:
     97
     98Returns version of this integer in the multi-precision floating
     99real field R::
    100100
    101101    sage: n = 9390823
    102102    sage: RR = RealField(200)
    103103    sage: RR(n)
    104104    9.3908230000000000000000000000000000000000000000000000000000e6
    105105
    106 
    107106"""
    108107#*****************************************************************************
    109108#       Copyright (C) 2004,2006 William Stein <wstein@gmail.com>
     
    288287    cdef Integer temp
    289288    cdef int v_int
    290289    if power_index < 5:
    291         # It turns out that simple repeated division is very fast for relatively few digits.
    292         # I don't think this is a real algorithmic statement, it's an annoyance introduced by memory allocation.
    293         # I think that manual memory management with mpn_* would make the divide & conquer approach even faster, but the code would be much more complicated.
     290        # It turns out that simple repeated division is very fast for
     291        # relatively few digits.  I don't think this is a real algorithmic
     292        # statement, it's an annoyance introduced by memory allocation.
     293        # I think that manual memory management with mpn_* would make the
     294        # divide & conquer approach even faster, but the code would be much
     295        # more complicated.
    294296        _digits_naive(v,l,offset,power_list[0],digits)
    295297    else:
    296298        mpz_init(mpz_quot)
     
    435437        The class ``Integer`` is implemented in Cython, as a
    436438        wrapper of the GMP ``mpz_t`` integer type.
    437439   
    438    
    439440    EXAMPLES::
    440441   
    441442        sage: Integer(010)
     
    567568            sage: ZZ(MyFloat(5))
    568569            5
    569570        """
    570 
    571571        # TODO: All the code below should somehow be in an external
    572572        # cdef'd function.  Then e.g., if a matrix or vector or
    573573        # polynomial is getting filled by mpz_t's, it can use the
     
    761761        if PY_TYPE_CHECK(x, Integer) and PY_TYPE_CHECK(y, Integer):       
    762762            return (<Integer>x)._xor(y)
    763763        return bin_op(x, y, operator.xor)
    764        
    765        
     764
    766765    def __richcmp__(left, right, int op):
    767766        """
    768767        cmp for integers
     
    815814        set_mpz(z,self.value)
    816815        return z
    817816
    818 
    819817    def list(self):
    820818        """
    821819        Return a list with this integer in it, to be compatible with the
     
    829827        """
    830828        return [ self ]
    831829
    832 
    833830    def  __dealloc__(self):
    834831        mpz_clear(self.value)
    835832
     
    916913        ::
    917914       
    918915            sage: big = 10^5000000
    919             sage: s = big.str()                 # long time (> 20 seconds)
    920             sage: len(s)                        # long time (depends on above defn of s)
     916            sage: s = big.str()       # long time (> 20 seconds)
     917            sage: len(s)              # long time (depends on above defn of s)
    921918            5000001
    922             sage: s[:10]                        # long time (depends on above defn of s)
     919            sage: s[:10]              # long time (depends on above defn of s)
    923920            '1000000000'
    924921        """
    925922        if base < 2 or base > 36:
     
    11271124       
    11281125        INPUT:
    11291126       
    1130        
    11311127        -  ``base`` - integer (default: 10)
    11321128       
    11331129        -  ``digits`` - optional indexable object as source for
     
    12741270                z = the_integer_ring._zero_element
    12751271            l = [z]*(s if s >= padto else padto)
    12761272            for i from 0<= i < s:
    1277                 if mpz_tstbit(self_abs.value,i):  # mpz_tstbit seems to return 0 for the high-order bit of negative numbers?!
     1273                # mpz_tstbit seems to return 0 for the high-order bit of
     1274                # negative numbers?!
     1275                if mpz_tstbit(self_abs.value,i):
    12781276                    l[i] = o
    12791277        else:
    12801278            s = mpz_sizeinbase(self.value, 2)
    12811279            if s > 256:
    12821280                sig_on()
    12831281
    1284             #   We use a divide and conquer approach (suggested
    1285             # by the prior author, malb?, of the digits method)
    1286             # here: for base b, compute b^2, b^4, b^8,
    1287             # ... (repeated squaring) until you get larger
    1288             # than your number; then compute (n // b^256,
    1289             # n % b ^ 256) (if b^512 > number) to split
    1290             # the number in half and recurse
    1291 
    1292             #   Pre-computing the exact number of digits up-front is actually faster (especially for large
    1293             # values of self) than trimming off trailing zeros after the fact.  It also seems that it would
     1282            # We use a divide and conquer approach (suggested by the prior
     1283            # author, malb?, of the digits method) here: for base b, compute
     1284            # b^2, b^4, b^8, ... (repeated squaring) until you get larger
     1285            # than your number; then compute (n // b^256, n % b^256)
     1286            # (if b^512 > number) to split the number in half and recurse
     1287
     1288            # Pre-computing the exact number of digits up-front is actually
     1289            # faster (especially for large values of self) than trimming off
     1290            # trailing zeros after the fact.  It also seems that it would
    12941291            # avoid duplicating the list in memory with a list-slice.
    12951292            z = the_integer_ring._zero_element if digits is None else digits[0]
    12961293            s = self_abs.exact_log(_base)
    12971294            l = [z]*(s+1 if s+1 >= padto else padto)
    12981295
    1299             # set up digits for optimal access once we get inside the worker functions
     1296            # set up digits for optimal access once we get inside the worker
     1297            # functions
    13001298            if not digits is None:
    13011299                # list objects have fastest access in the innermost loop
    13021300                if not PyList_CheckExact(digits):
    13031301                    digits = [digits[i] for i in range(_base)]
    13041302            elif mpz_cmp_ui(_base.value,s) < 0 and mpz_cmp_ui(_base.value,10000):
    1305                 # We can get a speed boost by pre-allocating digit values in big cases
    1306                 # We do this we have more digits than the base and the base is not too
    1307                 # extremely large (currently, "extremely" means larger than 10000 --
    1308                 # that's very arbitrary.)
     1303                # We can get a speed boost by pre-allocating digit values in
     1304                # big cases.
     1305                # We do this we have more digits than the base and the base
     1306                # is not too extremely large (currently, "extremely" means
     1307                # larger than 10000 -- that's very arbitrary.)
    13091308                if mpz_sgn(self.value) > 0:
    13101309                    digits = [Integer(i) for i in range(_base)]
    13111310                else:
     
    13271326                for power_index from 1 <= power_index < i:
    13281327                    power_list[power_index] = power_list[power_index-1]**2
    13291328
    1330                 #   Note that it may appear that the recursive calls to _digit_internal would be assigning
    1331                 # list elements i in l for anywhere from 0<=i<(1<<power_index).  However, this is not
    1332                 # the case due to the optimization of skipping assigns assigning zero.
     1329                # Note that it may appear that the recursive calls to
     1330                # _digit_internal would be assigning list elements i in l for
     1331                # anywhere from 0<=i<(1<<power_index).  However, this is not
     1332                # the case due to the optimization of skipping assigns
     1333                # assigning zero.
    13331334                _digits_internal(self.value,l,0,i-1,power_list,digits)
    13341335
    13351336            if s > 256:
     
    13451346       
    13461347        INPUT:
    13471348       
    1348        
    13491349        -  ``base`` - integer (default: 10)
    13501350       
    1351        
    13521351        EXAMPLES::
    13531352       
    13541353            sage: n = 52
     
    13601359            sage: n = 15
    13611360            sage: n.ndigits(2)
    13621361            4
    1363             sage: n=1000**1000000+1
     1362            sage: n = 1000**1000000+1
    13641363            sage: n.ndigits()
    13651364            3000001
    1366             sage: n=1000**1000000-1
     1365            sage: n = 1000**1000000-1
    13671366            sage: n.ndigits()
    13681367            3000000
    1369             sage: n=10**10000000-10**9999990
     1368            sage: n = 10**10000000-10**9999990
    13701369            sage: n.ndigits()
    13711370            10000000
    13721371        """
    13731372        cdef Integer temp
    1374         if mpz_cmp_si(self.value,0) == 0:
     1373        cdef unsigned long b
     1374
     1375        if mpz_sgn(self.value) == 0:
    13751376            temp = PY_NEW(Integer)
    1376             mpz_set_ui(temp.value,0)
     1377            mpz_set_ui(temp.value, 1)
    13771378            return temp
    1378         elif mpz_cmp_si(self.value,0) > 0:
    1379             temp=self.exact_log(base)
    1380             mpz_add_ui(temp.value,temp.value,1)
     1379
     1380        if mpz_sgn(self.value) > 0:
     1381            temp = self.exact_log(base)
     1382            mpz_add_ui(temp.value, temp.value, 1)
    13811383            return temp
    13821384        else:
    13831385            return self.abs().exact_log(base) + 1
     
    15851587            sage: Integer(32) / Integer(32)
    15861588            1
    15871589        """
    1588         # this is vastly faster than doing it here, since here
     1590        # This is vastly faster than doing it here, since here
    15891591        # we can't cimport rationals.
    15901592        return the_integer_ring._div(self, right)
    15911593
     
    16551657        else:
    16561658            return bin_op(x, y, operator.floordiv)
    16571659
    1658 
    16591660    def __pow__(self, n, modulus):
    16601661        r"""
    16611662        Computes `\text{self}^n`
     
    17421743            from sage.rings.finite_rings.integer_mod import Mod
    17431744            return Mod(self, modulus) ** n
    17441745       
    1745        
    17461746        if not PY_TYPE_CHECK(self, Integer):
    17471747            if isinstance(self, str):
    17481748                return self * n
     
    17811781        else:
    17821782            return x
    17831783
    1784 
    17851784    def nth_root(self, int n, bint truncate_mode=0):
    17861785        r"""
    17871786        Returns the (possibly truncated) n'th root of self.
    17881787       
    17891788        INPUT:
    17901789       
    1791        
    17921790        -  ``n`` - integer >= 1 (must fit in C int type).
    17931791       
    17941792        -  ``truncate_mode`` - boolean, whether to allow truncation if
    17951793           self is not an n'th power.
    17961794       
    1797        
    1798         OUTPUT: If truncate_mode is 0 (default), then returns the
    1799         exact n'th root if self is an n'th power, or raises a
    1800         ValueError if it is not.
     1795        OUTPUT:
     1796
     1797        If truncate_mode is 0 (default), then returns the exact n'th root
     1798        if self is an n'th power, or raises a ValueError if it is not.
    18011799       
    18021800        If truncate_mode is 1, then if either n is odd or self is
    18031801        positive, returns a pair (root, exact_flag) where root is the
     
    19001898
    19011899    cpdef size_t _exact_log_log2_iter(self,Integer m):
    19021900        """
    1903         This is only for internal use only.  You should expect it to crash and burn for
    1904         negative or other malformed input.  In particular, if the base `2\leq m<4` the log2
    1905         approximation of m is 1 and certain input causes endless loops.  Along these lines,
    1906         it is clear that this function is most useful for m with a relatively large number
     1901        This is only for internal use only.  You should expect it to crash
     1902        and burn for negative or other malformed input.  In particular, if
     1903        the base `2 \leq m < 4` the log2 approximation of m is 1 and certain
     1904        input causes endless loops.  Along these lines, it is clear that
     1905        this function is most useful for m with a relatively large number
    19071906        of bits.
    19081907
    1909         For ``small`` values (which I'll leave quite ambiguous), this function is a fast
    1910         path for exact log computations.  Any integer division with such input tends to
    1911         dominate the runtime.  Thus we avoid division entirely in this function.
     1908        For ``small`` values (which I'll leave quite ambiguous), this function
     1909        is a fast path for exact log computations.  Any integer division with
     1910        such input tends to dominate the runtime.  Thus we avoid division
     1911        entirely in this function.
    19121912
    19131913        AUTHOR::
    19141914
     
    19301930        cdef mpz_t accum
    19311931        cdef mpz_t temp_exp
    19321932
    1933         if mpz_cmp_si(m.value,4)<0:
     1933        if mpz_cmp_si(m.value,4) < 0:
    19341934            raise ValueError, "This is undefined or possibly non-convergent with this algorithm."
    19351935
    19361936        n_log2=mpz_sizeinbase(self.value,2)-1
     
    19441944            mpz_set_ui(accum,1)
    19451945            l = 0
    19461946            while l_min != l_max:
    1947                 #print "self=...",m,l_min,l_max
     1947                # print "self=...",m,l_min,l_max
    19481948                if l_min + 1 == l_max:
    19491949                    mpz_pow_ui(temp_exp,m.value,l_min+1-l)
    1950                     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.
     1950                    # This might over-shoot and make accum > self, but
     1951                    # we'll know that it's only over by a factor of m^1.
     1952                    mpz_mul(accum,accum,temp_exp)
    19511953                    if mpz_cmp(self.value,accum) >= 0:
    19521954                        l_min += 1
    19531955                    break
     
    19551957                mpz_mul(accum,accum,temp_exp)
    19561958                l = l_min
    19571959
    1958                 #Let x=n_log2-(mpz_sizeinbase(accum,2)-1) and y=m_log2.  Now, with x>0 and y>0, we have the
    1959                 #following observation.  If floor((x-1)/(y+1))=0, then x-1<y+1 which implies that x/y<1+2/y. 
    1960                 #So long as y>=2, this means that floor(x/y)<=1.  This shows that this iteration is forced to
    1961                 #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
    1962                 #which results in non-convergence.
    1963 
    1964                 # We need the additional '-1' in the l_min computation because mpz_sizeinbase(accum,2)-1 is smaller than the true log_2(accum)
     1960                # Let x=n_log2-(mpz_sizeinbase(accum,2)-1) and y=m_log2. 
     1961                # Now, with x>0 and y>0, we have the following observation. 
     1962                # If floor((x-1)/(y+1))=0, then x-1<y+1 which implies that
     1963                # x/y<1+2/y. 
     1964                # So long as y>=2, this means that floor(x/y)<=1.  This shows
     1965                # that this iteration is forced to converge for input m >= 4. 
     1966                # If m=3, we can find input so that floor((x-1)/(y+1))=0 and
     1967                # floor(x/y)=2 which results in non-convergence.
     1968
     1969                # We need the additional '-1' in the l_min computation
     1970                # because mpz_sizeinbase(accum,2)-1 is smaller than the
     1971                # true log_2(accum)
    19651972                l_min=l+(n_log2-(mpz_sizeinbase(accum,2)-1)-1)/(m_log2+1)
    19661973                l_max=l+(n_log2-(mpz_sizeinbase(accum,2)-1))/m_log2
    19671974            mpz_clear(temp_exp)
     
    19711978
    19721979    cpdef size_t _exact_log_mpfi_log(self,m):
    19731980        """
    1974         This is only for internal use only.  You should expect it to crash and burn for
    1975         negative or other malformed input.
    1976 
    1977         I avoid using this function until the input is large.  The overhead associated
    1978         with computing the floating point log entirely dominates the runtime for small values.
    1979         Note that this is most definitely not an artifact of format conversion.  Tricks
    1980         with log2 approximations and using exact integer arithmetic are much better for
    1981         small input.
     1981        This is only for internal use only.  You should expect it to crash
     1982        and burn for negative or other malformed input.
     1983
     1984        I avoid using this function until the input is large.  The overhead
     1985        associated with computing the floating point log entirely dominates
     1986        the runtime for small values.  Note that this is most definitely not
     1987        an artifact of format conversion.  Tricks with log2 approximations
     1988        and using exact integer arithmetic are much better for small input.
    19821989
    19831990        AUTHOR::
    19841991
     
    20122019            # I'm not sure what to do now
    20132020            upper = 0
    20142021        lower = rif_log.lower().floor()
    2015         # since the log function is monotonic increasing, lower and upper bracket our desired answer
     2022        # since the log function is monotonic increasing, lower
     2023        # and upper bracket our desired answer
    20162024
    20172025        # if upper - lower == 1: "we are done"
    20182026        if upper - lower == 2:
    2019             # 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
    2020             # We must test with exact integer arithmetic which takes all the bits of self into account.
     2027            # You could test it by checking rif_m**(lower+1), but I think
     2028            # that's a waste of time since it won't be conclusive.
     2029            # We must test with exact integer arithmetic which takes all
     2030            # the bits of self into account.
    20212031            if self >= m**(lower+1):
    20222032                return lower + 1
    20232033            else:
     
    20612071
    20622072    def exact_log(self, m):
    20632073        r"""
    2064         Returns the largest integer `k` such that
    2065         `m^k \leq \text{self}`, i.e., the floor of
    2066         `\log_m(\text{self})`.
    2067        
     2074        Returns the largest integer `k` such that `m^k \leq \text{self}`,
     2075        i.e., the floor of `\log_m(\text{self})`.
     2076
    20682077        This is guaranteed to return the correct answer even when the usual
    20692078        log function doesn't have sufficient precision.
    20702079       
    20712080        INPUT:
    20722081       
    2073        
    20742082        -  ``m`` - integer >= 2
    20752083       
    2076        
    20772084        AUTHORS:
    20782085
    20792086        - David Harvey (2006-09-15)
     
    21412148        cdef size_t n_log2
    21422149        cdef size_t m_log2
    21432150        cdef size_t guess # this will contain the final answer
    2144         cdef bint guess_filled = 0  # this variable is only used in one branch below.
     2151        cdef bint guess_filled = 0  # this variable is only used in one branch below
    21452152        cdef mpz_t z
    21462153        if PY_TYPE_CHECK(m,Integer):
    21472154            _m=<Integer>m
     
    21562163        n_log2=mpz_sizeinbase(self.value,2)-1
    21572164        m_log2=mpz_sizeinbase(_m.value,2)-1
    21582165        if mpz_divisible_2exp_p(_m.value,m_log2):
    2159             # Here, m is a power of 2 and the correct answer is found by a log 2 approximation.
    2160             guess = n_log2/m_log2 # truncating division
     2166            # Here, m is a power of 2 and the correct answer is found
     2167            # by a log 2 approximation.
     2168            guess = n_log2/m_log2  # truncating division
    21612169        elif n_log2/(m_log2+1) == n_log2/m_log2:
    2162             # In this case, we have an upper bound and lower bound which give the same answer, thus, the correct answer.
     2170            # In this case, we have an upper bound and lower bound which
     2171            # give the same answer, thus, the correct answer.
    21632172            guess = n_log2/m_log2
    2164         elif m_log2 < 8: # i.e. m<256
     2173        elif m_log2 < 8:  # i.e. m<256
    21652174            # if the base m is at most 256, we can use mpz_sizeinbase
    21662175            # to get the following guess which is either the exact
    21672176            # log, or 1+ the exact log
     
    21842193                    guess =  guess - 1
    21852194            if not guess_filled:
    21862195                # At this point, either
    2187                 #  1)  self is close enough to a perfect power of m that we need an exact comparison, or
    2188                 #  2)  the numbers are small enough that converting to the interval field is more work than the exact comparison.
     2196                #  1)  self is close enough to a perfect power of m that we
     2197                #      need an exact comparison, or
     2198                #  2)  the numbers are small enough that converting to the
     2199                #      interval field is more work than the exact comparison.
    21892200                compare = _m**guess
    21902201                if self < compare:
    21912202                    guess = guess - 1
    21922203        elif n_log2 < 5000:
    2193             # for input with small exact log, it's very fast to work in exact integer arithmetic starting from log2 approximations
     2204            # for input with small exact log, it's very fast to work in exact
     2205            # integer arithmetic starting from log2 approximations
    21942206            guess = self._exact_log_log2_iter(_m)
    21952207        else:
    2196             # finally, we are out of easy cases
    2197             # this subroutine uses interval arithmetic to guess and check the exact log.
     2208            # finally, we are out of easy cases this subroutine uses interval
     2209            # arithmetic to guess and check the exact log.
    21982210            guess = self._exact_log_mpfi_log(_m)
    21992211
    2200         result = <Integer>PY_NEW(Integer)
     2212        result = PY_NEW(Integer)
    22012213        mpz_set_ui(result.value,guess)
    22022214        return result
    22032215
     
    22132225       
    22142226        INPUT:
    22152227       
    2216        
    22172228        -  ``m`` - default: natural log base e
    22182229       
    22192230        -  ``prec`` - integer (default: None): if None, returns
    22202231           symbolic, else to given bits of precision as in RealField
    22212232       
    2222        
    22232233        EXAMPLES::
    22242234       
    22252235            sage: Integer(124).log(5)
     
    23382348       
    23392349        INPUT:
    23402350       
    2341        
    23422351        -  ``m`` - Integer
    23432352       
    2344        
    23452353        OUTPUT: Integer
    23462354       
    23472355        EXAMPLES::
     
    24262434            raise ValueError, "n must be nonzero"
    24272435        f = self.factor()
    24282436
    2429         # All of the declarations below are for optimizing the word-sized case.
    2430         # Operations are performed in c as far as possible without overflow before
    2431         # moving to python objects.
     2437        # All of the declarations below are for optimizing the word-sized
     2438        # case.  Operations are performed in c as far as possible without
     2439        # overflow before moving to python objects.
    24322440        cdef long long p_c, pn_c, apn_c
    24332441        cdef long all_len, sorted_len, prev_len
    24342442        cdef long long* ptr
     
    24692477                sage_free(ptr)
    24702478                fits_c = False
    24712479
    2472             # The two cases below are essentially the same algorithm, one operating
    2473             # on Integers in Python lists, the other on long longs.
     2480            # The two cases below are essentially the same algorithm, one
     2481            # operating on Integers in Python lists, the other on long longs.
    24742482            if fits_c:
    24752483               
    24762484                pn_c = p_c = p
     
    25682576            sage: abs(z) == abs(1)
    25692577            True
    25702578        """
    2571         cdef Integer x
    2572         x = PY_NEW(Integer)
     2579        cdef Integer x = PY_NEW(Integer)
    25732580        mpz_abs(x.value, self.value)
    25742581        return x
    25752582
     
    26112618            sage: a % b
    26122619            59
    26132620         """
    2614         cdef Integer z = <Integer>PY_NEW(Integer)
     2621        cdef Integer z = PY_NEW(Integer)
    26152622        cdef long yy, res
    26162623
    26172624        # first case: Integer % Integer
     
    26512658            except ValueError:
    26522659                return bin_op(x, y, operator.mod)
    26532660
    2654 
    26552661    def quo_rem(Integer self, other):
    26562662        """
    26572663        Returns the quotient and the remainder of self divided by other.
     
    26602666       
    26612667        INPUT:
    26622668       
    2663        
    26642669        -  ``other`` - the integer the divisor
    26652670       
    2666        
    26672671        OUTPUT:
    26682672       
    26692673       
     
    26712675       
    26722676        -  ``r`` - the remainder of self/other
    26732677       
    2674        
    26752678        EXAMPLES::
    26762679       
    26772680            sage: z = Integer(231)
     
    32753278            return sage.rings.infinity.infinity
    32763279        if mpz_cmp_ui(p.value, 2) < 0:
    32773280            raise ValueError, "You can only compute the valuation with respect to a integer larger than 1."
    3278         cdef Integer v
    3279         v = PY_NEW(Integer)
     3281
     3282        cdef Integer v = PY_NEW(Integer)
    32803283        cdef mpz_t u
    32813284        mpz_init(u)
    32823285        sig_on()
     
    33173320       
    33183321        INPUT:
    33193322       
    3320        
    33213323        -  ``p`` - an integer at least 2.
    33223324       
    3323        
    33243325        EXAMPLE::
    33253326       
    33263327            sage: n = 60
     
    33423343        """
    33433344        return self._valuation(Integer(p))
    33443345
     3346    # Alias for valuation
     3347    ord = valuation
     3348
    33453349    def val_unit(self, p):
    33463350        r"""
    33473351        Returns a pair: the p-adic valuation of self, and the p-adic unit
     
    33493353       
    33503354        INPUT:
    33513355       
    3352        
    33533356        -  ``p`` - an integer at least 2.
    33543357       
    3355        
    3356         OUTPUT:
    3357        
    3358        
    3359         -  ``v_p(self)`` - the p-adic valuation of
    3360            ``self``
    3361        
    3362         -  ``u_p(self)`` - ``self`` /
    3363            `p^{v_p(\mathrm{self})}`
    3364        
     3358        OUTPUT:
     3359       
     3360        -  ``v_p(self)`` - the p-adic valuation of ``self``
     3361       
     3362        -  ``u_p(self)`` - ``self`` / `p^{v_p(\mathrm{self})}`
    33653363       
    33663364        EXAMPLE::
    33673365       
     
    33793377        """
    33803378        return self._val_unit(Integer(p))
    33813379
    3382     def ord(self, p=None):
    3383         """
    3384         Synonym for valuation
    3385        
    3386         EXAMPLES::
    3387        
    3388             sage: n=12
    3389             sage: n.ord(3)
    3390             1
    3391         """
    3392         return self.valuation(p)
     3380    def odd_part(self):
     3381        r"""
     3382        The odd part of the integer `n`. This is `n / 2^v`,
     3383        where `v = \mathrm{valuation}(n,2)`.
     3384
     3385        IMPLEMENTATION:
     3386
     3387        Currently returns 0 when self is 0.  This behaviour is fairly arbitrary,
     3388        and in Sage 4.6 this special case was not handled at all, eventually
     3389        propagating a TypeError.  The caller should not rely on the behaviour
     3390        in case self is 0.
     3391
     3392        EXAMPLES::
     3393       
     3394            sage: odd_part(5)
     3395            5
     3396            sage: odd_part(4)
     3397            1
     3398            sage: odd_part(factorial(31))
     3399            122529844256906551386796875
     3400        """
     3401        cdef Integer odd
     3402        cdef unsigned long bits
     3403
     3404        if mpz_cmpabs_ui(self.value, 1) <= 0:
     3405            return self
     3406
     3407        odd  = PY_NEW(Integer)
     3408        bits = mpz_scan1(self.value, 0)
     3409        mpz_tdiv_q_2exp(odd.value, self.value, bits)
     3410        return odd
    33933411
    33943412    cdef Integer _divide_knowing_divisible_by(Integer self, Integer right):
    33953413        r"""
     
    34573475            sage: n._lcm(150)
    34583476            300
    34593477        """
    3460         cdef Integer z
    3461         z = PY_NEW(Integer)
     3478        cdef Integer z = PY_NEW(Integer)
    34623479        sig_on()
    34633480        mpz_lcm(z.value, self.value, n.value)
    34643481        sig_off()
     
    34833500        """
    34843501        Return the numerator of this integer.
    34853502       
    3486         EXAMPLE::
     3503        EXAMPLES::
    34873504       
    34883505            sage: x = 5
    34893506            sage: x.numerator()
     
    35823599                sign = ONE
    35833600            return sign / Integer(-k-n).multifactorial(k)
    35843601               
    3585         # compute the actual product, optimizing the number of large multiplications
     3602        # compute the actual product, optimizing the number of large
     3603        # multiplications
    35863604        cdef int i,j
    35873605       
    35883606        # we need (at most) log_2(#factors) concurrent sub-products
     
    36213639        free(sub_prods)
    36223640
    36233641        return z
    3624 
    36253642       
    36263643    def gamma(self):
    36273644        r"""
    3628         The gamma function on integers is the factorial function (shifted
    3629         by one) on positive integers, and `\pm \infty` on
    3630         non-positive integers.
     3645        The gamma function on integers is the factorial function (shifted by
     3646        one) on positive integers, and `\pm \infty` on non-positive integers.
    36313647       
    36323648        EXAMPLES::
    36333649       
     
    36963712       
    36973713    def is_one(self):
    36983714        r"""
    3699         Returns ``True`` if the integer is `1`,
    3700         otherwise ``False``.
     3715        Returns ``True`` if the integer is `1`, otherwise ``False``.
    37013716       
    37023717        EXAMPLES::
    37033718       
     
    37103725
    37113726    def __nonzero__(self):
    37123727        r"""
    3713         Returns ``True`` if the integer is not `0`,
    3714         otherwise ``False``.
     3728        Returns ``True`` if the integer is not `0`, otherwise ``False``.
    37153729       
    37163730        EXAMPLES::
    37173731       
     
    37363750
    37373751    def is_unit(self):
    37383752        r"""
    3739         Returns ``true`` if this integer is a unit, i.e., 1 or
    3740         `-1`.
     3753        Returns ``true`` if this integer is a unit, i.e., 1 or `-1`.
    37413754       
    37423755        EXAMPLES::
    37433756       
     
    37493762            1 True
    37503763            2 False
    37513764        """
    3752         return mpz_cmp_si(self.value, -1) == 0 or mpz_cmp_si(self.value, 1) == 0
     3765        return mpz_cmpabs_ui(self.value, 1) == 0
    37533766
    37543767    def is_square(self):
    37553768        r"""
    3756         Returns ``True`` if self is a perfect square
     3769        Returns ``True`` if self is a perfect square.
    37573770       
    37583771        EXAMPLES::
    37593772       
     
    37663779
    37673780    def is_power(self):
    37683781        r"""
    3769         Returns ``True`` if self is a perfect power, ie if
    3770         there exist integers a and b, `b > 1` with
    3771         `self = a^b`.
     3782        Returns ``True`` if self is a perfect power, i.e. if there exist
     3783        integers `a` and `b`, `b > 1` with `self = a^b`.
    37723784       
    37733785        EXAMPLES::
    37743786       
     
    37813793
    37823794    cdef bint _is_power_of(Integer self, Integer n):
    37833795        r"""
    3784         Returns a non-zero int if there is an integer b with
     3796        Returns a non-zero int if there is an integer b with 
    37853797        `\mathtt{self} = n^b`.
    37863798       
    3787         For more documentation see ``is_power_of``
     3799        For more documentation see ``is_power_of``.
    37883800       
    37893801        AUTHORS:
    37903802
     
    40284040            return True
    40294041        if not self.is_perfect_power():
    40304042            return False
    4031         return len(self.factor()) == 1  # this is potentially very slow, but at least it is right!!
     4043
     4044        # This is potentially very slow, but at least it is right!!
     4045        return len(self.factor()) == 1
     4046
    40324047        # PARI has a major bug -- see trac #4777. It gives wrong answer on
    40334048        # input of "150607571^14".
    40344049        #k, g = self._pari_().ispower()
     
    40924107            sage: z.is_irreducible()
    40934108            True
    40944109        """
    4095         n = self if self>=0 else -self
     4110        n = self if self >= 0 else -self
    40964111        return bool(n._pari_().isprime())
    40974112
    40984113    def is_pseudoprime(self):
     
    41284143            sage: (-4).is_perfect_power()
    41294144            False
    41304145
    4131         This is a test to make sure we workaround a bug in GMP. (See
    4132         trac \#4612.)
     4146        This is a test to make sure we work around a bug in GMP,
     4147        see trac \#4612.
    41334148
    41344149        ::
    41354150
     
    41384153        """
    41394154        cdef mpz_t tmp
    41404155        cdef int res
    4141         if mpz_sgn(self.value) == -1:
     4156        if mpz_sgn(self.value) < 0:
    41424157            if mpz_cmp_si(self.value, -1) == 0:
    41434158                return True
    41444159            mpz_init(tmp)
    4145             mpz_mul_si(tmp, self.value, -1)
     4160            mpz_neg(tmp, self.value)
    41464161            while mpz_perfect_square_p(tmp):
    41474162                mpz_sqrt(tmp, tmp)
    41484163            res = mpz_perfect_power_p(tmp)
     
    41924207       
    41934208    def kronecker(self, b):
    41944209        r"""
    4195         Calculate the Kronecker symbol
    4196         `\left(\frac{self}{b}\right)` with the Kronecker extension
    4197         `(self/2)=(2/self)` when self odd, or `(self/2)=0`
    4198         when `self` even.
     4210        Calculate the Kronecker symbol `\left(\frac{self}{b}\right)`
     4211        with the Kronecker extension `(self/2)=(2/self)` when `self` is odd,
     4212        or `(self/2)=0` when `self` is even.
    41994213       
    42004214        EXAMPLES::
    42014215       
     
    42474261       
    42484262    def squarefree_part(self, long bound=-1):
    42494263        r"""
    4250         Return the square free part of `x` (=self), i.e., the
    4251         unique integer `z` that `x = z y^2`, with
    4252         `y^2` a perfect square and `z` square-free.
    4253        
    4254         Use ``self.radical()`` for the product of the primes
    4255         that divide self.
     4264        Return the square free part of `x` (=self), i.e., the unique integer
     4265        `z` that `x = z y^2`, with `y^2` a perfect square and `z` square-free.
     4266       
     4267        Use ``self.radical()`` for the product of the primes that divide self.
    42564268       
    42574269        If self is 0, just returns 0.
    42584270       
     
    42914303        cdef Integer z
    42924304        cdef long even_part, p, p2
    42934305        cdef char switch_p
    4294         if mpz_cmp_ui(self.value, 0) == 0:
     4306        if mpz_sgn(self.value) == 0:
    42954307            return self
    42964308        if 0 <= bound < 2:
    42974309            return self
    42984310        elif 2 <= bound <= 10000:
    4299             z = <Integer>PY_NEW(Integer)
     4311            z = PY_NEW(Integer)
    43004312            even_part = mpz_scan1(self.value, 0)
    43014313            mpz_fdiv_q_2exp(z.value, self.value, even_part ^ (even_part&1))
    43024314            sig_on()
     
    43524364       
    43534365        INPUT:
    43544366       
    4355        
    43564367        -  ``proof`` - bool or None (default: None, see
    43574368           proof.arithmetic or sage.structure.proof) Note that the global Sage
    43584369           default is proof=True
    43594370       
    4360        
    43614371        EXAMPLES::
    43624372       
    43634373            sage: Integer(100).next_prime()
     
    43904400            n += 2
    43914401        return integer_ring.ZZ(n)
    43924402   
    4393 
    43944403    def additive_order(self):
    43954404        """
    43964405        Return the additive order of self.
     
    45194528        """
    45204529        Return string that evaluates in Magma to this element.
    45214530
    4522         For small integers we just use base 10.  For large integers we use base 16,
    4523         but use Magma's StringToInteger command, which (for no good reason)
    4524         is much faster than 0x[string literal].  We only use base 16 for integers
    4525         with at least 10000 binary digits, since e.g., for a large list of
    4526         small integers the overhead of calling StringToInteger can be a killer.
     4531        For small integers we just use base 10.  For large integers we use
     4532        base 16, but use Magma's StringToInteger command, which (for no
     4533        good reason) is much faster than 0x[string literal].  We only use
     4534        base 16 for integers with at least 10000 binary digits, since e.g.,
     4535        for a large list of small integers the overhead of calling
     4536        StringToInteger can be a killer.
    45274537
    45284538        EXAMPLES:
    45294539            sage: (117)._magma_init_(magma)           # optional - magma
     
    46334643        """
    46344644        if mpz_sgn(self.value) < 0:
    46354645            raise ValueError, "square root of negative integer not defined."
    4636         cdef Integer x
    4637         x = PY_NEW(Integer)
     4646
     4647        cdef Integer x = PY_NEW(Integer)
    46384648
    46394649        sig_on()
    46404650        mpz_sqrt(x.value, self.value)
     
    46704680       
    46714681        INPUT:
    46724682       
    4673        
    46744683        -  ``prec`` - integer (default: None): if None, returns
    46754684           an exact square root; otherwise returns a numerical square root if
    46764685           necessary, to the given bits of precision.
     
    46834692        -  ``all`` - bool (default: False); if True, return all
    46844693           square roots of self, instead of just one.
    46854694       
    4686        
    46874695        EXAMPLES::
    46884696       
    46894697            sage: Integer(144).sqrt()
     
    47584766       
    47594767        INPUT:
    47604768       
    4761        
    47624769        -  ``self`` - integer
    47634770       
    47644771        -  ``n`` - integer
     
    47664773        -  ``minimal`` - boolean (default false), whether to
    47674774           compute minimal cofactors (see below)
    47684775       
    4769        
    4770         OUTPUT: A triple (g, s, t), where `g` is the non-negative
    4771         gcd of self and `n`, and `s` and `t` are
    4772         cofactors satisfying the Bezout identity
     4776        OUTPUT:
     4777
     4778        A triple (g, s, t), where `g` is the non-negative gcd of self
     4779        and `n`, and `s` and `t` are cofactors satisfying the Bezout identity
    47734780       
    47744781        .. math::
    47754782       
    47764783             g = s \cdot \mbox{\rm self} + t \cdot n.
    47774784       
    4778        
    4779        
    4780         .. note::
    4781 
    4782            If minimal is False, then there is no guarantee that the
    4783            returned cofactors will be minimal in any sense; the only
    4784            guarantee is that the Bezout identity will be satisfied
    4785            (see examples below).
    4786        
    4787            If minimal is True, the cofactors will satisfy the
    4788            following conditions. If either self or `n` are zero,
    4789            the trivial solution is returned. If both self and
    4790            `n` are nonzero, the function returns the unique
    4791            solution such that `0 \leq s < |n|/g` (which then
    4792            must also satisfy
    4793            `0 \leq |t| \leq |\mbox{\rm self}|/g`).
     4785        .. note::
     4786
     4787           If minimal is False, then there is no guarantee that the returned
     4788           cofactors will be minimal in any sense; the only guarantee is that
     4789           the Bezout identity will be satisfied (see examples below).
     4790           
     4791           If minimal is True, the cofactors will satisfy the following
     4792           conditions. If either self or `n` are zero, the trivial solution
     4793           is returned. If both self and `n` are nonzero, the function returns
     4794           the unique solution such that `0 \leq s < |n|/g` (which then must
     4795           also satisfy `0 \leq |t| \leq |\mbox{\rm self}|/g`).
    47944796       
    47954797        EXAMPLES::
    47964798       
     
    49644966        n *= sign
    49654967
    49664968        # Now finally call into MPIR to do the shifting.
    4967         cdef Integer z = <Integer>PY_NEW(Integer)
     4969        cdef Integer z = PY_NEW(Integer)
    49684970        if n < 0:
    49694971            mpz_fdiv_q_2exp(z.value, self.value, -n)
    49704972        else:
     
    50355037        return (<Integer>x)._shift_helper(y, -1)
    50365038
    50375039    cdef _and(Integer self, Integer other):
    5038         cdef Integer x
    5039         x = PY_NEW(Integer)
     5040        cdef Integer x = PY_NEW(Integer)
    50405041        mpz_and(x.value, self.value, other.value)
    50415042        return x
    50425043
     
    50565057            return (<Integer>x)._and(y)
    50575058        return bin_op(x, y, operator.and_)
    50585059
    5059 
    50605060    cdef _or(Integer self, Integer other):
    5061         cdef Integer x
    5062         x = PY_NEW(Integer)
     5061        cdef Integer x = PY_NEW(Integer)
    50635062        mpz_ior(x.value, self.value, other.value)
    50645063        return x
    50655064
     
    50775076            return (<Integer>x)._or(y)
    50785077        return bin_op(x, y, operator.or_)
    50795078
    5080 
    50815079    def __invert__(self):
    50825080        """
    50835081        Return the multiplicative inverse of self, as a rational number.
     
    50905088            sage: n.__invert__()
    50915089            1/10
    50925090        """
    5093         return one/self    # todo: optimize
    5094        
     5091        return one / self
     5092
    50955093    def inverse_of_unit(self):
    50965094        """
    50975095        Return inverse of self if self is a unit in the integers, i.e.,
     
    51125110            ...
    51135111            ZeroDivisionError: Inverse does not exist.
    51145112        """
    5115         if mpz_cmp_si(self.value, 1) == 0 or mpz_cmp_si(self.value, -1) == 0:
     5113        if mpz_cmpabs_ui(self.value, 1) == 0:
    51165114            return self
    51175115        else:
    51185116            raise ZeroDivisionError, "Inverse does not exist."
    51195117
    51205118    def inverse_mod(self, n):
    51215119        """
    5122         Returns the inverse of self modulo `n`, if this inverse
    5123         exists. Otherwise, raises a ``ZeroDivisionError``
    5124         exception.
    5125        
    5126         INPUT:
    5127        
     5120        Returns the inverse of self modulo `n`, if this inverse exists.
     5121        Otherwise, raises a ``ZeroDivisionError`` exception.
     5122       
     5123        INPUT:
    51285124       
    51295125        -  ``self`` - Integer
    51305126       
    51315127        -  ``n`` - Integer
    51325128       
    5133        
    5134         OUTPUT:
    5135        
     5129        OUTPUT:
    51365130       
    51375131        -  ``x`` - Integer such that x\*self = 1 (mod m), or
    51385132           raises ZeroDivisionError.
     
    51925186            left, right = canonical_coercion(self, n)
    51935187            return left.gcd(right)
    51945188        cdef Integer m = as_Integer(n)
    5195         cdef Integer g = <Integer>PY_NEW(Integer)
     5189        cdef Integer g = PY_NEW(Integer)
    51965190        sig_on()
    51975191        mpz_gcd(g.value, self.value, m.value)
    51985192        sig_off()
     
    52005194
    52015195    def crt(self, y, m, n):
    52025196        """
    5203         Return the unique integer between `0` and `mn` that
    5204         is congruent to the integer modulo `m` and to `y`
    5205         modulo `n`. We assume that `m` and `n` are
    5206         coprime.
     5197        Return the unique integer between `0` and `mn` that is congruent to
     5198        the integer modulo `m` and to `y` modulo `n`. We assume that `m` and
     5199        `n` are coprime.
    52075200       
    52085201        EXAMPLES::
    52095202       
     
    52225215        if not g.is_one():
    52235216            raise ArithmeticError, "CRT requires that gcd of moduli is 1."
    52245217        # Now s*m + t*n = 1, so the answer is x + (y-x)*s*m, where x=self.
    5225         return (self + (_y-self)*s*_m) % (_m*_n)
     5218        return (self + (_y - self) * s * _m) % (_m * _n)
    52265219
    52275220    def test_bit(self, long index):
    52285221        r"""
    52295222        Return the bit at ``index``.
    52305223       
     5224        If the index is negative, returns 0.
     5225       
     5226        Although internally a sign-magnitude representation is used
     5227        for integers, this method pretends to use a two's complement
     5228        representation.  This is illustrated with a negative integer
     5229        below.
     5230       
    52315231        EXAMPLES::
    52325232       
    52335233            sage: w = 6
     
    52375237            1
    52385238            sage: w.test_bit(-1)
    52395239            0
     5240            sage: x = -20
     5241            sage: x.str(2)
     5242            '-10100'
     5243            sage: x.test_bit(4)
     5244            0
     5245            sage: x.test_bit(5)
     5246            1
     5247            sage: x.test_bit(6)
     5248            1
    52405249        """
    52415250        if index < 0:
    52425251            return 0
     
    52895298   
    52905299    INPUT:
    52915300   
    5292    
    52935301    -  ``v`` - list or tuple
    52945302   
    5295    
    52965303    OUTPUT: integer
    52975304   
    52985305    EXAMPLES::
     
    53345341       
    53355342    return z
    53365343
    5337 
    5338 
    53395344def GCD_list(v):
    53405345    r"""
    53415346    Return the GCD of a list v of integers. Elements of v are converted
     
    53455350   
    53465351    INPUT:
    53475352   
    5348    
    53495353    -  ``v`` - list or tuple
    53505354   
    5351    
    53525355    OUTPUT: integer
    53535356   
    53545357    EXAMPLES::
     
    54125415        ...
    54135416        TypeError: expected string or Unicode object, sage.rings.integer.Integer found
    54145417    """
    5415     cdef Integer r
    5416     r = PY_NEW(Integer)
     5418    cdef Integer r = PY_NEW(Integer)
    54175419    r._reduce_set(s)
    54185420    return r
    54195421   
     
    54575459    def _repr_type(self):
    54585460        return "Native"
    54595461
    5460 
    54615462############### INTEGER CREATION CODE #####################
    54625463
    54635464# We need a couple of internal GMP datatypes.
     
    57225723    integer_pool_size = 0
    57235724    integer_pool_count = 0
    57245725    sage_free(integer_pool)
     5726
  • sage/rings/integer_ring.pyx

    diff -r 777e70039438 sage/rings/integer_ring.pyx
    a b  
    273273        raise TypeError, 'len() of unsized object'
    274274
    275275    def _div(self, integer.Integer left, integer.Integer right):
    276         cdef rational.Rational x
    277         x = PY_NEW(rational.Rational)
    278         if mpz_cmp_si(right.value, 0) == 0:
     276        cdef rational.Rational x = PY_NEW(rational.Rational)
     277        if mpz_sgn(right.value) == 0:
    279278            raise ZeroDivisionError, 'Rational division by zero'
    280         mpq_set_num(x.value, left.value)
    281         mpq_set_den(x.value, right.value)
     279        mpz_set(mpq_numref(x.value), left.value)
     280        mpz_set(mpq_denref(x.value), right.value)
    282281        mpq_canonicalize(x.value)
    283282        return x
    284283