
    g0                    Z   d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZmZmZ ddlmZmZmZ ddl m!Z!m"Z"m#Z# ddl$m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- d Z.d[dZ/d Z0d Z1d\dZ2d]dZ3d^dZ4d_d!Z5d`d#Z6d$ Z7d%Z8d&Z9d'Z:d(Z;d)Z<d*Z=d+Z>d,Z?d\d-Z@	 	 dad.ZA	 	 dbd/ZBdcd0ZCd`d1ZDddd2ZEded3ZFd`d4ZGdfd5ZHd6 ZId`d7ZJd8 ZKd9 ZLd`d:ZMd; ZN e&d<d=d>?          d@             ZO e&dAd=d>?          dB             ZP e&dCd=d>?          dfdD            ZQdfdEeRdFeRdGeRfdHZSd\dIZT e&dJd=d>?          dfdK            ZU e&dLd=d>?          dM             ZV e&dNd=d>?          dO             ZWdP ZXdQ ZYdR ZZdS Z[dT Z\dU Z]dV Z^dW Z_dX Z`dY ZadZ ZbdS )gz
Integer factorization
    )defaultdictN)Dict)Mul)RationalInteger)
num_digitsPow)_randint)S)
SYMPY_INTSgcdsqrtsqrtremiroot	bit_scan1remove   )isprimeMERSENNE_PRIME_EXPONENTSis_mersenne_prime)sieve
primerange	nextprime)digits)
deprecated)flatten)as_int
filldedent)_ecm_one_factorc                     | dk    rdS t          |           t                    t          fdD                       fS )a  
    Return the B-smooth and B-power smooth values of n.

    The smoothness of n is the largest prime factor of n; the power-
    smoothness is the largest divisor raised to its multiplicity.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import smoothness
    >>> smoothness(2**7*3**2)
    (3, 128)
    >>> smoothness(2**4*13)
    (13, 16)
    >>> smoothness(2)
    (2, 2)

    See Also
    ========

    factorint, smoothness_p
    r   )r   r   c              3   .   K   | ]}||         z  V  d S N ).0mfacss     Q/var/www/html/ai-engine/env/lib/python3.11/site-packages/sympy/ntheory/factor_.py	<genexpr>zsmoothness.<locals>.<genexpr>5   s+      33!T!W*333333    )	factorintmax)nr'   s    @r(   
smoothnessr.      sL    0 	AvvvQ<<Dt99c3333d3333333r*   c                    |dv rt          |          }n|dvrd}t          | t                    r|r| S i }|                                 D ][}d |                    d          d                             d          d                             d	          D             \  }||<   \|d
ur|dur|S t          |d          S t          | t                    st          | d          }|rdndt          | t                    r| }nAt          fdt          |
                                          D             fd          f}|du s!|d
urt          |           t          t          fv r|S g }	|d         D ]L}
t          |
          }
|
                    d           |	                    dt          |
          z             Md                    |	          S )ao  
    Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
    where:

    1. p**M is the base-p divisor of n
    2. sm(p + m) is the smoothness of p + m (m = -1 by default)
    3. psm(p + m) is the power smoothness of p + m

    The list is sorted according to smoothness (default) or by power smoothness
    if power=1.

    The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
    factor govern the results that are obtained from the p +/- 1 type factoring
    methods.

        >>> from sympy.ntheory.factor_ import smoothness_p, factorint
        >>> smoothness_p(10431, m=1)
        (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
        >>> smoothness_p(10431)
        (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
        >>> smoothness_p(10431, power=1)
        (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])

    If visual=True then an annotated string will be returned:

        >>> print(smoothness_p(21477639576571, visual=1))
        p**i=4410317**1 has p-1 B=1787, B-pow=1787
        p**i=4869863**1 has p-1 B=2434931, B-pow=2434931

    This string can also be generated directly from a factorization dictionary
    and vice versa:

        >>> factorint(17*9)
        {3: 2, 17: 1}
        >>> smoothness_p(_)
        'p**i=3**2 has p-1 B=2, B-pow=2\np**i=17**1 has p-1 B=2, B-pow=16'
        >>> smoothness_p(_)
        {3: 2, 17: 1}

    The table of the output logic is:

        ====== ====== ======= =======
        |              Visual
        ------ ----------------------
        Input  True   False   other
        ====== ====== ======= =======
        dict    str    tuple   str
        str     str    tuple   dict
        tuple   str    tuple   str
        n       str    tuple   tuple
        mul     str    tuple   tuple
        ====== ====== ======= =======

    See Also
    ========

    factorint, smoothness
    )r   r   )TFNc                 ,    g | ]}t          |          S r$   intr%   is     r(   
<listcomp>z smoothness_p.<locals>.<listcomp>   s0     B B BqCFF B B Br*   hasr   =r   z**TF)visualr/   c                 z    g | ]7\  }}|t          |gt          t          |z                       z             f8S r$   )tuplelistr.   )r%   fMr&   s      r(   r6   z smoothness_p.<locals>.<listcomp>   sY     9 9 9!Q d:a!e+<+<&=&= =>>@ 9 9 9r*   c                 0    | d                  | d         fS Nr   r   r$   )xks    r(   <lambda>zsmoothness_p.<locals>.<lambda>   s    qtAw!o r*   key   z#p**i=%i**%i has p%+i B=%i, B-pow=%i
)bool
isinstancestr
splitlinessplitsmoothness_pr;   r+   sortedr<   itemstyper3   r   r   insertappendjoin)r-   r&   powerr9   dlivr'   rvlinesdatrB   s    `         @r(   rM   rM   8   sC   z f	}	$	$!S * 	H,,.. 	 	BB BHHUOOA&,,S11!4::4@@B B BDAqAaDD&"5"5HAe,,,,5!! *5))) !U 8 9 9 9 9%)$**,,%7%79 9 9 65557 7 7 8
 6--DGGSz4I4I	E!u I Icll

1a:U3ZZGHHHH99Ur*   c                    	 t          |           t          |          }} n# t          $ r ddlm} t	          d | |fD                       r6t          |           } t          |          }| j        dk    r_|j        dk    rt          | j        |j                   cY S t          | j        |j                  t          | j        |j                  z
  cY S | j        dk    rt          | j        |j                  cY S t          t          | j        |j                  t          | j        |j                            }t          t          | j        |j                  t          | j        |j                            }||z
  cY S t          | t          t          f          r^t          ||          rNt          |j        d         t                    r.|j        d         dk    rt          | |j        d                   cY S t          d| d|          w xY w|dk    rt          d|z            t          ||           d         S )a*  
    Find the greatest integer m such that p**m divides n.

    Examples
    ========

    >>> from sympy import multiplicity, Rational
    >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
    [0, 1, 2, 3, 3]
    >>> multiplicity(3, Rational(1, 9))
    -2

    Note: when checking for the multiplicity of a number in a
    large factorial it is most efficient to send it as an unevaluated
    factorial or to call ``multiplicity_in_factorial`` directly:

    >>> from sympy.ntheory import multiplicity_in_factorial
    >>> from sympy import factorial
    >>> p = factorial(25)
    >>> n = 2**100
    >>> nfac = factorial(n, evaluate=False)
    >>> multiplicity(p, nfac)
    52818775009509558395695966887
    >>> _ == multiplicity_in_factorial(p, n)
    True

    See Also
    ========

    trailing

    r   	factorialc              3   N   K   | ] }t          |t          t          f          V  !d S r#   )rI   r   r   r4   s     r(   r)   zmultiplicity.<locals>.<genexpr>   s1      EEz!j(344EEEEEEr*   r   z!expecting ints or fractions, got z and z9no such integer exists: multiplicity of %s is not-defined)r   
