Skip to main content
Mathematics LibreTexts

1.8: Documentation

  • Page ID
    181183
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    Sage offers a wide range of features. To explore what Sage can do, check out the Quick Reference Card and the Reference Manual for detailed information.

    The tutorial offers a useful overview for getting familiar with Sage and its functionalities.

    You can find Sage documentation at the official website. At this stage, reading the documentation is optional, but we will guide you through getting started with Sage in this book.

    To quickly reference Sage documentation, use the ? operator in Sage. This can be a useful way to get immediate help with functions or commands. You can also view the source code of functions using the ?? operator.

    Set?
    Signature:      Set(X=None)
    Docstring:     
       Create the underlying set of "X".
    
       If "X" is a list, tuple, Python set, or "X.is_finite()" is "True",
       this returns a wrapper around Python's enumerated immutable
       "frozenset" type with extra functionality.  Otherwise it returns a
       more formal wrapper.
    
       If you need the functionality of mutable sets, use Python's builtin
       set type.
    
       EXAMPLES:
    
          sage: X = Set(GF(9,'a'))
          sage: X
          {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2}
          sage: type(X)
          <class 'sage.sets.set.Set_object_enumerated_with_category'>
          sage: Y = X.union(Set(QQ))
          sage: Y
          Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field
          sage: type(Y)
          <class 'sage.sets.set.Set_object_union_with_category'>
    
       Usually sets can be used as dictionary keys.
    
          sage: d={Set([2*I,1+I]):10}
          sage: d                  # key is randomly ordered
          {{I + 1, 2*I}: 10}
          sage: d[Set([1+I,2*I])]
          10
          sage: d[Set((1+I,2*I))]
          10
    
       The original object is often forgotten.
    
          sage: v = [1,2,3]
          sage: X = Set(v)
          sage: X
          {1, 2, 3}
          sage: v.append(5)
          sage: X
          {1, 2, 3}
          sage: 5 in X
          False
    
       Set also accepts iterators, but be careful to only give *finite*
       sets:
    
          sage: sorted(Set(range(1,6)))
          [1, 2, 3, 4, 5]
          sage: sorted(Set(list(range(1,6))))
          [1, 2, 3, 4, 5]
          sage: sorted(Set(iter(range(1,6))))
          [1, 2, 3, 4, 5]
    
       We can also create sets from different types:
    
          sage: sorted(Set([Sequence([3,1], immutable=True), 5, QQ, Partition([3,1,1])]), key=str)
          [5, Rational Field, [3, 1, 1], [3, 1]]
    
       Sets with unhashable objects work, but with less functionality:
    
          sage: A = Set([QQ, (3, 1), 5])  # hashable
          sage: sorted(A.list(), key=repr)
          [(3, 1), 5, Rational Field]
          sage: type(A)
          <class 'sage.sets.set.Set_object_enumerated_with_category'>
          sage: B = Set([QQ, [3, 1], 5])  # unhashable
          sage: sorted(B.list(), key=repr)
          Traceback (most recent call last):
          ...
          AttributeError: 'Set_object_with_category' object has no attribute 'list'
          sage: type(B)
          <class 'sage.sets.set.Set_object_with_category'>
    Init docstring: Initialize self.  See help(type(self)) for accurate signature.
    File:           /srv/conda/envs/notebook/lib/python3.8/site-packages/sage/sets/set.py
    Type:           function
    Set??
    Signature: Set(X=None)
    Docstring:
       Create the underlying set of "X".
    
       If "X" is a list, tuple, Python set, or "X.is_finite()" is "True",
       this returns a wrapper around Python's enumerated immutable
       "frozenset" type with extra functionality.  Otherwise it returns a
       more formal wrapper.
    
       If you need the functionality of mutable sets, use Python's builtin
       set type.
    
       EXAMPLES:
    
          sage: X = Set(GF(9,'a'))
          sage: X
          {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2}
          sage: type(X)
          <class 'sage.sets.set.Set_object_enumerated_with_category'>
          sage: Y = X.union(Set(QQ))
          sage: Y
          Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field
          sage: type(Y)
          <class 'sage.sets.set.Set_object_union_with_category'>
    
       Usually sets can be used as dictionary keys.
    
          sage: d={Set([2*I,1+I]):10}
          sage: d                  # key is randomly ordered
          {{I + 1, 2*I}: 10}
          sage: d[Set([1+I,2*I])]
          10
          sage: d[Set((1+I,2*I))]
          10
    
       The original object is often forgotten.
    
          sage: v = [1,2,3]
          sage: X = Set(v)
          sage: X
          {1, 2, 3}
          sage: v.append(5)
          sage: X
          {1, 2, 3}
          sage: 5 in X
          False
    
       Set also accepts iterators, but be careful to only give *finite*
       sets:
    
          sage: sorted(Set(range(1,6)))
          [1, 2, 3, 4, 5]
          sage: sorted(Set(list(range(1,6))))
          [1, 2, 3, 4, 5]
          sage: sorted(Set(iter(range(1,6))))
          [1, 2, 3, 4, 5]
    
       We can also create sets from different types:
    
          sage: sorted(Set([Sequence([3,1], immutable=True), 5, QQ, Partition([3,1,1])]), key=str)
          [5, Rational Field, [3, 1, 1], [3, 1]]
    
       Sets with unhashable objects work, but with less functionality:
    
          sage: A = Set([QQ, (3, 1), 5])  # hashable
          sage: sorted(A.list(), key=repr)
          [(3, 1), 5, Rational Field]
          sage: type(A)
          <class 'sage.sets.set.Set_object_enumerated_with_category'>
          sage: B = Set([QQ, [3, 1], 5])  # unhashable
          sage: sorted(B.list(), key=repr)
          Traceback (most recent call last):
          ...
          AttributeError: 'Set_object_with_category' object has no attribute 'list'
          sage: type(B)
          <class 'sage.sets.set.Set_object_with_category'>
    Source:   
    def Set(X=None):
        r"""
        Create the underlying set of ``X``.
    
        If ``X`` is a list, tuple, Python set, or ``X.is_finite()`` is
        ``True``, this returns a wrapper around Python's enumerated immutable
        ``frozenset`` type with extra functionality.  Otherwise it returns a
        more formal wrapper.
    
        If you need the functionality of mutable sets, use Python's
        builtin set type.
    
        EXAMPLES::
    
            sage: X = Set(GF(9,'a'))
            sage: X
            {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2}
            sage: type(X)
            <class 'sage.sets.set.Set_object_enumerated_with_category'>
            sage: Y = X.union(Set(QQ))
            sage: Y
            Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field
            sage: type(Y)
            <class 'sage.sets.set.Set_object_union_with_category'>
    
        Usually sets can be used as dictionary keys.
    
        ::
    
            sage: d={Set([2*I,1+I]):10}
            sage: d                  # key is randomly ordered
            {{I + 1, 2*I}: 10}
            sage: d[Set([1+I,2*I])]
            10
            sage: d[Set((1+I,2*I))]
            10
    
        The original object is often forgotten.
    
        ::
    
            sage: v = [1,2,3]
            sage: X = Set(v)
            sage: X
            {1, 2, 3}
            sage: v.append(5)
            sage: X
            {1, 2, 3}
            sage: 5 in X
            False
    
        Set also accepts iterators, but be careful to only give *finite*
        sets::
    
            sage: sorted(Set(range(1,6)))
            [1, 2, 3, 4, 5]
            sage: sorted(Set(list(range(1,6))))
            [1, 2, 3, 4, 5]
            sage: sorted(Set(iter(range(1,6))))
            [1, 2, 3, 4, 5]
    
        We can also create sets from different types::
    
            sage: sorted(Set([Sequence([3,1], immutable=True), 5, QQ, Partition([3,1,1])]), key=str)
            [5, Rational Field, [3, 1, 1], [3, 1]]
    
        Sets with unhashable objects work, but with less functionality::
    
            sage: A = Set([QQ, (3, 1), 5])  # hashable
            sage: sorted(A.list(), key=repr)
            [(3, 1), 5, Rational Field]
            sage: type(A)
            <class 'sage.sets.set.Set_object_enumerated_with_category'>
            sage: B = Set([QQ, [3, 1], 5])  # unhashable
            sage: sorted(B.list(), key=repr)
            Traceback (most recent call last):
            ...
            AttributeError: 'Set_object_with_category' object has no attribute 'list'
            sage: type(B)
            <class 'sage.sets.set.Set_object_with_category'>
    
        TESTS::
    
            sage: Set(Primes())
            Set of all prime numbers: 2, 3, 5, 7, ...
            sage: Set(Subsets([1,2,3])).cardinality()
            8
            sage: S = Set(iter([1,2,3])); S
            {1, 2, 3}
            sage: type(S)
            <class 'sage.sets.set.Set_object_enumerated_with_category'>
            sage: S = Set([])
            sage: TestSuite(S).run()
    
        Check that :trac:`16090` is fixed::
    
            sage: Set()
            {}
        """
        if X is None:
            X = []
        elif isinstance(X, CategoryObject):
            if isinstance(X, Set_generic):
                return X
            elif X in Sets().Finite():
                return Set_object_enumerated(X)
            else:
                return Set_object(X)
    
        if isinstance(X, Element) and not isinstance(X, Set_base):
            raise TypeError("Element has no defined underlying set")
    
        try:
            X = frozenset(X)
        except TypeError:
            return Set_object(X)
        else:
            return Set_object_enumerated(X)
    File:      /srv/conda/envs/notebook/lib/python3.8/site-packages/sage/sets/set.py
    Type:      function
    factor?
    Signature:      factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds)
    Docstring:     
       Return the factorization of "n".  The result depends on the type of
       "n".
    
       If "n" is an integer, returns the factorization as an object of
       type "Factorization".
    
       If n is not an integer, "n.factor(proof=proof, **kwds)" gets
       called. See "n.factor??" for more documentation in this case.
    
       Warning:
    
         This means that applying "factor" to an integer result of a
         symbolic computation will not factor the integer, because it is
         considered as an element of a larger symbolic ring.EXAMPLES:
    
            sage: f(n)=n^2
            sage: is_prime(f(3))
            False
            sage: factor(f(3))
            9
    
       INPUT:
    
       * "n" - an nonzero integer
    
       * "proof" - bool or None (default: None)
    
       * "int_" - bool (default: False) whether to return answers as
         Python ints
    
       * "algorithm" - string
    
         * "'pari'" - (default) use the PARI c library
    
         * "'kash'" - use KASH computer algebra system (requires that kash
           be installed)
    
         * "'magma'" - use Magma (requires magma be installed)
    
       * "verbose" - integer (default: 0); PARI's debug variable is set to
         this; e.g., set to 4 or 8 to see lots of output during
         factorization.
    
       OUTPUT:
    
       * factorization of n
    
       The qsieve and ecm commands give access to highly optimized
       implementations of algorithms for doing certain integer
       factorization problems. These implementations are not used by the
       generic factor command, which currently just calls PARI (note that
       PARI also implements sieve and ecm algorithms, but they are not as
       optimized). Thus you might consider using them instead for certain
       numbers.
    
       The factorization returned is an element of the class
       "Factorization"; see Factorization?? for more details, and examples
       below for usage. A Factorization contains both the unit factor (+1
       or -1) and a sorted list of (prime, exponent) pairs.
    
       The factorization displays in pretty-print format but it is easy to
       obtain access to the (prime,exponent) pairs and the unit, to
       recover the number from its factorization, and even to multiply two
       factorizations. See examples below.
    
       EXAMPLES:
    
          sage: factor(500)
          2^2 * 5^3
          sage: factor(-20)
          -1 * 2^2 * 5
          sage: f=factor(-20)
          sage: list(f)
          [(2, 2), (5, 1)]
          sage: f.unit()
          -1
          sage: f.value()
          -20
          sage: factor( -next_prime(10^2) * next_prime(10^7) )
          -1 * 101 * 10000019
    
          sage: factor(-500, algorithm='kash')      # optional - kash
          -1 * 2^2 * 5^3
    
          sage: factor(-500, algorithm='magma')     # optional - magma
          -1 * 2^2 * 5^3
    
          sage: factor(0)
          Traceback (most recent call last):
          ...
          ArithmeticError: factorization of 0 is not defined
          sage: factor(1)
          1
          sage: factor(-1)
          -1
          sage: factor(2^(2^7)+1)
          59649589127497217 * 5704689200685129054721
    
       Sage calls PARI's factor, which has proof False by default. Sage
       has a global proof flag, set to True by default (see
       "sage.structure.proof.proof", or proof.[tab]). To override the
       default, call this function with proof=False.
    
          sage: factor(3^89-1, proof=False)
          2 * 179 * 1611479891519807 * 5042939439565996049162197
    
          sage: factor(2^197 + 1)  # long time (2s)
          3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843
    
       Any object which has a factor method can be factored like this:
    
          sage: K.<i> = QuadraticField(-1)
          sage: factor(122 - 454*i)
          (-3*i - 2) * (-i - 2)^3 * (i + 1)^3 * (i + 4)
    
       To access the data in a factorization:
    
          sage: f = factor(420); f
          2^2 * 3 * 5 * 7
          sage: [x for x in f]
          [(2, 2), (3, 1), (5, 1), (7, 1)]
          sage: [p for p,e in f]
          [2, 3, 5, 7]
          sage: [e for p,e in f]
          [2, 1, 1, 1]
          sage: [p^e for p,e in f]
          [4, 3, 5, 7]
    
       We can factor Python, numpy and gmpy2 numbers:
    
          sage: factor(math.pi)
          3.141592653589793
          sage: import numpy
          sage: factor(numpy.int8(30))
          2 * 3 * 5
          sage: import gmpy2
          sage: factor(gmpy2.mpz(30))
          2 * 3 * 5
    Init docstring: Initialize self.  See help(type(self)) for accurate signature.
    File:           /srv/conda/envs/notebook/lib/python3.8/site-packages/sage/arith/misc.py
    Type:           function
    factor??
    Signature: factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds)
    Docstring:
       Return the factorization of "n".  The result depends on the type of
       "n".
    
       If "n" is an integer, returns the factorization as an object of
       type "Factorization".
    
       If n is not an integer, "n.factor(proof=proof, **kwds)" gets
       called. See "n.factor??" for more documentation in this case.
    
       Warning:
    
         This means that applying "factor" to an integer result of a
         symbolic computation will not factor the integer, because it is
         considered as an element of a larger symbolic ring.EXAMPLES:
    
            sage: f(n)=n^2
            sage: is_prime(f(3))
            False
            sage: factor(f(3))
            9
    
       INPUT:
    
       * "n" - an nonzero integer
    
       * "proof" - bool or None (default: None)
    
       * "int_" - bool (default: False) whether to return answers as
         Python ints
    
       * "algorithm" - string
    
         * "'pari'" - (default) use the PARI c library
    
         * "'kash'" - use KASH computer algebra system (requires that kash
           be installed)
    
         * "'magma'" - use Magma (requires magma be installed)
    
       * "verbose" - integer (default: 0); PARI's debug variable is set to
         this; e.g., set to 4 or 8 to see lots of output during
         factorization.
    
       OUTPUT:
    
       * factorization of n
    
       The qsieve and ecm commands give access to highly optimized
       implementations of algorithms for doing certain integer
       factorization problems. These implementations are not used by the
       generic factor command, which currently just calls PARI (note that
       PARI also implements sieve and ecm algorithms, but they are not as
       optimized). Thus you might consider using them instead for certain
       numbers.
    
       The factorization returned is an element of the class
       "Factorization"; see Factorization?? for more details, and examples
       below for usage. A Factorization contains both the unit factor (+1
       or -1) and a sorted list of (prime, exponent) pairs.
    
       The factorization displays in pretty-print format but it is easy to
       obtain access to the (prime,exponent) pairs and the unit, to
       recover the number from its factorization, and even to multiply two
       factorizations. See examples below.
    
       EXAMPLES:
    
          sage: factor(500)
          2^2 * 5^3
          sage: factor(-20)
          -1 * 2^2 * 5
          sage: f=factor(-20)
          sage: list(f)
          [(2, 2), (5, 1)]
          sage: f.unit()
          -1
          sage: f.value()
          -20
          sage: factor( -next_prime(10^2) * next_prime(10^7) )
          -1 * 101 * 10000019
    
          sage: factor(-500, algorithm='kash')      # optional - kash
          -1 * 2^2 * 5^3
    
          sage: factor(-500, algorithm='magma')     # optional - magma
          -1 * 2^2 * 5^3
    
          sage: factor(0)
          Traceback (most recent call last):
          ...
          ArithmeticError: factorization of 0 is not defined
          sage: factor(1)
          1
          sage: factor(-1)
          -1
          sage: factor(2^(2^7)+1)
          59649589127497217 * 5704689200685129054721
    
       Sage calls PARI's factor, which has proof False by default. Sage
       has a global proof flag, set to True by default (see
       "sage.structure.proof.proof", or proof.[tab]). To override the
       default, call this function with proof=False.
    
          sage: factor(3^89-1, proof=False)
          2 * 179 * 1611479891519807 * 5042939439565996049162197
    
          sage: factor(2^197 + 1)  # long time (2s)
          3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843
    
       Any object which has a factor method can be factored like this:
    
          sage: K.<i> = QuadraticField(-1)
          sage: factor(122 - 454*i)
          (-3*i - 2) * (-i - 2)^3 * (i + 1)^3 * (i + 4)
    
       To access the data in a factorization:
    
          sage: f = factor(420); f
          2^2 * 3 * 5 * 7
          sage: [x for x in f]
          [(2, 2), (3, 1), (5, 1), (7, 1)]
          sage: [p for p,e in f]
          [2, 3, 5, 7]
          sage: [e for p,e in f]
          [2, 1, 1, 1]
          sage: [p^e for p,e in f]
          [4, 3, 5, 7]
    
       We can factor Python, numpy and gmpy2 numbers:
    
          sage: factor(math.pi)
          3.141592653589793
          sage: import numpy
          sage: factor(numpy.int8(30))
          2 * 3 * 5
          sage: import gmpy2
          sage: factor(gmpy2.mpz(30))
          2 * 3 * 5
    Source:   
    def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds):
        """
        Return the factorization of ``n``.  The result depends on the
        type of ``n``.
    
        If ``n`` is an integer, returns the factorization as an object
        of type ``Factorization``.
    
        If n is not an integer, ``n.factor(proof=proof, **kwds)`` gets called.
        See ``n.factor??`` for more documentation in this case.
    
        .. warning::
    
           This means that applying ``factor`` to an integer result of
           a symbolic computation will not factor the integer, because it is
           considered as an element of a larger symbolic ring.
    
           EXAMPLES::
    
               sage: f(n)=n^2
               sage: is_prime(f(3))
               False
               sage: factor(f(3))
               9
    
        INPUT:
    
        -  ``n`` - an nonzero integer
    
        -  ``proof`` - bool or None (default: None)
    
        -  ``int_`` - bool (default: False) whether to return
           answers as Python ints
    
        -  ``algorithm`` - string
    
           - ``'pari'`` - (default) use the PARI c library
    
           - ``'kash'`` - use KASH computer algebra system (requires that
             kash be installed)
    
           - ``'magma'`` - use Magma (requires magma be installed)
    
        -  ``verbose`` - integer (default: 0); PARI's debug
           variable is set to this; e.g., set to 4 or 8 to see lots of output
           during factorization.
    
        OUTPUT:
    
        -  factorization of n
    
        The qsieve and ecm commands give access to highly optimized
        implementations of algorithms for doing certain integer
        factorization problems. These implementations are not used by the
        generic factor command, which currently just calls PARI (note that
        PARI also implements sieve and ecm algorithms, but they are not as
        optimized). Thus you might consider using them instead for certain
        numbers.
    
        The factorization returned is an element of the class
        :class:`~sage.structure.factorization.Factorization`; see Factorization??
        for more details, and examples below for usage. A Factorization contains
        both the unit factor (+1 or -1) and a sorted list of (prime, exponent)
        pairs.
    
        The factorization displays in pretty-print format but it is easy to
        obtain access to the (prime,exponent) pairs and the unit, to
        recover the number from its factorization, and even to multiply two
        factorizations. See examples below.
    
        EXAMPLES::
    
            sage: factor(500)
            2^2 * 5^3
            sage: factor(-20)
            -1 * 2^2 * 5
            sage: f=factor(-20)
            sage: list(f)
            [(2, 2), (5, 1)]
            sage: f.unit()
            -1
            sage: f.value()
            -20
            sage: factor( -next_prime(10^2) * next_prime(10^7) )
            -1 * 101 * 10000019
    
        ::
    
            sage: factor(-500, algorithm='kash')      # optional - kash
            -1 * 2^2 * 5^3
    
        ::
    
            sage: factor(-500, algorithm='magma')     # optional - magma
            -1 * 2^2 * 5^3
    
        ::
    
            sage: factor(0)
            Traceback (most recent call last):
            ...
            ArithmeticError: factorization of 0 is not defined
            sage: factor(1)
            1
            sage: factor(-1)
            -1
            sage: factor(2^(2^7)+1)
            59649589127497217 * 5704689200685129054721
    
        Sage calls PARI's factor, which has proof False by default.
        Sage has a global proof flag, set to True by default (see
        :mod:`sage.structure.proof.proof`, or proof.[tab]). To override
        the default, call this function with proof=False.
    
        ::
    
            sage: factor(3^89-1, proof=False)
            2 * 179 * 1611479891519807 * 5042939439565996049162197
    
        ::
    
            sage: factor(2^197 + 1)  # long time (2s)
            3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843
    
        Any object which has a factor method can be factored like this::
    
            sage: K.<i> = QuadraticField(-1)
            sage: factor(122 - 454*i)
            (-3*i - 2) * (-i - 2)^3 * (i + 1)^3 * (i + 4)
    
        To access the data in a factorization::
    
            sage: f = factor(420); f
            2^2 * 3 * 5 * 7
            sage: [x for x in f]
            [(2, 2), (3, 1), (5, 1), (7, 1)]
            sage: [p for p,e in f]
            [2, 3, 5, 7]
            sage: [e for p,e in f]
            [2, 1, 1, 1]
            sage: [p^e for p,e in f]
            [4, 3, 5, 7]
    
        We can factor Python, numpy and gmpy2 numbers::
    
            sage: factor(math.pi)
            3.141592653589793
            sage: import numpy
            sage: factor(numpy.int8(30))
            2 * 3 * 5
            sage: import gmpy2
            sage: factor(gmpy2.mpz(30))
            2 * 3 * 5
    
        TESTS::
    
            sage: factor(Mod(4, 100))
            Traceback (most recent call last):
            ...
            TypeError: unable to factor 4
            sage: factor("xyz")
            Traceback (most recent call last):
            ...
            TypeError: unable to factor 'xyz'
        """
        try:
            m = n.factor
        except AttributeError:
            # Maybe n is not a Sage Element, try to convert it
            e = py_scalar_to_element(n)
            if e is n:
                # Either n was a Sage Element without a factor() method
                # or we cannot it convert it to Sage
                raise TypeError("unable to factor {!r}".format(n))
            n = e
            m = n.factor
    
        if isinstance(n, Integer):
            return m(proof=proof, algorithm=algorithm, int_=int_,
                     verbose=verbose, **kwds)
    
        # Polynomial or other factorable object
        try:
            return m(proof=proof, **kwds)
        except TypeError:
            # Maybe the factor() method does not have a proof option
            return m(**kwds)
    File:      /srv/conda/envs/notebook/lib/python3.8/site-packages/sage/arith/misc.py
    Type:      function

    1.8: Documentation is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?