ValueError(sympy.functions.combinatorial.factorialsr]   allr   qpmultiplicityminrI   r   r   argsmultiplicity_in_factorialr   )rc   r-   r]   likecrosss        r(   rd   rd      s@   BPayy&))1 P P PFFFFFFEEq!fEEEEE 	;AAsaxx3!88(ac222222#AC--QS!#0F0FFFFF#AC----- ac** ac**, ,  ac** ac**, , e|###Z122 	;1i((	;16!9g..	; q	Q,Qq	:::::jAANOOO1P4 	AvvTWXYZZZ!Q<<?s*   " A<H 5H%H>BHA8H?Hc                    t          |           t                    c} | dk    rt          d| z            dk     rt          dz            t          t                    }t	          |                                           D ]\  }}t          |||                   ||<   t          fd|                                D                       S )a  return the largest integer ``m`` such that ``p**m`` divides ``n!``
    without calculating the factorial of ``n``.

    Parameters
    ==========

    p : Integer
        positive integer
    n : Integer
        non-negative integer

    Examples
    ========

    >>> from sympy.ntheory import multiplicity_in_factorial
    >>> from sympy import factorial

    >>> multiplicity_in_factorial(2, 3)
    1

    An instructive use of this is to tell how many trailing zeros
    a given factorial has. For example, there are 6 in 25!:

    >>> factorial(25)
    15511210043330985984000000
    >>> multiplicity_in_factorial(10, 25)
    6

    For large factorials, it is much faster/feasible to use
    this function rather than computing the actual factorial:

    >>> multiplicity_in_factorial(factorial(25), 2**100)
    52818775009509558395695966887

    See Also
    ========

    multiplicity

    r   z!expecting positive integer got %sz%expecting non-negative integer got %sc              3   v   K   | ]3\  }}|z   t          t          |                    z
  |d z
  z  |z  V  4dS r   N)sumr   )r%   rW   rB   r-   s      r(   r)   z,multiplicity_in_factorial.<locals>.<genexpr>  sN      MM41aAF1aLL)))QU3Q6MMMMMMr*   )r   r_   r   r3   r+   rO   r,   re   )rc   r-   r=   rB   rW   s    `   r(   rg   rg      s    T !99fQiiDAqAvv<q@BBB1uu@1DFFF
 	CA!""$$  11ad||!
 MMMM17799MMMMMMr*   rF   c           	      t   | dk    rdS i }dd}d }| dk    rxt          || dd|          d         } | dk    rdS t          |                                 dk    rdS t          j        fd|                                D                       fS |dk     r\t          |           rIdk    rdS | z  } |d	<   | dk    rd	fS t          |           \  }}|rd	|z  fS t                    rdS d}| d
z  dk    r't          | d	          \  }}|r|} |dz  }nn	| d
z  dk    '| |dz  k     r || ||          S | 	                                dz  dz   }||k     rt          ||          D ]}t          | |          \  }}	|	r|} |	|z  }	t          |	          dk    r dS |	||<   | dk    r6t          j        fd|                                D                       fc S dk    sk     ret          | |z            \  }}|r9|t          j        fd|                                D                       z  fc S t                    r dS |}| |dz  k     r || ||          S r?t          t          t                    z	                                                      }
n3t          dt          t          j        | |                    d	z             }
t          j        |           }|dz  }|
D ]}||k     rd	 t%          d	||z            }t          |dz             }t'          ||z
            dk     r%||z  | k    r|} ||z  }t          j        |           }nnbn4	 t          | |          \  }}|r|} ||z  }t          j        |           }nn3| ||d	z   z  k     r n || ||          S )a   Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
    perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).

    Explanation
    ===========

    This is a low-level helper for ``perfect_power``, for internal use.

    Parameters
    ==========

    n : int
        assume that n is a nonnegative integer
    next_p : int
        Assume that n has no factor less than next_p.
        i.e., all(n % p for p in range(2, next_p)) is True

    Examples
    ========
    >>> from sympy.ntheory.factor_ import _perfect_power
    >>> _perfect_power(16)
    (2, 4)
    >>> _perfect_power(17)
    False

       Fr   r   c                     t          |          dk    rdS ||| <   t          j        fd|                                D                       fS )Nr   Fc              3   .   K   | ]\  }}||z  z  V  d S r#   r$   r%   rc   egs      r(   r)   z/_perfect_power.<locals>.done.<locals>.<genexpr>F  /      ??tq!QT??????r*   )r   mathprodrO   )r-   factorsrt   multis     ` r(   donez_perfect_power.<locals>.doneA  sY    5MM665
y????w}}?????BBr*   i@B i  c              3   .   K   | ]\  }}||z  z  V  d S r#   r$   rr   s      r(   r)   z!_perfect_power.<locals>.<genexpr>P  ru   r*   rF            c              3   .   K   | ]\  }}||z  z  V  d S r#   r$   )r%   rc   rs   _gs      r(   r)   z!_perfect_power.<locals>.<genexpr>  sK       %E %E,0Aq &'BZ %E %E %E %E %E %Er*   c              3   .   K   | ]\  }}||z  z  V  d S r#   r$   rr   s      r(   r)   z!_perfect_power.<locals>.<genexpr>  sK       -I -I041 ./AY -I -I -I -I -I -Ir*   (   T      ?{Gz?)_factorint_smallr   valuesrv   rw   rO   r   r   r   
bit_lengthr   r   rN   r+   keysr3   loglog2powabs)r-   next_prx   ry   rz   r&   _exacttf_maxrc   t
prime_iterlogn	thresholdbrbr   rt   s                  @@r(   _perfect_powerr     s   6 	AvvuG	AEC C C 	I~~Wav>>qAq555!!"665y????w}}?????BB zzaLL 	!Avvu!GAGAJAvv!t "!QKK	6 !Q36MQZZ ! 5 a%1**!QKK	6 	AaKEE a%1** 	619}}tAw5))) \\^^R"$FFF++ 	% 	%A!Q<<DAq %U
AYY77 55
669 %E %E %E %E4;MMOO%E %E %E E EFHI I I I!VVrAvvA %ah 2 2IAv % 49 -I -I -I -I8?-I -I -I $I $I  IJK L L L L  %$uu619}}tAw5))) 	 A Ia9Q<<&788==??@@

  3tx6':':#;#;a#?@@
9Q<<Dr	I  q==4!8$$S\\rAv;;%%"a%1**AQJE9Q<<DD !!QKK	6 AQJE9Q<<DD vAE 47Au%%%r*   Tc                     t           t                    r j        s                                 \  }}|t          j        u r6t          |          }|r$                     d|d                   |d         f}nFt          |          }|r5|\  }t          |g          }|r|\  }	}
                     ||	          f}|S t                       dk     r#t                      }|r|\  }dz  r| fS dS ||rt                     S  dk    rdS t          j                   }t          |          dz    dz  dv }d|z   |st                    }nt          fd	|D                       } dz  dk    rt                     fd
|D             }|rt!          |          }|D ]*t#                     \  }}|rt          |          fc S +dS  fd}t%           |            |          D ]W\  }|rĉ |z  dk    rt'           |          d         dk    r dS t#                     \  }}|s@ |z  z  }t          |t)          d                    }|s dS |\  }}||z  z  |z  |c}|s2t+                    }|d         k    r||d         z  z  |d         c}t          |          fc S |z  dk     r0d|z  z  }t-          t          |dz             |z
            dk    rt#                     \  }}|r=|r(t          |||          }|r|d         |d         z  c}t          |          fc S YdS )ap  
    Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
    perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
    perfect power). A ValueError is raised if ``n`` is not Rational.

    By default, the base is recursively decomposed and the exponents
    collected so the largest possible ``e`` is sought. If ``big=False``
    then the smallest possible ``e`` (thus prime) will be chosen.

    If ``factor=True`` then simultaneous factorization of ``n`` is
    attempted since finding a factor indicates the only possible root
    for ``n``. This is True by default since only a few small factors will
    be tested in the course of searching for the perfect power.

    The use of ``candidates`` is primarily for internal use; if provided,
    False will be returned if ``n`` cannot be written as a power with one
    of the candidates as an exponent and factoring (beyond testing for
    a factor of 2) will not be attempted.

    Examples
    ========

    >>> from sympy import perfect_power, Rational
    >>> perfect_power(16)
    (2, 4)
    >>> perfect_power(16, big=False)
    (4, 2)

    Negative numbers can only have odd perfect powers:

    >>> perfect_power(-4)
    False
    >>> perfect_power(-8)
    (-2, 3)

    Rationals are also recognized:

    >>> perfect_power(Rational(1, 2)**3)
    (1/2, 3)
    >>> perfect_power(Rational(-3, 2)**3)
    (-3/2, 3)

    Notes
    =====

    To know whether an integer is a perfect power of 2 use

        >>> is2pow = lambda n: bool(n and not n & (n - 1))
        >>> [(i, is2pow(i)) for i in range(5)]
        [(0, False), (1, True), (2, True), (3, False), (4, True)]

    It is not necessary to provide ``candidates``. When provided
    it will be assumed that they are ints. The first one that is
    larger than the computed maximum possible exponent will signal
    failure for the routine.

        >>> perfect_power(3**8, [9])
        False
        >>> perfect_power(3**8, [2, 4, 8])
        (3, 8)
        >>> perfect_power(3**8, [4, 8], big=False)
        (9, 4)

    See Also
    ========
    sympy.core.intfunc.integer_nthroot
    sympy.ntheory.primetest.is_square
    r   r   rF   FNro   
   )rF   ro   r|      c                 4    g | ]}|cxk    rk     n n|S r$   r$   )r%   r5   max_possiblemin_possibles     r(   r6   z!perfect_power.<locals>.<listcomp>   sD     1 1 11q////<///// ///r*   c                 &    g | ]}|z  d k    |S r   r$   )r%   r5   rs   s     r(   r6   z!perfect_power.<locals>.<listcomp>$  s"    <<<1Q3!88!888r*   c               3   B   K   ddz  z   } 	 | V  t          |           } NrF   )r   )rX   r-   s    r(   _factorszperfect_power.<locals>._factors-  s2      QY	HHH2B	r*   T)	generator)
candidatesr   g       @r   r   )bigfactor)rI   r   
is_Integeras_numer_denomr   Oneperfect_powerfuncr   r   rv   r   r3   r   rN   r   reversedr   zipr   divisorsprimefactorsr   )r-   r   r   r   rc   rb   ppnumpqden_r   r   
not_squarerokr   facexactr&   rEEe0rs   r   r   s   `                      @@@r(   r   r     sY   J !X q| !!1::q!!B /ffQ1&&1.q!!B -Q"1qc** -FCS))1,B	q		A1uuA2 	DAq1u r1uuca   Avv u9Q<<Dt99q=LR<'Jz>L l;;

 1 1 1 1 1
 1 1 1 2 2
Q3!88!A<<<<Z<<<J 	.!*--J 	! 	!A!QKKEAr !1vvqy   !u     hhjj*-- + +Q 	a#gllq#q!AAvvuu Q{{HAu , sAvI"1!t1L1L1LMMM , 55DAqA;q=!DAq 0!!__a5A::q"Q%x="Q%DAqq6619 6B;;d1fA3q3w<<!#$$t++ A;;5 	 (!!V<<< (Q41Q4DAqq6619	 5r*        c                     t                       dk     rt          d          t          ||z             }|}t          |dz             D ]}	|}
|s fd}d}	 |r||k    rnV|dz  } ||
          }
 | ||                    }t	          |
|z
             }|dk    rH| k    rnt          |          c S  |d dz
            } |d dz
            d}dS )a|  
    Use Pollard's rho method to try to extract a nontrivial factor
    of ``n``. The returned factor may be a composite number. If no
    factor is found, ``None`` is returned.

    The algorithm generates pseudo-random values of x with a generator
    function, replacing x with F(x). If F is not supplied then the
    function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
    Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
    supplied; the ``a`` will be ignored if F was supplied.

    The sequence of numbers generated by such functions generally have a
    a lead-up to some number and then loop around back to that number and
    begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
    and loop look a bit like the Greek letter rho, and thus the name, 'rho'.

    For a given function, very different leader-loop values can be obtained
    so it is a good idea to allow for retries:

    >>> from sympy.ntheory.generate import cycle_length
    >>> n = 16843009
    >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
    >>> for s in range(5):
    ...     print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
    ...
    loop length = 2489; leader length =  43
    loop length =   78; leader length = 121
    loop length = 1482; leader length = 100
    loop length = 1482; leader length = 286
    loop length = 1482; leader length = 101

    Here is an explicit example where there is a three element leadup to
    a sequence of 3 numbers (11, 14, 4) that then repeat:

    >>> x=2
    >>> for i in range(9):
    ...     print(x)
    ...     x=(x**2+12)%17
    ...
    2
    16
    13
    11
    14
    4
    11
    14
    4
    >>> next(cycle_length(lambda x: (x**2+12)%17, 2))
    (3, 3)
    >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
    [2, 16, 13, 11, 14, 4]

    Instead of checking the differences of all generated values for a gcd
    with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
    2nd and 4th, 3rd and 6th until it has been detected that the loop has been
    traversed. Loops may be many thousands of steps long before rho finds a
    factor or reports failure. If ``max_steps`` is specified, the iteration
    is cancelled with a failure after the specified number of steps.

    Examples
    ========

    >>> from sympy import pollard_rho
    >>> n=16843009
    >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
    >>> pollard_rho(n, F=F)
    257

    Use the default setting with a bad value of ``a`` and no retries:

    >>> pollard_rho(n, a=n-2, retries=0)

    If retries is > 0 then perhaps the problem will correct itself when
    new values are generated for a:

    >>> pollard_rho(n, a=n-2, retries=1)
    257

    References
    ==========

    .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
           A Computational Perspective", Springer, 2nd edition, 229-231

    r   z pollard_rho should receive n > 4r   c                 2    t          | d          z   z  S r   )r   )rA   ar-   s    r(   rC   zpollard_rho.<locals>.<lambda>  s    3q!Q<<!+q0 r*   r   ro   N)r3   r_   r   ranger   )r-   sr   retriesseed	max_stepsFrandintVr5   Ujrt   s   ` `          r(   pollard_rhor   c  s/   n 	AA1uu;<<<tg~&&G	A7Q;   	100000A	 a)mmFA!A!!A$$AAE1AAvvAvvq66MMMGAq1uGAq1u4r*   r   c           	         t          |           } | dk     s|dk     rt          d          t          ||z             }t          |dz             D ]}|}t	          j        d|dz             D ]C}t          t          j        ||                    }	t          |t          ||	          |           }Dt          |dz
  |           }
d|
cxk     r| k     rn nt          |
          c S  |d| dz
            }dS )a  
    Use Pollard's p-1 method to try to extract a nontrivial factor
    of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.

    The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
    The default is 2.  If ``retries`` > 0 then if no factor is found after the
    first attempt, a new ``a`` will be generated randomly (using the ``seed``)
    and the process repeated.

    Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).

    A search is made for factors next to even numbers having a power smoothness
    less than ``B``. Choosing a larger B increases the likelihood of finding a
    larger factor but takes longer. Whether a factor of n is found or not
    depends on ``a`` and the power smoothness of the even number just less than
    the factor p (hence the name p - 1).

    Although some discussion of what constitutes a good ``a`` some
    descriptions are hard to interpret. At the modular.math site referenced
    below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
    for every prime power divisor of N. But consider the following:

        >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
        >>> n=257*1009
        >>> smoothness_p(n)
        (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])

    So we should (and can) find a root with B=16:

        >>> pollard_pm1(n, B=16, a=3)
        1009

    If we attempt to increase B to 256 we find that it does not work:

        >>> pollard_pm1(n, B=256)
        >>>

    But if the value of ``a`` is changed we find that only multiples of
    257 work, e.g.:

        >>> pollard_pm1(n, B=256, a=257)
        1009

    Checking different ``a`` values shows that all the ones that did not
    work had a gcd value not equal to ``n`` but equal to one of the
    factors:

        >>> from sympy import ilcm, igcd, factorint, Pow
        >>> M = 1
        >>> for i in range(2, 256):
        ...     M = ilcm(M, i)
        ...
        >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
        ...      igcd(pow(a, M, n) - 1, n) != n])
        {1009}

    But does aM % d for every divisor of n give 1?

        >>> aM = pow(255, M, n)
        >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
        [(257**1, 1), (1009**1, 1)]

    No, only one of them. So perhaps the principle is that a root will
    be found for a given value of B provided that:

    1) the power smoothness of the p - 1 value next to the root
       does not exceed B
    2) a**M % p != 1 for any of the divisors of n.

    By trying more than one ``a`` it is possible that one of them
    will yield a factor.

    Examples
    ========

    With the default smoothness bound, this number cannot be cracked:

        >>> from sympy.ntheory import pollard_pm1
        >>> pollard_pm1(21477639576571)

    Increasing the smoothness bound helps:

        >>> pollard_pm1(21477639576571, B=2000)
        4410317

    Looking at the smoothness of the factors of this number we find:

        >>> from sympy.ntheory.factor_ import smoothness_p, factorint
        >>> print(smoothness_p(21477639576571, visual=1))
        p**i=4410317**1 has p-1 B=1787, B-pow=1787
        p**i=4869863**1 has p-1 B=2434931, B-pow=2434931

    The B and B-pow are the same for the p - 1 factorizations of the divisors
    because those factorizations had a very large prime factor:

        >>> factorint(4410317 - 1)
        {2: 2, 617: 1, 1787: 1}
        >>> factorint(4869863-1)
        {2: 1, 2434931: 1}

    Note that until B reaches the B-pow value of 1787, the number is not cracked;

        >>> pollard_pm1(21477639576571, B=1786)
        >>> pollard_pm1(21477639576571, B=1787)
        4410317

    The B value has to do with the factors of the number next to the divisor,
    not the divisors themselves. A worst case scenario is that the number next
    to the factor p has a large prime divisisor or is a perfect power. If these
    conditions apply then the power-smoothness will be about p/2 or p. The more
    realistic is that there will be a large prime factor next to p requiring
    a B value on the order of p/2. Although primes may have been searched for
    up to this level, the p/2 is a factor of p - 1, something that we do not
    know. The modular.math reference below states that 15% of numbers in the
    range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
    will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
    percentages are nearly reversed...but in that range the simple trial
    division is quite fast.

    References
    ==========

    .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
           A Computational Perspective", Springer, 2nd edition, 236-238
    .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
    .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
       ro   z*pollard_pm1 should receive n > 3 and B > 2r   rF   N)
r3   r_   r   r   r   r   rv   r   r   r   )r-   Br   r   r   r   r5   aMrc   rs   rt   s              r(   pollard_pm1r     s   B 	AA1uuAEFFFtax  G
 7Q;  !!QU++ 	' 	'ADHQNN##ARQA&&BBQNNq9999199999q66MMM GAq1u r*   Fc                    |r!t          |                                           }t          |           }|D ])}||z  dk    rt          ||z  |          \  }}|dz   | |<   *|r^t	          t          |                               t          |                              D ]!}t          t          || |         fz             "t          |          t          |           |k    fS )a  
    Helper function for integer factorization. Trial factors ``n`
    against all integers given in the sequence ``candidates``
    and updates the dict ``factors`` in-place. Returns the reduced
    value of ``n`` and a flag indicating whether any factors were found.
    r   r   )
r<   r   lenr   rN   set
differenceprint
factor_msgr3   )	rx   r-   r   verbosefactors0nfactorsrU   r&   rB   s	            r(   _trialr   p  s      (''7||H  q5A::!q&!$$DAqQGAJ 0G//H>>?? 	0 	0A*71:.////q663w<<8+++r*   c                 @   |rt          d           |dk    r|rt          t                     dS ||dz  k     st          |          r*d| t          |          <   |rt          t                     dS t	          ||          }|sdS |\  }	}
|	|dz  k     st          |	          r|
| |	<   n_t          |	||||d          }|                                D ]5\  }}|rt          t          ||fz             t          |
|z            | |<   6|rt          t                     dS )z
    Helper function for integer factorization. Checks if ``n``
    is a prime or a perfect power, and in those cases updates the factorization.
    zCheck for terminationr   TrF   Fr   )r   complete_msgr   r3   r   r+   rO   r   )rx   r-   limit	use_trialuse_rhouse_pm1r   r   rc   baseexpr'   r   rs   s                 r(   _check_terminationr     sW     '%&&&Avv 	 ,t619}}

}A 	 ,t 	q&!!A uID#fai74==ui'!&( ( (JJLL 	$ 	$DAq +jAq6)***SUGAJJ l4r*   z4Trial division with ints [%i ... %i] and fail_max=%iz&Trial division with primes [%i ... %i]z7Pollard's rho with retries %i, max_steps %i and seed %iz2Pollard's p-1 with smoothness bound %i and seed %iz;Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %iz		%i ** %iz/Close factors satisying Fermat condition found.zFactorization is complete.c                    d }|dz  }t          ||          }|dk     rB|dz  s)t          |          }|| d<   ||z  }t          ||          }d}|dk     r |||          S |dk     rh|dz  sO|dz  }d}|dz  s.|dz  }|dz  }|dk    rt          |d          \  }}	||	z  }n|dz  .|| d<   t          ||          }d}|dk     r |||          S |d	z  }
||
dk     rd
nd|
z
  z  }d}||k     r||z  r|dz  }nQ||z  }d}||z  s.||z  }|dz  }|dk    rt          ||          \  }}	||	z  }n||z  .|| |<   d}t          ||          }|dz  }||dz  k     r |||          S ||z  r|dz  }nQ||z  }d}||z  s.||z  }|dz  }|dk    rt          ||          \  }}	||	z  }n||z  .|| |<   d}t          ||          }|dz  }||dz  k     r |||          S ||k      |||          S )a  
    Return the value of n and either a 0 (indicating that factorization up
    to the limit was complete) or else the next near-prime that would have
    been tested.

    Factoring stops if there are fail_max unsuccessful tests in a row.

    If factors of n were found they will be in the factors dictionary as
    {factor: multiplicity} and the returned value of n will have had those
    factors removed. The factors dictionary is modified in-place.

    c                 $    ||z  | k    r| |fS | dfS )zpreturn n, d if the sqrt(n) was not reached yet, else
           n, 0 indicating that factoring is done.
        r   r$   )r-   rU   s     r(   rz   z_factorint_small.<locals>.done  s#     Q3!88a4K!tr*   rF   ro   r   	   r            r/   r   r   )re   r   r   )rx   r-   r   fail_maxr   rz   limit2
threshold2r&   mmp6failss               r(   r   r     s      AXFQJzz1u 	(!AGAJ!GAQJ>>46??"zz1u 	(!GAA!e aQ77"1aLLEArGA !e  GAJQJ??46??" 
!B
R!VVrrb((FE
(

v: 	(QJEE&LAA&j fQ77"1f--EArGA &j   GFOEQJ!	!!46??" v: 	(QJEE&LAA&j fQ77"1f--EArGA &j   GFOEQJ!	!!46??"O (

P 46??r*   c	                 T  0 t          | t                    rt          |           } |rBt          | |||||dd          0t	          0fdt          0          D             g           }	|	S i }
|r3t          | t          t          f          st          | |||||d          }
n]t          | t                    r1d |                                                                 D             }
nt          | t                    r| }
|
rt          | t          t          f          rt          |

                                          D ]w}t          |          r|
                    |          }t          ||||||d          }|                                D ]%\  }}||
v r|
|xx         ||z  z  cc<   ||z  |
|<   &x|st          |           t          u r|dur|dur|
i k    rt          j        S d|
v r#|
                    d           t          j        g}ng }|                    d t          |
                                          D                        t          |d	diS t          | t          t          f          r|
S |s|s|s|sJ d
dlm} t          | |          rt)          | j        d
                   }|dk    ri }d}t-          j        d|dz             D ]*}|dk    rd
||z  }}|d
k    r||z  }||z  }|d
k    |||<   +|r3|r1t          |          D ]!}t1          t2          |||         fz             "|rt1          t4                     |S |                     |          } t)          |           } |rt9          |          }d}| d
k     rt          |  |||||d          }d|d<   |S |r|dk     r| dk    ri S | diS | dk     r%d
dii ddiddiddiddidddddiddiddig
|          S i }|rnt;          |           }t=          |          dk    r<t1          d|dd         z  dt=          |          dz
  z  z   |dd         z              nt1          d|            d}d}t?          ||p|          }|rt1          t@          d||fz             tC          || ||          \  } }|r3|r1t          |          D ]!}t1          t2          |||         fz             "|d
k    r0| dk    rd|t9          |           <   |rt1          t4                     |S |rJ||k    rD|rt1          d|           tE          || ||||||          r|S | dk    rd|t9          |           <   |S tE          || ||||||          r|S tG          |           }|dz   }| dz  dk    |dz  z  r|dz  }|dz  }|| z
  }tI          d          D ]}tK          |          \  } }!|!s|rt1          tL                     || z
  || z   fD ]M}"t          |"|||||          }#|#                                D ]!\  }}|'                    |d
          |z   ||<   "N|rt1          t4                     |c S ||dz   dz  z  }|dz  }|d|z  }%}$|p|dz   }&d
}'	 t?          |%|&          }(|rb|rt1          tP          |$|(fz             t-          j        |$|(          })tS          || |)|          \  } }*|(}|*rtE          || ||||||          r|S nd}*|%|&k    rB|rt1          d|&           | dk    rd|t9          |           <   |rt1          t4                     |S |*s$|r|rt1          tT          |$|(fz             tW          | |$|(          }+|+r`|+|dz  k     st          |+          r|+g})nt          |+||||||           })tS          || |)d!          \  } }tE          || ||||||          r|S |r|rt1          tX          d|$|(fz             t[          | d|$|("          }+|+r`|+|dz  k     st          |+          r|+g})nt          |+||||||           })tS          || |)d!          \  } }tE          || ||||||          r|S |'dz  }'|r|'dk    rt]          |           d#k    rn	|%|%dz  }%}$d$},d%|,z  }-d}.	 |rt1          t^          |,|-|.fz             ta          | |,|-|.|,&          }/|/r`|/|dz  k     st          |/          r|/g})nt          |/||||||           })tS          || |)d!          \  } }tE          || ||||||          r|S |,dz  },d%|,z  }-|.dz  }.)'a  
    Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
    the prime factors of ``n`` as keys and their respective multiplicities
    as values. For example:

    >>> from sympy.ntheory import factorint
    >>> factorint(2000)    # 2000 = (2**4) * (5**3)
    {2: 4, 5: 3}
    >>> factorint(65537)   # This number is prime
    {65537: 1}

    For input less than 2, factorint behaves as follows:

        - ``factorint(1)`` returns the empty factorization, ``{}``
        - ``factorint(0)`` returns ``{0:1}``
        - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``

    Partial Factorization:

    If ``limit`` (> 3) is specified, the search is stopped after performing
    trial division up to (and including) the limit (or taking a
    corresponding number of rho/p-1 steps). This is useful if one has
    a large number and only is interested in finding small factors (if
    any). Note that setting a limit does not prevent larger factors
    from being found early; it simply means that the largest factor may
    be composite. Since checking for perfect power is relatively cheap, it is
    done regardless of the limit setting.

    This number, for example, has two small factors and a huge
    semi-prime factor that cannot be reduced easily:

    >>> from sympy.ntheory import isprime
    >>> a = 1407633717262338957430697921446883
    >>> f = factorint(a, limit=10000)
    >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
    True
    >>> isprime(max(f))
    False

    This number has a small factor and a residual perfect power whose
    base is greater than the limit:

    >>> factorint(3*101**7, limit=5)
    {3: 1, 101: 7}

    List of Factors:

    If ``multiple`` is set to ``True`` then a list containing the
    prime factors including multiplicities is returned.

    >>> factorint(24, multiple=True)
    [2, 2, 2, 3]

    Visual Factorization:

    If ``visual`` is set to ``True``, then it will return a visual
    factorization of the integer.  For example:

    >>> from sympy import pprint
    >>> pprint(factorint(4200, visual=True))
     3  1  2  1
    2 *3 *5 *7

    Note that this is achieved by using the evaluate=False flag in Mul
    and Pow. If you do other manipulations with an expression where
    evaluate=False, it may evaluate.  Therefore, you should use the
    visual option only for visualization, and use the normal dictionary
    returned by visual=False if you want to perform operations on the
    factors.

    You can easily switch between the two forms by sending them back to
    factorint:

    >>> from sympy import Mul
    >>> regular = factorint(1764); regular
    {2: 2, 3: 2, 7: 2}
    >>> pprint(factorint(regular))
     2  2  2
    2 *3 *7

    >>> visual = factorint(1764, visual=True); pprint(visual)
     2  2  2
    2 *3 *7
    >>> print(factorint(visual))
    {2: 2, 3: 2, 7: 2}

    If you want to send a number to be factored in a partially factored form
    you can do so with a dictionary or unevaluated expression:

    >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
    {2: 10, 3: 3}
    >>> factorint(Mul(4, 12, evaluate=False))
    {2: 4, 3: 1}

    The table of the output logic is:

        ====== ====== ======= =======
                       Visual
        ------ ----------------------
        Input  True   False   other
        ====== ====== ======= =======
        dict    mul    dict    mul
        n       mul    dict    dict
        mul     mul    dict    dict
        ====== ====== ======= =======

    Notes
    =====

    Algorithm:

    The function switches between multiple algorithms. Trial division
    quickly finds small factors (of the order 1-5 digits), and finds
    all large factors if given enough time. The Pollard rho and p-1
    algorithms are used to find large factors ahead of time; they
    will often find factors of the order of 10 digits within a few
    seconds:

    >>> factors = factorint(12345678910111213141516)
    >>> for base, exp in sorted(factors.items()):
    ...     print('%s %s' % (base, exp))
    ...
    2 2
    2507191691 1
    1231026625769 1

    Any of these methods can optionally be disabled with the following
    boolean parameters:

        - ``use_trial``: Toggle use of trial division
        - ``use_rho``: Toggle use of Pollard's rho method
        - ``use_pm1``: Toggle use of Pollard's p-1 method

    ``factorint`` also periodically checks if the remaining part is
    a prime number or a perfect power, and in those cases stops.

    For unevaluated factorial, it uses Legendre's formula(theorem).


    If ``verbose`` is set to ``True``, detailed progress is printed.

    See Also
    ========

    smoothness, smoothness_p, divisors

    Fr   r   r   r   r   r9   multiplec              3   |   K   | ]6}|         d k    r|g|         z  nt           j        |z  g|          z  V  7dS r   Nr   r   )r%   rc   r   s     r(   r)   zfactorint.<locals>.<genexpr>  sd       5 5#$ +.a&1**1#A,,157)c!fW:M 5 5 5 5 5 5r*   )r   r   r   r   r   r9   c                 N    i | ]"\  }}t          |          t          |          #S r$   r2   r%   rB   rW   s      r(   
<dictcomp>zfactorint.<locals>.<dictcomp>  s6     ( ( (Ac!ffc!ff ( ( (r*   Tr/   c                 &    g | ]}t          |d diS evaluateFr	   r4   s     r(   r6   zfactorint.<locals>.<listcomp>  s5     : : : !,e,, : : :r*   r   r   r\   r   rF   r   r   ro   r   )rF   ro   r|   2   zFactoring %sNz..(%i other digits)..	Factoringi   iX  zExceeded limit:r   r   r   r   r   r   )r   r   )r   r   r   r   use_ecmr   r   )r   r   r   r~   i'  d   )r   )1rI   r   dictr+   rm   rN   r   as_powers_dictrO   r<   r   r   poprP   r   r   NegativeOneextendr`   r]   r   rf   r   r   r   r   r   r   r3   rJ   r   re   trial_int_msgr   r   isqrtr   r   
fermat_msgget	trial_msgr   pm1_msgr   rho_msgr   r   ecm_msgr    )1r-   r   r   r   r   r  r   r9   r   
factorlist
factordictrE   rs   rU   rB   rW   rf   r]   rA   rx   r&   rc   rb   snsmallr   r   sqrt_nr   a2b2r   r   fermatr   r'   lowhigh_limit	iterationhigh_psfound_trialcB1B2
num_curvesr   r   s1                                                   @r(   r+   r+     s   j !T GG )#*G#*55J J J  5 5 5 5(.s5 5 568: :
J jS$K00 q'.'.u> > >

 
As		 ( ($$&&( ( (

	At		 
 (jS$K00 (
))** 
	( 
	(Cs|| s##A#Ui")75J J JA		 ( (1
??qMMMQqS(MMMM$%aCJqMM	(
  $q''T//$$%%5LNN2M?DDD : :$Z%5%5%7%788: : : 	; 	; 	;D)5)))	Ac{	#	# 5575g555BBBBBB!Y 16!977GA%aQ//  q55a1fqAq&&Qa q&& 

 87 8 8 8A*71:67777 $l###N q		Aq		A E

 	1uuBey'WU< < <  966I1v	
R AQFQFQFQF!q!fq!fq!f6679 	9 G  "VVr77R<<.2bqb6))SWWr\:;=?WE F F F F +q!!!
 EHu~&&E 4mq%22333 !UH==IAv 07 0 	0 	0A*71:.////{{q55GCFFO 	 ,  % 	,#U+++gq%%wA A 	Nq55GCFFO'1eY!7GV= =  1XXF
A	A
q1u 	Q	
AB	aB1XX  BKK	6 	 "j!!!!eQU^ 7 7 %9)0')02 2 2 !JJLL 7 7DAq!(Q!2!2Q!6GAJJ7 $l###NNN
q1ul	Q &C ov"FIH!D&!!  
	  0i3,.///!#u--B#GQG<<NA{F 1'1eY297GV U  U K&== 1'0001uu"#A $l###N  '	' ' 2'S%L0111Su555 '619}}

}S&q1:/6/6/6/68 8 8 "'1b%@@@DAq)'1eY*17GVM M '&  ' 5'QUO34441%HHH '619}}

}S&q1:/6/6/6/68 8 8 "'1b%@@@DAq)'1eY*17GVM M '& 	Q	 	yA~~*Q--2*=*=$q&TQH!T 
B	RBJ 	2'RZ00111 BJR@@@ 		!!WV__!XvU%.#*#*#*#*, , , '1b%888DAq!'1eY")7GVE E 
aVa
)r*   c           
         |rWt          | |||||dd          t          fdt                                          d           D             g           }|S t	          | j        |||||                                          }	t          t          |	          }	t	          | j	        |||||                                          D ]\  }
}|	|
xx         | z  cc<   t          |	          dk    rd|	v r|	d= |st          |	          S d|	v r#|	                    d           t          j        g}ng }|                    d	 t          |	                                          D                        t!          |d
diS )a  
    Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
    the prime factors of ``r`` as keys and their respective multiplicities
    as values. For example:

    >>> from sympy import factorrat, S
    >>> factorrat(S(8)/9)    # 8/9 = (2**3) * (3**-2)
    {2: 3, 3: -2}
    >>> factorrat(S(-1)/987)    # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
    {-1: 1, 3: -1, 7: -1, 47: -1}

    Please see the docstring for ``factorint`` for detailed explanations
    and examples of the following keywords:

        - ``limit``: Integer limit up to which trial division is done
        - ``use_trial``: Toggle use of trial division
        - ``use_rho``: Toggle use of Pollard's rho method
        - ``use_pm1``: Toggle use of Pollard's p-1 method
        - ``verbose``: Toggle detailed printing of progress
        - ``multiple``: Toggle returning a list of factors or dict
        - ``visual``: Toggle product form of output
    Fr   c              3      K   | ]9\  }}|         d k    r|g|         z  nt           j        |z  g|          z  V  :dS r   r   )r%   rc   r   r   s      r(   r)   zfactorrat.<locals>.<genexpr>  sp       I I#'1a +.a&1**1#A,,157)c!fW:M I I I I I Ir*   c                 @    | d         dk    r| d         n
d| d         z  S r@   r$   )elems    r(   rC   zfactorrat.<locals>.<lambda>  s,    ;?7Q;; JNa=>tAwY r*   rD   r   r   r/   c                 &    g | ]}t          |d diS r   r	   r4   s     r(   r6   zfactorrat.<locals>.<listcomp>   s5     1 1 1 !,e,, 1 1 1r*   r   )	factorratrm   rN   rO   r+   rc   copyr   r3   rb   r   r  r  r   r  r  r   )ratr   r   r   r   r   r9   r   r  r=   rc   rs   rf   r   s                @r(   r(  r(    s   0  	5I!7!%%A A A  I I I I+1#))++=G =G,H ,H ,HI I I KM	N N

 #%u	!7!	# 	# 	##'466  	CA#%u$-")")")	+ + + ,1577	 1
 	
!

1vvzza1ffaD 
*Aww77EE"IIIM?DDD 1 1$QWWYY//1 1 1 	2 	2 	2D)5)))r*   c                     t          |           } |                    dd||d           t          t          dd| i|                                          }d |dd         D             }|r!t          |d                   r||d         gz  }|S )aM  Return a sorted list of n's prime factors, ignoring multiplicity
    and any composite factor that remains if the limit was set too low
    for complete factorization. Unlike factorint(), primefactors() does
    not return -1 or 0.

    Parameters
    ==========

    n : integer
    limit, verbose, **kwargs :
        Additional keyword arguments to be passed to ``factorint``.
        Since ``kwargs`` is new in version 1.13,
        ``limit`` and ``verbose`` are retained for compatibility purposes.

    Returns
    =======

    list(int) : List of prime numbers dividing ``n``

    Examples
    ========

    >>> from sympy.ntheory import primefactors, factorint, isprime
    >>> primefactors(6)
    [2, 3]
    >>> primefactors(-5)
    [5]

    >>> sorted(factorint(123456).items())
    [(2, 6), (3, 1), (643, 1)]
    >>> primefactors(123456)
    [2, 3, 643]

    >>> sorted(factorint(10000000001, limit=200).items())
    [(101, 1), (99009901, 1)]
    >>> isprime(99009901)
    False
    >>> primefactors(10000000001, limit=300)
    [101]

    See Also
    ========

    factorint, divisors

    NF)r9   r   r   r   r-   c                     g | ]}|d v|	S ))r/   r   r   r$   )r%   r=   s     r(   r6   z primefactors.<locals>.<listcomp>:  s"    999qQj%8%8%8%8%8r*   r/   r$   )r3   updaterN   r+   r   r   )r-   r   r   kwargsrx   r   s         r(   r   r     s    ^ 	AA
MMTu!g7 7 8 8 8Y---f--224455G 	:9GDRDM999A 772;'' 	gbk]Hr*   c              #      K    dk    r
|s rdV  dS t                     t                                                    dfd	|r fd             D             E d{V  dS              E d{V  dS )zHelper function for divisors which generates the divisors.

    Parameters
    ==========

    n : int
        a nonnegative integer
    proper: bool
        If `True`, returns the generator that outputs only the proper divisor (i.e., excluding n).

    r   Nr   c              3   
  K   | t                    k    rdV  d S dgt          |                             D ]&}                    d         |          z             'fd | dz             D             E d {V  d S )Nr   r/   c              3   ,   K   | ]}D ]	}||z  V  
d S r#   r$   )r%   rb   rc   powss      r(   r)   z-_divisors.<locals>.rec_gen.<locals>.<genexpr>[  s4      DD!tDD!ADDDDDDDr*   )r   r   rR   )r-   r   r2  r  r  rec_gens     @r(   r3  z_divisors.<locals>.rec_genT  s      B<<GGGGG3D:be,-- . .DHr!u,----DDDDwwq1u~~DDDDDDDDDDDDr*   c              3   (   K   | ]}|k    |V  d S r#   r$   )r%   rc   r-   s     r(   r)   z_divisors.<locals>.<genexpr>^  s'      33!AFFAFFFF33r*   r   )r+   rN   r   )r-   properr  r  r3  s   ` @@@r(   	_divisorsr6  @  s       	Avv 	! 	GGG1J	
!!	"	"BE E E E E E E E  3333wwyy333333333333799r*   c                 |    t          t          t          |                     |          }|r|nt          |          S )a-  
    Return all divisors of n sorted from 1..n by default.
    If generator is ``True`` an unordered generator is returned.

    The number of divisors of n can be quite large if there are many
    prime factors (counting repeated factors). If only the number of
    factors is desired use divisor_count(n).

    Examples
    ========

    >>> from sympy import divisors, divisor_count
    >>> divisors(24)
    [1, 2, 3, 4, 6, 8, 12, 24]
    >>> divisor_count(24)
    8

    >>> list(divisors(120, generator=True))
    [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]

    Notes
    =====

    This is a slightly modified version of Tim Peters referenced at:
    https://stackoverflow.com/questions/1010381/python-factorization

    See Also
    ========

    primefactors, factorint, divisor_count
    )r6  r   r   rN   )r-   r   r5  rX   s       r(   r   r   c  s5    @ 
6#a&&>>6	*	*B*22r

*r*   c                     |sdS |dk    rt          | |          \  } }|rdS | dk    rdS t          d t          |                                           D              } | r|r| dz  } | S )a  
    Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
    those that are divisible by ``modulus`` are counted. If ``proper`` is True
    then the divisor of ``n`` will not be counted.

    Examples
    ========

    >>> from sympy import divisor_count
    >>> divisor_count(6)
    4
    >>> divisor_count(6, 2)
    2
    >>> divisor_count(6, proper=True)
    3

    See Also
    ========

    factorint, divisors, totient, proper_divisor_count

    r   r   c                 *    g | ]\  }}|d k    |d z   S r   r$   r   s      r(   r6   z!divisor_count.<locals>.<listcomp>  s%    >>>1Aa!er*   )divmodr   r+   rO   )r-   modulusr5  r   s       r(   divisor_countr=    s    0  q	Aa!!1 	1Avvq>>	! 2 2 4 4>>>?A V 	QHr*   c                 &    t          | |d          S )a  
    Return all divisors of n except n, sorted by default.
    If generator is ``True`` an unordered generator is returned.

    Examples
    ========

    >>> from sympy import proper_divisors, proper_divisor_count
    >>> proper_divisors(24)
    [1, 2, 3, 4, 6, 8, 12]
    >>> proper_divisor_count(24)
    7
    >>> list(proper_divisors(120, generator=True))
    [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]

    See Also
    ========

    factorint, divisors, proper_divisor_count

    T)r   r5  )r   )r-   r   s     r(   proper_divisorsr?    s    , A48888r*   c                 &    t          | |d          S )a$  
    Return the number of proper divisors of ``n``.

    Examples
    ========

    >>> from sympy import proper_divisor_count
    >>> proper_divisor_count(6)
    3
    >>> proper_divisor_count(6, modulus=2)
    1

    See Also
    ========

    divisors, proper_divisors, divisor_count

    T)r<  r5  )r=  )r-   r<  s     r(   proper_divisor_countrA    s    & GD9999r*   c              #   F  K   | dk    r| dk    rdV  dS d t          |                                           D             }t          dt          |          z            D ]A}d}t          |                                          D ]}|dz  r|||         z  }|dz  }|V  BdS )zHelper function for udivisors which generates the unitary divisors.

    Parameters
    ==========

    n : int
        a nonnegative integer

    r   Nc                     g | ]
\  }}||z  S r$   r$   )r%   rc   rs   s      r(   r6   z_udivisors.<locals>.<listcomp>  s     88841a!Q$888r*   rF   )r+   rO   r   r   r   )r-   
factorpowsr5   rU   rB   s        r(   
_udivisorsrE    s       	Avv66GGG889Q<<#5#5#7#7888J 1c*oo%&&  q||~~&& 	 	A1u #Z]"!GAA r*   c                 z    t          t          t          |                               }|r|nt          |          S )a)  
    Return all unitary divisors of n sorted from 1..n by default.
    If generator is ``True`` an unordered generator is returned.

    The number of unitary divisors of n can be quite large if there are many
    prime factors. If only the number of unitary divisors is desired use
    udivisor_count(n).

    Examples
    ========

    >>> from sympy.ntheory.factor_ import udivisors, udivisor_count
    >>> udivisors(15)
    [1, 3, 5, 15]
    >>> udivisor_count(15)
    4

    >>> sorted(udivisors(120, generator=True))
    [1, 3, 5, 8, 15, 24, 40, 120]

    See Also
    ========

    primefactors, factorint, divisors, divisor_count, udivisor_count

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Unitary_divisor
    .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html

    )rE  r   r   rN   r-   r   rX   s      r(   	udivisorsrH    s3    B 
F3q66NN	#	#B*22r

*r*   c                 d    | dk    rdS dt          d t          |           D                       z  S )a  
    Return the number of unitary divisors of ``n``.

    Parameters
    ==========

    n : integer

    Examples
    ========

    >>> from sympy.ntheory.factor_ import udivisor_count
    >>> udivisor_count(120)
    8

    See Also
    ========

    factorint, divisors, udivisors, divisor_count, totient

    References
    ==========

    .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html

    r   rF   c                     g | ]
}|d k    |S r:  r$   )r%   rc   s     r(   r6   z"udivisor_count.<locals>.<listcomp>:  s    444a!ee1eeer*   )r   r+   r-   s    r(   udivisor_countrL    s:    8 	Avvqc44ill4445555r*   c              #   *  K   | dk    rdS t          |           D ]}d|z  }| |k    r	| |z  r|V  t          d| z  dz
            D ]}| |cxk    rdk    rn | |z  r|V  t          d| z  dz             D ]}| |cxk    rdk    rn | |z  r|V  dS )zHelper function for antidivisors which generates the antidivisors.

    Parameters
    ==========

    n : int
        a nonnegative integer

    rF   Nr   )r6  )r-   rU   ys      r(   _antidivisorsrO  =  s       	Avvq\\  aCq55QU5GGGqs1u  q::::A:::::!a%:GGGqs1u  q::::A:::::!a%:GGG r*   c                 z    t          t          t          |                               }|r|nt          |          S )av  
    Return all antidivisors of n sorted from 1..n by default.

    Antidivisors [1]_ of n are numbers that do not divide n by the largest
    possible margin.  If generator is True an unordered generator is returned.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import antidivisors
    >>> antidivisors(24)
    [7, 16]

    >>> sorted(antidivisors(128, generator=True))
    [3, 5, 15, 17, 51, 85]

    See Also
    ========

    primefactors, factorint, divisors, divisor_count, antidivisor_count

    References
    ==========

    .. [1] definition is described in https://oeis.org/A066272/a066272a.html

    )rO  r   r   rN   rG  s      r(   antidivisorsrQ  U  s2    8 
vc!ff~~	&	&B*22r

*r*   c                     t          t          |                     } | dk    rdS t          d| z  dz
            t          d| z  dz             z   t          |           z   t          | d          z
  dz
  S )a  
    Return the number of antidivisors [1]_ of ``n``.

    Parameters
    ==========

    n : integer

    Examples
    ========

    >>> from sympy.ntheory.factor_ import antidivisor_count
    >>> antidivisor_count(13)
    4
    >>> antidivisor_count(27)
    5

    See Also
    ========

    factorint, divisors, antidivisors, divisor_count, totient

    References
    ==========

    .. [1] formula from https://oeis.org/A066272

    rF   r   r   r   )r   r   r=  rK  s    r(   antidivisor_countrS  u  sz    < 	s1vvAAvvq1q!!M!A#'$:$::a(A../123 3r*   zfThe `sympy.ntheory.factor_.totient` has been moved to `sympy.functions.combinatorial.numbers.totient`.z1.13z%deprecated-ntheory-symbolic-functions)deprecated_since_versionactive_deprecations_targetc                 $    ddl m}  ||           S )ax  
    Calculate the Euler totient function phi(n)

    .. deprecated:: 1.13

        The ``totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.totient`
        instead. See its documentation for more information. See
        :ref:`deprecated-ntheory-symbolic-functions` for details.

    ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
    that are relatively prime to n.

    Parameters
    ==========

    n : integer

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import totient
    >>> totient(1)
    1
    >>> totient(25)
    20
    >>> totient(45) == totient(5)*totient(9)
    True

    See Also
    ========

    divisor_count

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
    .. [2] https://mathworld.wolfram.com/TotientFunction.html

    r   )totient)%sympy.functions.combinatorial.numbersrW  )r-   _totients     r(   rW  rW    s&    Z JIIIII8A;;r*   zvThe `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.c                 $    ddl m}  ||           S )av  
    Calculate the Carmichael reduced totient function lambda(n)

    .. deprecated:: 1.13

        The ``reduced_totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.reduced_totient`
        instead. See its documentation for more information. See
        :ref:`deprecated-ntheory-symbolic-functions` for details.

    ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
    `k^m \equiv 1 \mod n` for all k relatively prime to n.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import reduced_totient
    >>> reduced_totient(1)
    1
    >>> reduced_totient(8)
    2
    >>> reduced_totient(30)
    4

    See Also
    ========

    totient

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Carmichael_function
    .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html

    r   )reduced_totient)rX  r[  )r-   _reduced_totients     r(   r[  r[    s)    P ZYYYYYAr*   zrThe `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.c                 &    ddl m}  || |          S )a?  
    Calculate the divisor function `\sigma_k(n)` for positive integer n

    .. deprecated:: 1.13

        The ``divisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.divisor_sigma`
        instead. See its documentation for more information. See
        :ref:`deprecated-ntheory-symbolic-functions` for details.

    ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^\omega p_i^{m_i},

    then

    .. math ::
        \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
        + p_i^{m_ik}).

    Parameters
    ==========

    n : integer

    k : integer, optional
        power of divisors in the sum

        for k = 0, 1:
        ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
        ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``

        Default for k is 1.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
    >>> divisor_sigma(18, 0)
    6
    >>> divisor_sigma(39, 1)
    56
    >>> divisor_sigma(12, 2)
    210
    >>> divisor_sigma(37)
    38

    See Also
    ========

    divisor_count, totient, divisors, factorint

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Divisor_function

    r   )divisor_sigma)rX  r^  )r-   rB   func_divisor_sigmas      r(   r^  r^    s+    B ZYYYYYa###r*   r-   rB   returnc                    dk    r=t          j        d t          |                                           D                       S t          j        fdt          |                                           D                       S )a   Calculate the divisor function `\sigma_k(n)` for positive integer n

    Parameters
    ==========

    n : int
        positive integer
    k : int
        nonnegative integer

    See Also
    ========

    sympy.functions.combinatorial.numbers.divisor_sigma

    r   c              3       K   | ]	}|d z   V  
dS rl   r$   )r%   rs   s     r(   r)   z!_divisor_sigma.<locals>.<genexpr>M  s&      >>1Q>>>>>>r*   c              3   L   K   | ]\  }}||d z   z  z  d z
  |z  d z
  z  V  dS rl   r$   )r%   rc   rs   rB   s      r(   r)   z!_divisor_sigma.<locals>.<genexpr>N  sE      WW$!Qa!QU)nq(AqD1H5WWWWWWr*   )rv   rw   r+   r   rO   )r-   rB   s    `r(   _divisor_sigmard  ;  sv    " 	Avvy>>	!(;(;(=(=>>>>>>9WWWW)A,,BTBTBVBVWWWWWWr*   c                     t          |           } t          |          }| dk    rt          d          |dk    rt          d          d}t          |                                           D ]\  }}||||z  z  z  }|S )a  
    Calculate core(n, t) = `core_t(n)` of a positive integer n

    ``core_2(n)`` is equal to the squarefree part of n

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^\omega p_i^{m_i},

    then

    .. math ::
        core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.

    Parameters
    ==========

    n : integer

    t : integer
        core(n, t) calculates the t-th power free part of n

        ``core(n, 2)`` is the squarefree part of ``n``
        ``core(n, 3)`` is the cubefree part of ``n``

        Default for t is 2.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import core
    >>> core(24, 2)
    6
    >>> core(9424, 3)
    1178
    >>> core(379238)
    379238
    >>> core(15**11, 10)
    15

    See Also
    ========

    factorint, sympy.solvers.diophantine.diophantine.square_factor

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core

    r   zn must be a positive integerr   zt must be >= 2)r   r_   r+   rO   )r-   r   rN  rc   rs   s        r(   corerf  Q  s    l 	q		Aq		AAvv7888	
a)***aLL&&(( 	 	DAqQUOAAr*   ztThe `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.c                 &    ddl m}  || |          S )aL  
    Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n

    .. deprecated:: 1.13

        The ``udivisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.udivisor_sigma`
        instead. See its documentation for more information. See
        :ref:`deprecated-ntheory-symbolic-functions` for details.

    ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^\omega p_i^{m_i},

    then

    .. math ::
        \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).

    Parameters
    ==========

    k : power of divisors in the sum

        for k = 0, 1:
        ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
        ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``

        Default for k is 1.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import udivisor_sigma
    >>> udivisor_sigma(18, 0)
    4
    >>> udivisor_sigma(74, 1)
    114
    >>> udivisor_sigma(36, 3)
    47450
    >>> udivisor_sigma(111)
    152

    See Also
    ========

    divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
    factorint

    References
    ==========

    .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html

    r   )udivisor_sigma)rX  rh  )r-   rB   _udivisor_sigmas      r(   rh  rh    s*    | XWWWWW?1a   r*   zfThe `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.c                 $    ddl m}  ||           S )a  
    Calculate the number of distinct prime factors for a positive integer n.

    .. deprecated:: 1.13

        The ``primenu`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primenu`
        instead. See its documentation for more information. See
        :ref:`deprecated-ntheory-symbolic-functions` for details.

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^k p_i^{m_i},

    then ``primenu(n)`` or `\nu(n)` is:

    .. math ::
        \nu(n) = k.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import primenu
    >>> primenu(1)
    0
    >>> primenu(30)
    3

    See Also
    ========

    factorint

    References
    ==========

    .. [1] https://mathworld.wolfram.com/PrimeFactor.html

    r   )primenu)rX  rk  )r-   _primenus     r(   rk  rk    s&    X JIIIII8A;;r*   zlThe `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.c                 $    ddl m}  ||           S )aR  
    Calculate the number of prime factors counting multiplicities for a
    positive integer n.

    .. deprecated:: 1.13

        The ``primeomega`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primeomega`
        instead. See its documentation for more information. See
        :ref:`deprecated-ntheory-symbolic-functions` for details.

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^k p_i^{m_i},

    then ``primeomega(n)``  or `\Omega(n)` is:

    .. math ::
        \Omega(n) = \sum_{i=1}^k m_i.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import primeomega
    >>> primeomega(1)
    0
    >>> primeomega(20)
    3

    See Also
    ========

    factorint

    References
    ==========

    .. [1] https://mathworld.wolfram.com/PrimeFactor.html

    r   )
primeomega)rX  rn  )r-   _primeomegas     r(   rn  rn  	  s&    Z POOOOO;q>>r*   c                     t          |           }|dk     rt          d          |dk    rt          d          t          |dz
           S )a  Returns the exponent ``i`` for the nth Mersenne prime (which
    has the form `2^i - 1`).

    Examples
    ========

    >>> from sympy.ntheory.factor_ import mersenne_prime_exponent
    >>> mersenne_prime_exponent(1)
    2
    >>> mersenne_prime_exponent(20)
    4423
    r   z?nth must be a positive integer; mersenne_prime_exponent(1) == 23   zGThere are only 51 perfect numbers; nth must be less than or equal to 51)r   r_   r   )nthr-   s     r(   mersenne_prime_exponentrs  7	  sN     	sA1uuZ[[[2vvbccc#AE**r*   c                     t                       dk     rdS  dz  dk    rO                                 dz   dz	  }d|dz
  z  d|z  dz
  z   k    rdS |t          v pt          d|z  dz
            S  ddz  k     rdS  dz  dk    rdS t	           fdd	D                       rdS t                     dk    }|r,t          t          d
t                     z                      |S )aC  Returns True if ``n`` is a perfect number, else False.

    A perfect number is equal to the sum of its positive, proper divisors.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
    >>> from sympy.ntheory.factor_ import is_perfect, divisors
    >>> is_perfect(20)
    False
    >>> is_perfect(6)
    True
    >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
    True

    References
    ==========

    .. [1] https://mathworld.wolfram.com/PerfectNumber.html
    .. [2] https://en.wikipedia.org/wiki/Perfect_number

    r   FrF   r   r   i  i   c              3   0   K   | ]\  }}|z  |k    V  d S r#   r$   )r%   r&   r   r-   s      r(   r)   zis_perfect.<locals>.<genexpr>s	  s/      
C
C$!Q1q5A:
C
C
C
C
C
Cr*   ))   r   )i  u   )iD  Q   a  In 1888, Sylvester stated: "
            ...a prolonged meditation on the subject has satisfied
            me that the existence of any one such [odd perfect number]
            -- its escape, so to say, from the complex web of conditions
            which hem it in on all sides -- would be little short of a
            miracle." I guess SymPy just found that miracle and it
            factors like this: %s)	r   r   r   r   ra   	abundancer_   r   r+   )r-   r&   results   `  r(   
is_perfectr|  L	  s.   0 	q		A1uuu1uzz\\^^aA%!a%La1f\*a//5,,K0A!Q$(0K0KK 	2t8||u3w!||u

C
C
C
C"B
C
C
CCC u q\\QF 6 %% (1||%4 5 5 6 6 	6 Mr*   c                 ,    t          |           d| z  z
  S )aE  Returns the difference between the sum of the positive
    proper divisors of a number and the number.

    Examples
    ========

    >>> from sympy.ntheory import abundance, is_perfect, is_abundant
    >>> abundance(6)
    0
    >>> is_perfect(6)
    True
    >>> abundance(10)
    -2
    >>> is_abundant(10)
    False
    rF   rd  rK  s    r(   rz  rz  	  s    " !q1u$$r*   c                     t          |           } t          |           rdS | dz  dk    pt          t          |           dk              S )a  Returns True if ``n`` is an abundant number, else False.

    A abundant number is smaller than the sum of its positive proper divisors.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import is_abundant
    >>> is_abundant(20)
    True
    >>> is_abundant(15)
    False

    References
    ==========

    .. [1] https://mathworld.wolfram.com/AbundantNumber.html

    Fr   r   r   r|  rH   rz  rK  s    r(   is_abundantr  	  sH    ( 	q		A!}} uq5A:/illQ.///r*   c                     t          |           } t          |           rdS t          t          |           dk               S )a  Returns True if ``n`` is a deficient number, else False.

    A deficient number is greater than the sum of its positive proper divisors.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import is_deficient
    >>> is_deficient(20)
    False
    >>> is_deficient(15)
    True

    References
    ==========

    .. [1] https://mathworld.wolfram.com/DeficientNumber.html

    Fr   r  rK  s    r(   is_deficientr  	  s;    ( 	q		A!}} u	!q !!!r*   c                 h    | |k    o,| |z   t          |           cxk    ot          |          k    nc S )a(  Returns True if the numbers `m` and `n` are "amicable", else False.

    Amicable numbers are two different numbers so related that the sum
    of the proper divisors of each is equal to that of the other.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
    >>> from sympy.ntheory.factor_ import is_amicable
    >>> is_amicable(220, 284)
    True
    >>> divisor_sigma(220) == divisor_sigma(284)
    True

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Amicable_numbers

    r~  )r&   r-   s     r(   is_amicabler  	  sC    , 6Ea!e~a00EEEEN14E4EEEEEEr*   c                       dk     rdS  dz  oIt                      o9t           fdt                                                     D                       S )z Returns True if the numbers `n` is Carmichael number, else False.

    Parameters
    ==========

    n : Integer

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Carmichael_number
    .. [2] https://oeis.org/A002997

    1  FrF   c              3   H   K   | ]\  }}|d k    od z
  |d z
  z  dk    V  dS )r   r   Nr$   )r%   rc   rs   r-   s      r(   r)   z is_carmichael.<locals>.<genexpr>	  sB      RRTQqAv01q5QU+q0RRRRRRr*   )r   ra   r+   rO   rK  s   `r(   is_carmichaelr  	  sh     	3wwuq5 S^ SRRRRYq\\=O=O=Q=QRRRRRSr*   c                     d| cxk    r|k    rEn nB| dz  dk    rd t          | dz   |d          D             S d t          | |d          D             S t          d          )zl Returns a list of the number of Carmichael in the range

    See Also
    ========

    is_carmichael

    r   rF   c                 0    g | ]}t          |          |S r$   r  r4   s     r(   r6   z4find_carmichael_numbers_in_range.<locals>.<listcomp>
  s%    FFF!]15E5EFAFFFr*   r   c                 0    g | ]}t          |          |S r$   r  r4   s     r(   r6   z4find_carmichael_numbers_in_range.<locals>.<listcomp>

  s%    BBB!q1A1ABABBBr*   zQThe provided range is not valid. x and y must be non-negative integers and x <= y)r   r_   )rA   rN  s     r(    find_carmichael_numbers_in_ranger  	  s{     	A{{{{{{{{{q5A::FFuQUAq11FFFFBBuQ1~~BBBBlmmmr*   c                     d}g }t          |          | k     r<t          |          r|                    |           |dz  }t          |          | k     <|S )z Returns the first n Carmichael numbers.

    Parameters
    ==========

    n : Integer

    See Also
    ========

    is_carmichael

    r  rF   )r   r  rR   )r-   r5   carmichaelss      r(   find_first_n_carmichaelsr  
  sk     	AK
k

Q

 	"q!!!	Q k

Q


 r*   c                     t          t          |                     }t          |          }|dk    rt          d          |dk    rdS d|dz
  |dz
  z  z   S )a  
    Returns the additive digital root of a natural number ``n`` in base ``b``
    which is a single digit value obtained by an iterative process of summing
    digits, on each iteration using the result from the previous iteration to
    compute a digit sum.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import dra
    >>> dra(3110, 12)
    8

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Digital_root

    r   (Base should be an integer greater than 1r   )r   r   r_   )r-   r   r   s      r(   drar  (
  s^    * fQii..Cq		AAvvCDDD
axxqqQU##$r*   c                     t          t          |                     } t          |          }|dk    rt          d          | |k    r6d}| dk    r&t          | |          \  } }|dk    rdS ||z  }| dk    &|} | |k    6| S )a  
    Returns the multiplicative digital root of a natural number ``n`` in a given
    base ``b`` which is a single digit value obtained by an iterative process of
    multiplying digits, on each iteration using the result from the previous
    iteration to compute the digit multiplication.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import drm
    >>> drm(9876, 10)
    0

    >>> drm(49, 10)
    8

    References
    ==========

    .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html

    r   r  r   )r   r   r_   r;  )r-   r   mulr   s       r(   drmr  H
  s    0 	F1IIAq		AAvvCDDD
a%%!ee!Q<<DAqAvvq1HC	 !ee
  a%% Hr*   )r/   r   N)rF   )NTT)rF   r   r   r   NN)r   rF   r   r   )F)NTTTTFNF)NTTTFNF)NF)FF)r   Fr:  )c__doc__collectionsr   rv   sympy.core.containersr   sympy.core.mulr   sympy.core.numbersr   r   sympy.core.intfuncr   sympy.core.powerr
   sympy.core.randomr   sympy.core.singletonr   sympy.external.gmpyr   r   r   r	  r   r   r   r   	primetestr   r   r   generater   r   r   r   sympy.utilities.decoratorr   sympy.utilities.iterablesr   sympy.utilities.miscr   r   ecmr    r.   rM   rd   rg   r   r   r   r   r   r   r  r  r  r  r  r   r
  r   r   r+   r(  r   r6  r   r=  r?  rA  rE  rH  rL  rO  rQ  rS  rW  r[  r^  r3   rd  rf  rh  rk  rn  rs  r|  rz  r  r  r  r  r  r  r  r  r$   r*   r(   <module>r     s    $ # # # # #  & & & & & &       0 0 0 0 0 0 0 0 ) ) ) ) ) )             & & & & & & " " " " " "D D D D D D D D D D D D D D D D D D K K K K K K K K K K 2 2 2 2 2 2 2 2 2 2       0 0 0 0 0 0 - - - - - - 3 3 3 3 3 3 3 3            4 4 4<c c c cL? ? ?D<N <N <N~R& R& R& R&jl l l l^p p p pfW W W Wt, , , ,($ $ $N G4	
C
>
G
>
+d d d dN DHAFi i i iX FJ38:* :* :* :*z8 8 8 8v       F!+ !+ !+ !+H# # # #L9 9 9 92: : : :,  6"+ "+ "+ "+J6 6 6B  0+ + + +@"3 "3 "3H  jBD D D* *	D D*Z  zBD D D% %	D D%P  vBD D D>$ >$ >$	D D>$BX XS XC Xc X X X X,@ @ @ @F  xBD D D;! ;! ;!	D D;!|  jBD D D) )	D D)X  pBD D D* *	D D*Z+ + +*8 8 8v% % %(0 0 04" " "4F F F2S S S*n n n$  2% % %@$ $ $ $ $r*   