
    \h_F                   V   S r SSKJr  SSKJr  SSKJrJr  SSKJ	r	  SSK
r
SSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJrJrJrJrJ r J!r!J"r"  SSK#J$r$J%r%J&r&  SSK'J(r(J)r)J*r*  SSK+J+r+  SSK,J-r-  SSK.J/r/  SSK0J1r1J2r2  SSK3J4r4  S r5SXS jr6S r7S r8SYS jr9SZS jr: " S S\	5      r;\;" SS 9r<S[S! jr=S\S" jr>S]S# jr?S$ r@S%rAS&rBS'rCS(rDS)rES*rFS+rGS,rHSYS- jrI  S^S. jrJ  S_S/ jrKS`S0 jrLS]S1 jrMSaS2 jrNSbS3 jrOS]S4 jrPScS5 jrQS6 rRS]S7 jrSS8 rTS9 rUS]S: jrVS; rW\-" S<S=S>S?9S@ 5       rX\-" SAS=S>S?9SB 5       rY\-" SCS=S>S?9ScSD j5       rZScSdSE jjr[SYSF jr\\-" SGS=S>S?9ScSH j5       r]\-" SIS=S>S?9SJ 5       r^\-" SKS=S>S?9SL 5       r_SM r`SN raSO rbSP rcSQ rdSR reSS rfST rgSU rhSV riSW rjg)ez
Integer factorization
    )annotations)bisect_left)defaultdictOrderedDict)MutableMappingN)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                h   ^ U S:X  a  g[        U 5      m[        T5      [        U4S jT 5       5      4$ )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  2   >#    U  H  oTU   -  v   M     g 7fN ).0mfacss     M/var/www/auris/envauris/lib/python3.13/site-packages/sympy/ntheory/factor_.py	<genexpr>smoothness.<locals>.<genexpr>8   s     3dT!W*ds   )	factorintmax)nr*   s    @r+   
smoothnessr1      s2    0 	AvQ<Dt9c3d3333    c                  ^ US;   a  [        U5      nOUS;  a  Sn[        U [        5      (       a  U(       a  U $ 0 nU R                  5        HY  nUR	                  S5      S   R	                  S5      S   R	                  S5       Vs/ s H  n[        U5      PM     snu  mnXtT'   M[     US	La  US
La  U$ [        US
S9$ [        U [        5      (       d
  [        U S
S9nU(       a  SmOSm[        U [        5      (       a  U n	O_U[        [        WR                  5       5       V
Vs/ s H*  u  pU
[        U/[        [        X-   5      5      -   5      4PM,     snn
U4S jS94n	US
L d  US	La  [        U 5      [
        [        4;   a  U	$ / nU	S    H=  n[        U5      nUR!                  SU5        UR#                  S[        U5      -  5        M?     SR%                  U5      $ s  snf s  snn
f )a  
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   )TFNhasr   =r   z**TF)visualc                   > U S   T   U S   4$ Nr   r   r'   )xks    r+   <lambda>smoothness_p.<locals>.<lambda>   s    qtAw!or2   key   z#p**i=%i**%i has p%+i B=%i, B-pow=%i
)bool
isinstancestr
splitlinessplitintsmoothness_ptupler.   sortedlistitemsr1   typer	   r    insertappendjoin)r0   r)   powerr6   dliivr*   rvfMlinesdatr;   s                 @r+   rH   rH   ;   s   z f	}	$!SH,,.BHHUOA&,,S1!4::4@B@  !CF@BDAqaD ! &"5HAe,,5!!5)!U%)$**,%79%7TQ d:ae+<&= =>@%79 67 8
 6-DGSz4I	E!ucl

1a:U3ZGH  99U9B 9s   G$1G$c                    [        U 5      [        U5      pUS:X  a  [        SU-  5      e[        X5      S   $ ! [         Ga    SSKJn  [	        S X4 5       5      (       Gad  [        U 5      n [        U5      nU R                  S:X  av  UR                  S:X  a#  [        U R                  UR                  5      * s $ [        U R                  UR                  5      [        U R                  UR                  5      -
  s $ U R                  S:X  a"  [        U R                  UR                  5      s $ [        [        U R                  UR                  5      [        U R                  UR                  5      5      n[        [        U R                  UR                  5      [        U R                  UR                  5      5      nX4-
  s $ [        U [        [        45      (       a_  [        X5      (       aO  [        UR                  S   [        5      (       a-  UR                  S   S:  a  [        XR                  S   5      s $ [        SU < SU< 35      ef = f)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   #    U  H  n[        U[        [        45      v   M     g 7fr&   )rC   r   r
   )r(   rT   s     r+   r,   multiplicity.<locals>.<genexpr>   s     Efz!j(344fs   #%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minrC   r   r   argsmultiplicity_in_factorialr   )rd   r0   r]   likecrosss        r+   re   re      s   BPay&)16 	AvTWXYZZ!<?9  PFEqfEEEAAssax33!8(acc222#ACC-QSS!##0FFF#ACC-- acc* acc*,  acc* acc*, |#Z1221((166!9g..q	Q,Qq	::ANOO1Ps+   9 BI<AI?0I1BIA8IIc                J  ^ [        U 5      [        T5      sn mU S::  a  [        SU -  5      eTS:  a  [        ST-  5      e[        [        5      n[	        U 5      R                  5        H  u  p4[        X2U   5      X$'   M     [        U4S jUR                  5        5       5      $ )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  p   >#    U  H+  u  pTU-   [        [        TU5      5      -
  US -
  -  U-  v   M-     g7fr   N)sumr   )r(   rU   r;   r0   s      r+   r,   ,multiplicity_in_factorial.<locals>.<genexpr>  s5     M941AF1aL))QU3Q69s   36)r!   r`   r   rG   r.   rL   r/   rf   )rd   r0   rW   r;   rU   s    `   r+   rh   rh      s    T !9fQiDAqAv<q@BB1u@1DFF
 	CA!""$1d| % M1779MMMr2   c           	       ^^ U S::  a  g0 nSmSnS nU S::  ae  [        X SSU5      S   n U S:  a  g[        UR                  5       6 mTS:X  a  g[        R                  " U4S jUR                  5        5       5      T4$ US:  a\  [        U 5      mT(       aH  TS:X  a  gU T-  n TUS	'   U S:X  a  S	T4$ [        U T5      u  pVU(       a  S	U-  T4$ [        T5      (       a  gSnU S
-  S:X  a)  [        U S	5      u  pVU(       a  Un US-  nOOU S
-  S:X  a  M)  XS-  :  a
  U" XTU5      $ U R                  5       S-  S-   nX:  a  [        X5       H  n[        X5      u  pYU	(       d  M  Un X-  n	[        TU	5      mTS:X  a    gXU'   U S:X  a2  [        R                  " U4S jUR                  5        5       5      T4s  $ TS:X  d  TT:  d  M}  Tm[        X-  T5      u  pVU(       a5  U[        R                  " U4S jUR                  5        5       5      -  T4s  $ [        T5      (       d  M    g   UnXS-  :  a
  U" XTU5      $ T(       a/  [        [        T[        T5      -	  5      R                  5       5      n
O,[        S[        [        R                   " X5      5      S	-   5      n
[        R"                  " U 5      nUS-  nU
 H  nX:  aV   [%        S	X-  5      n[        US-   5      n['        X-
  5      S:  a%  X-  U :X  a  Un X8-  n[        R"                  " U 5      nOO7MU   [        X5      u  pVU(       a  Un X8-  n[        R"                  " U 5      nOOM4  XUS	-   -  :  d  M    O   U" XTU5      $ )a9  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U5      mTS:X  a  gX1U '   [        R                  " U4S jUR                  5        5       5      T4$ )Nr   Fc              3  6   >#    U  H  u  pXT-  -  v   M     g 7fr&   r'   r(   rd   egs      r+   r,   /_perfect_power.<locals>.done.<locals>.<genexpr>I       ?tqT   )r   mathprodrL   )r0   factorsrv   multis     ` r+   done_perfect_power.<locals>.doneD  s?    5M6
yy?w}}??BBr2   i@B   c              3  6   >#    U  H  u  pXT-  -  v   M     g 7fr&   r'   rt   s      r+   r,   !_perfect_power.<locals>.<genexpr>S  rx   ry   r@            c              3  6   >#    U  H  u  pXT-  -  v   M     g 7fr&   r'   )r(   rd   ru   _gs      r+   r,   r     s!      %E4CDA &'BZ4Cry   c              3  6   >#    U  H  u  pXT-  -  v   M     g 7fr&   r'   rt   s      r+   r,   r     s!      -I8G ./AY8Gry   (         ?{Gz?)_factorint_smallr   valuesrz   r{   rL   r   r   r   
bit_lengthr   r   rJ   r.   keysrG   loglog2powabs)r0   next_pr|   r}   r~   r)   _exacttf_maxrd   t
prime_iterlogn	thresholdbrbr   rv   s                  @@r+   _perfect_powerr   "  s   6 	AvG	AEC 	I~Wv>qAq5!"6yy?w}}??BB zaLAv!GAGAJAv!t "!QK	Q36MQZZ  a%1*!QK	AaKE a%1* 	19}A5)) \\^R"$FF+A!<DAq
AY7 
699 %E4;MMO%E EFHI I!VrAvA %ah 2IA 499 -I8?-I $I  IJK L L $' ,( 19}A5)) 	 Ia9Q<&78==?@
  3txx':#;a#?@
99Q<Dr	I=48$S\rv;%"%1*AJE99Q<D  !!K	AJE99Q<D  A- . Au%%r2   c           	     :	  ^ ^^^^^  T S:  a  Ucq  [        T * SUS9nU(       d  gUu  pVXf* -  nXW-  Xg-  peUS::  a  gU(       d  [        U5      (       a  U* U4$ [        SUS-   5       H  nXh-  S:X  d  M  XVU-  -  * U4s  $    U V	s1 s H  oS-  (       d  M  U	iM     n
n	U
(       d  g[        T * XU5      nU(       a  US   * US   4$ g[        T [        5      (       GaJ  [        T [
        5      (       Gd4  T R                  T R                  pUS:X  a.  [        XX#5      nUSLa  [        R                  US   -  US   4$ S$ [        XS9=n(       d  g[        XS9=n(       d  gXLsu  mm u  mmUUU UU 4S	 jnU(       aU  U V	s/ s H  n	T U	-  S:X  d  M  TU	-  S:X  d  M  U	PM     nn	U(       d  gU(       a  [        U5      O
[        U5      nU" U5      $ [        R                  " T T5      mTS:X  a  gU(       a  U" T5      $ [        U4S
 j[        STS-   5       5       5      nU" U5      $ Ub  [        U5      n[!        T 5      m Uc  U(       a  [#        T 5      $ T S::  a  g[        R$                  " T 5      n['        U5      S-   nT S-  S;   nSU-   nU(       d  [        UU5      nO[)        U V	s/ s H  n	UU	s=::  a  U:  d  M  O  M  U	PM     sn	5      nT S-  S:X  a'  [+        T 5      nU V	s/ s H  oU	-  S:X  d  M  U	PM     nn	U(       a  [-        U5      nU H(  n[/        T U5      u  nnU(       d  M  ['        U5      U4s  $    gU 4S jn[1        U" 5       U5       GH+  u  nnU(       a  T U-  S:X  a  [3        T U5      S   nUS:X  a    g[/        T U5      u  nnU(       d5  T UU-  -  n[        U[5        USS9S9nU(       d    gUu  nnUUU-  -  U-  UnnU(       d$  [7        U5      nUS   U:w  a  UUUS   -  -  US   nn['        U5      U4s  $ X-  S:  a'  SX-  -  n[9        ['        US-   5      U-
  5      S:  a  M  [/        T U5      u  nnU(       d  M  U(       a  [        UX#S9nU(       a  US   UUS   -  nn['        U5      U4s  $    gs  sn	f s  sn	f s  sn	f s  sn	f )a  
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   T)bigfactorFr   rq   r@   )r   c                J   > TTU -  -  nTTU -  -  nTR                  X5      U 4$ )z0Helper to compute final result given an exponent)func)exponentnew_numnew_denden_baseden_expr0   num_basenum_exps      r+   compute_tuple$perfect_power.<locals>.compute_tuple)  s5    7h#67G7h#67G66'+X55r2   c              3  >   >#    U  H  nTU-  S :X  d  M  Uv   M     g7fr   Nr'   )r(   rd   rv   s     r+   r,    perfect_power.<locals>.<genexpr>?  s     ?0qAEQJ0s   	
   )r@   rq   r      c               3  @   >#    STS-  -   n  U v   [        U 5      n M  7fNr@   )r   )rV   r0   s    r+   _factorsperfect_power.<locals>._factorsc  s)     QYH2B    )	generator)
candidatesr   g       @r   r   )perfect_powerr   r   rC   r
   r   rd   rc   r   Oner/   rf   rz   r   nextsetr!   r   r   rG   rJ   r   reversedr   zipr   divisorsprimefactorsr   )!r0   r   r   r   ppr   ru   e2rd   rT   odd_candidatesrc   qqr   valid_candidatesr   max_possible
not_squaremin_possiblerokr   facexactr)   rEEe0r   r   rv   r   r   s!   `                           @@@@@r+   r   r     s   L 	1urtF;BDAbB7AGqAvgajjr1u1q5)5A:6]?A-- * &09Zq5!Z9A2~F;qE62a5=  !Xz!W'='=ssACC16qc:B-/u_AEEBqEM2a5)G%G!!333!!33335070h	6 	6 +5  J:a#*Q;!#3 !"8?!q8H !":  J#),$%#6F2GA ##HHWg&6 ##?Jq!a%0??Q_
 	q	Aca  Av 99Q<Dt9q=LR<'Jz>Ll;

 1
1q/</ / 
 1 2
Q3!8!A%/<ZQ3!8!ZJ<!*-JA!QKEArr1vqy    hj*-Qa#glq#q!AAv Q{HAu sAvI"1!t1LM DAqA;q=!qA!!_a5A:q"Q%x="Q%qAq619 6B;dfA3q3w<!#$t+ A;55!!<Q41Q4qAq619W .Z K :> JL1 =s<   R	R	?RRR*R?RR(R8Rc                      \ rS rSrSrSSS jjrSS jrSS jrSS jrSS jr	SS	 jr
S
 rSS jr\SS j5       r\R                  SS j5       rSSS jjrSS jrSS jrSrg)FactorCachei  aT  Provides a cache for prime factors.
``factor_cache`` is pre-prepared as an instance of ``FactorCache``,
and ``factorint`` internally references it to speed up
the factorization of prime factors.

While cache is automatically added during the execution of ``factorint``,
users can also manually add prime factors independently.

>>> from sympy import factor_cache
>>> factor_cache[15] = 5

Furthermore, by customizing ``get_external``,
it is also possible to use external databases.
The following is an example using http://factordb.com .

.. code-block:: python

    import requests
    from sympy import factor_cache

    def get_external(self, n: int) -> list[int] | None:
        res = requests.get("http://factordb.com/api", params={"query": str(n)})
        if res.status_code != requests.codes.ok:
            return None
        j = res.json()
        if j.get("status") in ["FF", "P"]:
            return list(int(p) for p, _ in j.get("factors"))

    factor_cache.get_external = get_external

Be aware that writing this code will trigger internet access
to factordb.com when calling ``factorint``.

Nc                .    [        5       U l        Xl        g r&   )r   _cachemaxsize)selfr   s     r+   __init__FactorCache.__init__  s    -8]r2   c                ,    [        U R                  5      $ r&   )lenr   r   s    r+   __len__FactorCache.__len__  s    4;;r2   c                    XR                   ;   $ r&   )r   r   r0   s     r+   __contains__FactorCache.__contains__  s    KKr2   c                J    U R                  U5      nUc  [        U S35      eU$ Nz does not exist.)getKeyErrorr   r0   r   s      r+   __getitem__FactorCache.__getitem__  s,    !>aS 0122r2   c                t   SUs=:  a  U::  a  O  OX-  S:X  a  [        U5      (       d  [        U SU 35      e[        U R                  R	                  US5      U5      U R                  U'   U R
                  b@  [        U R                  5      U R
                  :  a  U R                  R                  S5        g g g )Nr   r   z is not a prime factor of F)r   r`   r/   r   r   r   r   popitemr   s      r+   __setitem__FactorCache.__setitem__  s    FaAJ!Ox'A!EFFT[[__Q2F;A<<#DKK(84<<(GKK& )H#r2   c                X    XR                   ;  a  [        U S35      eU R                   U	 g r   )r   r   r   s     r+   __delitem__FactorCache.__delitem__  s*    KKaS 0122KKNr2   c                6    U R                   R                  5       $ r&   )r   __iter__r   s    r+   r   FactorCache.__iter__  s    {{##%%r2   c                "    [        5       U l        g)zClear the cache N)r   r   r   s    r+   cache_clearFactorCache.cache_clear  s    !mr2   c                    U R                   $ )z>Returns the maximum cache size; if ``None``, it is unlimited. )_maxsizer   s    r+   r   FactorCache.maxsize  s     }}r2   c                    Ub  US::  a  [        S5      eXl        UbQ  [        U R                  5      U:  a7  U R                  R	                  S5        [        U R                  5      U:  a  M6  g g g )Nr   z/maxsize must be None or a non-negative integer.F)r`   r   r   r   r   )r   values     r+   r   r     s`    !NOOdkk"U*##E* dkk"U* r2   c                x   U[         R                  S   ::  a1  [         R                  [        [         R                  U5         U:X  a  U$ XR                  ;   a*  U R                  R	                  U5        U R                  U   $ U R                  U5      =n(       a   U R                  X5        U R                  U   $ U$ )zfReturn the prime factor of ``n``.
If it does not exist in the cache, return the value of ``default``.
r7   )r   _listr   r   move_to_endget_externaladd)r   r0   defaultr|   s       r+   r   FactorCache.get  s     B{{;u{{A671<KK##A&;;q>!''**7*HHQ ;;q>!r2   c                H    [        USS9 H  nX0U'   [        X5      u  pM     g )NT)reverse)rJ   r   )r   r0   r|   rd   _s        r+   r   FactorCache.add  s'    .AG!<DAq /r2   c                    g r&   r'   r   s     r+   r   FactorCache.get_external  s    r2   )r   r   r   r&   )r   
int | None)returnrG   )r  rB   )r0   rG   r  rG   )r0   rG   r   rG   )r0   rG   )r  None)r  r  )r   r  r  r  )r0   rG   r|   z	list[int]r  r  )r0   rG   r  zlist[int] | None)__name__
__module____qualname____firstlineno____doc__r   r   r   r   r   r   r   r   propertyr   setterr   r   r   __static_attributes__r'   r2   r+   r   r     sk    !D  '
&$   ^^+ + 
r2   r   r   )r   c                  ^ ^ [        T 5      m T S:  a  [        S5      e[        XC-   5      nUn[        US-   5       H  n	Un
U(       d  UU 4S jnSn U(       a  X:  a  OEUS-  nU" U
5      n
U" U" U5      5      n[	        X-
  T 5      nUS:X  a  M?  UT :X  a  O[        U5      s  $ U" ST S-
  5      nU" ST S-
  5      mSnM     g)ah
  
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

   z pollard_rho should receive n > 4r   c                *   > [        U ST5      T-   T-  $ r   )r   )r:   ar0   s    r+   r<   pollard_rho.<locals>.<lambda>g  s    3q!Q<!+q0r2   r   rq   N)rG   r`   r   ranger   )r0   sr  retriesseed	max_stepsFrandintVrT   Ujrv   s   ` `          r+   pollard_rhor     s    n 	AA1u;<<t~&G	A7Q;0AamFA!A!A$AAE1AAvAvq6MAq1uAq1u'  ( r2   c           	        [        U 5      n U S:  d  US:  a  [        S5      e[        XA-   5      n[        US-   5       H  nUn[        R
                  " SUS-   5       H8  n[        [        R                  " X5      5      n	[        U[        X5      U 5      nM:     [        US-
  U 5      n
SU
s=:  a  U :  a  O  O[        U
5      s  $ U" SU S-
  5      nM     g)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
   rq   z*pollard_pm1 should receive n > 3 and B > 2r   r@   N)
rG   r`   r   r  r   r   rz   r   r   r   )r0   Br  r  r  r  rT   aMrd   ru   rv   s              r+   pollard_pm1r%  {  s    B 	AA1uAEFFtx G
 7Q;!!!QU+ADHHQN#ARQA&B , QNq919q6M Aq1u  r2   c                   U(       a  [        U R                  5       5      n[        U 5      nU H2  nX-  S:X  d  M  X:w  a	  U[        U'   [	        X-  U5      u  pUS-   X'   M4     U(       aI  [        [        U 5      R                  [        W5      5      5       H  n[        [        XU   4-  5        M     [        U5      [        U 5      U:g  4$ )z
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   )rK   r   r   factor_cacher   rJ   r   
differenceprint
factor_msgrG   )	r|   r0   r   verbosefactors0nfactorsrR   r)   r;   s	            r+   _trialr.    s     '7|H5A:v"#Q!&!$DAQGJ  G//H>?A*1:./ @q63w<8+++r2   c           	        U(       a  [        S5        US:X  a  U(       a  [        [        5        gXS-  :  d  [        U5      (       a.  U[        U'   SU [	        U5      '   U(       a  [        [        5        g[        X5      nU(       d  gUu  pXS-  :  d  [        U	5      (       a  U	[        U'   XU	'   OE[        XX4USS9nUR                  5        H%  u  pU(       a  [        [        X4-  5        X-  X'   M'     U(       a  [        [        5        g)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   Tr@   Fr+  )	r)  complete_msgr   r'  rG   r   r.   rL   r*  )r|   r0   limit	use_trialuse_rhouse_pm1r+  r   rd   baseexpr*   r   ru   s                 r+   _check_terminationr8  +  s     %&Av,19}

QA, 	q!AIDai74==Qi'!&(JJLDAjA6)*GJ ! lr2   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 ** %iz0Close factors satisfying Fermat condition found.zFactorization is complete.c                   S nUS-  n[        X5      nUS:  a8  US-  (       d  [        U5      nXS'   X-  n[        X5      nSnUS:  a  U" X5      $ US:  ai  US-  (       dO  US-  nSnUS-  (       d/  US-  nUS-  nUS:X  a  [        US5      u  pX-  nOUS-  (       d  M/  XS'   [        X5      nSnUS:  a  U" X5      $ US	-  n
XJS:  a  S
OSU
-
  -  nSnX:  a  X-  (       a  US-  nOLX-  nSnX-  (       d,  X-  nUS-  nUS:X  a  [        X5      u  pX-  nOX-  (       d  M,  XU'   Sn[        X5      nUS-  nXtS-  :  a  U" X5      $ X-  (       a  US-  nOLX-  nSnX-  (       d,  X-  nUS-  nUS:X  a  [        X5      u  pX-  nOX-  (       d  M,  XU'   Sn[        X5      nUS-  nXtS-  :  a  U" X5      $ X:  a  M  U" X5      $ )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                     X-  U ::  a  X4$ U S4$ )z]return n, d if the sqrt(n) was not reached yet, else
n, 0 indicating that factoring is done.
r   r'   )r0   rR   s     r+   r~   _factorint_small.<locals>.donek  s     3!84K!tr2   r@   rq   r   	   r           r7   r   r"  )rf   r   r   )r|   r0   r2  fail_maxr   r~   limit2
threshold2r)   mmp6failss               r+   r   r   ]  s:    AXFQJz1u!AAJGAQJ>?"z1u!GAA!eaQ7"1aLEAGA !ee AJQJ??" 
!B
!Vrb((FE

:QJELAAjQ7"1-EAGA jj  FOEQJ!	!?" :QJELAAjQ7"1-EAGA jj  FOEQJ!	!?"O 
P ?r2   c	                  ^1 [        U [        5      (       a  [        U 5      n U(       a/  [        XUX4USSS9m1[	        U14S j[        T15       5       / 5      n	U	$ 0 n
U(       a)  [        U [        [        45      (       d  [        XUX4USS9n
Or[        U [        5      (       aF  U R                  5       R                  5        VVs0 s H  u  p[        U5      [        U5      _M     n
nnO[        U [        5      (       a  U n
U
(       a  [        U [        [        45      (       a  [        U
R                  5       5       Hf  n[        U5      (       a  M  U
R                  U5      n[        XX#XFSS9nUR                  5        H   u  pX;   a  X==   X-  -  ss'   M  X-  X'   M"     Mh     U(       d  [        U 5      [        L a  USLa  USLa  U
0 :X  a  [        R                   $ SU
;   a#  U
R                  S5        [        R"                  /nO/ nUR%                  [        U
R                  5       5       Vs/ s H  n['        USS06PM     sn5        [        USS06$ [        U [        [        45      (       a  U
$ U(       d  U(       d  U(       d	  U(       d   eSS	KJn  [        U U5      (       a  [-        U R.                  S   5      nUS
:  a  0 nSn[0        R2                  " SUS-   5       H-  nUS:  a  SUU-  nnUS:w  a  UU-  nUU-  nUS:w  a  M  UUU'   M/     U(       a0  U(       a)  [        U5       H  n[5        [6        UUU   4-  5        M     U(       a  [5        [8        5        U$ U R;                  U5      n [-        U 5      n U(       a  [        U5      nSnU S:  a  [        U * XUXFSS9nSUS'   U$ U(       a  US:  a  U S:X  a  0 $ U S0$ U S:  a"  SS00 SS0SS0SS0SS0SSS.SS0SS0SS0/
U    $ 0 nU(       aP  [=        U 5      n[?        U5      S:  a*  [5        SUSS -  S[?        U5      S-
  -  -   USS -   5        O[5        SU 5        SnSn[A        UU=(       d    U5      nU(       a  [5        [B        SUU4-  5        [E        UU UU5      u  n nU(       a0  U(       a)  [        U5       H  n[5        [6        UUU   4-  5        M     US:X  a,  U S:  a  SU[        U 5      '   U(       a  [5        [8        5        U$ [F        RI                  U 5      =n(       aC  [K        U U5      u  p[        U5      U[        U5      '   [F        RI                  U 5      =n(       a  MC  U(       aF  UU:  a@  U(       a  [5        SU5        [M        UXUX4UU5      (       a  U$ U S:  a  SU[        U 5      '   U$ [M        UXUX4UU5      (       a  U$ [O        U 5      nUS-   nU S-  S:H  US-  -  (       a  US-  nUS-  nUU -
  n[Q        S5       H  n [S        U5      u  n!n"U"(       d  U(       a  [5        [T        5        UU!-
  UU!-   4 HV  n#[        U#XX4US9n$U$R                  5        H  u  pURI                  US5      U-   UU'   M     [F        RW                  U U$5        MX     U(       a  [5        [8        5        Us  $ UUS-   S-  -  nUS-  nM     USU-  n&n%U=(       d    US-   n'Sn( [A        U&U'5      n)U(       ad  U(       a  [5        [X        U%U)4-  5        [0        R2                  " U%U)5      n*[[        UU U*U5      u  n n+U)nU+(       a  [M        UXUX4UU5      (       a  U$ OSn+U&U':  a?  U(       a  [5        SU'5        U S:  a  SU[        U 5      '   U(       a  [5        [8        5        U$ U+(       Gd  U(       a  U(       a  [5        [\        U%U)4-  5        [_        U U%U)S9n,U,(       aR  U,US-  :  d  [        U,5      (       a  U,/n*O[        U,UUUUUUS9n*[[        UU U*SS9u  n n [M        UXUX4UU5      (       a  U$ U(       a  U(       a  [5        [`        SU%U)4-  5        [c        U SU%U)S 9n,U,(       aR  U,US-  :  d  [        U,5      (       a  U,/n*O[        U,UUUUUUS9n*[[        UU U*SS9u  n n [M        UXUX4UU5      (       a  U$ U(S-  n(U(       a  U(S:  a  [e        U 5      S!:  a  O
U&U&S-  n&n%GM   S"n-S#U--  n.Sn/ U(       a  [5        [f        U-U.U/4-  5        [i        U U-U.U/U-S$9n0U0(       aR  U0US-  :  d  [        U05      (       a  U0/n*O[        U0UUUUUUS9n*[[        UU U*SS9u  n n [M        UXUX4UU5      (       a  U$ U-S-  n-S#U--  n.U/S-  n/M  s  snnf s  snf )%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r2  r3  r4  r5  r+  r6   multiplec              3  ~   >#    U  H2  nTU   S :  a	  U/TU   -  O[         R                  U-  /TU   * -  v   M4     g7fr   r   r   )r(   rd   r   s     r+   r,   factorint.<locals>.<genexpr>_  sF      5(31 +.a&1*1#A,1557)c!fW:MM(3s   :=)r2  r3  r4  r5  r+  r6   Tr7   evaluater   r\   r=  r@   r   r   rq   r  )r@   rq   r   2   zFactoring %sNz..(%i other digits)..	Factoringi   iX  zExceeded limit:r"  r2  r3  r4  r5  r+  )r#  r  )r2  r3  r4  r5  use_ecmr+  r0  )r  r  r  r   i'  d   )r  )5rC   r   dictr.   rn   rJ   r	   as_powers_dictrL   rG   rK   r   r   poprM   r   r   NegativeOneextendr   ra   r]   r!   rg   r   r   r)  r*  r1  r   rD   r   rf   trial_int_msgr   r'  r   r   r8  isqrtr  r   
fermat_msgr   	trial_msgr.  pm1_msgr%  rho_msgr   r   ecm_msgr#   )2r0   r2  r3  r4  r5  rQ  r+  r6   rH  
factorlist
factordictr;   rU   r?   ru   rR   rg   rT   r]   r:   r|   r)   rd   rc   snsmallr@  r   sqrt_nr  a2b2r  r   fermatr   r*   lowhigh_limit	iterationhigh_psfound_trialcB1B2
num_curvesr   r   s2                                                    @r+   r.   r.     s	   j !TG)#*#*55J  5(.s568:
JjS$K00q'.'.u>
 
As		$$&(& *.c!fc!fn& 	 (
	At		
jS$K00
)*Cs||s#A#i")5JA	?MQS(M$%CJM	 " + $q'T/$%55LNN2MM?DD$Z%5%5%78:8 !,e,8: 	;D)5))	Ac{	#	#7g55B!Y166!97GA%%aQ/q5a1fqAq&Qa q& 
 0 7A*71:67 )l#N q	Aq	AE
 	1uBe'U< 6I1v	
R AQFQFQFQF!q!fq!fq!f6679 	9 G Vr7R<.2bq6))SWr\:;=?WE F +q!
 EHu~&Emq%223 !UH=IAv7A*71:./ !{q5GCFO,"
"!
"a|a&A "
"!
" %#U+gq%A ANq5GCFO'1Y!GV= = 1XF
A	A
q1u	Q	
AB	aB1XBK	6j!!eQU^ %)0)02 !JJLDA!(Q!2Q!6GAJ )  D) $ l#N
q1ul	Q! ( &C ov"FI
D&! i3,./!!#u-B#GQG<NA{F1'1Y29GV U  UK&='01u"#Al#N 'S%L01Su5619}

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

S&q1:/6/6/6/68 "'1b%@DAq)'1Y*1GVM M& 	Q	yA~*Q-2*=$q&TQ T 
B	RBJ
'RZ001 BJR@	!WV__XvU%.#*#*#*#*, '1b%8DAq!'1Y")GVE E
aVa
) k(6:s    !e)+e/c                  ^ U(       a=  [        XUX4USSS9m[        U4S j[        TR                  5       S S9 5       / 5      nU$ [	        U R
                  XX4US9R                  5       n	[        [        U	5      n	[	        U R                  UUUUUS9R                  5        H  u  pX==   U* -  ss'   M     [        U	5      S:  a	  SU	;   a  U	S	 U(       d  [        U	5      $ SU	;   a#  U	R                  S5        [        R                  /nO/ nUR                  [        U	R                  5       5       Vs/ s H  n[!        US	S06PM     sn5        [#        US	S06$ s  snf )
ad  
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
FrG  c              3     >#    U  H4  u  pTU   S :  a	  U/TU   -  O[         R                  U-  /TU   * -  v   M6     g7fr   rJ  )r(   rd   r  r   s      r+   r,   factorrat.<locals>.<genexpr>  sO      I,H41 +.a&1*1#A,1557)c!fW:MM,Hs   <?c                .    U S   S:  a  U S   $ SU S   -  $ r9   r'   )elems    r+   r<   factorrat.<locals>.<lambda>  s1    ;?7Q; JNa JG=>tAwYJGr2   r>   rP  r   r7   rL  )	factorratrn   rJ   rL   r.   rd   copyr   rG   rc   r   rS  rU  r   rV  rW  r   r	   )ratr2  r3  r4  r5  r+  r6   rH  r_  rW   rd   ru   rg   rT   r   s                 @r+   rx  rx  u  sk   0 I!!%%A  I+1#))+=G,HI KM	N

 #%%u!!	##'46  	CA#%%u$-")")")	+ ,157	3
 	

3 1vza1faDAw7EE"IMM?DD$QWWY/1/ !,e,/1 	2D)5))1s   1Ec                   [        U 5      n UR                  SSXS.5        [        [        SSU 0UD6R	                  5       5      nUSS  Vs/ s H  oUS;  d  M
  UPM     nnU(       a  [        US   5      (       a  XdS   /-  nU$ s  snf )a  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)r6   rH  r2  r+  r0   r7   )r7   r   r   r'   )rG   updaterJ   r.   r   r   )r0   r2  r+  kwargsr|   rW   r  s          r+   r   r     s    ^ 	AA
MMTu!7 8Y--f-2245G DRM9Mqj%8MA9772;''	bk]H 	:s   	BBc              #  
  ^ ^^^#    T S::  a  U(       d  T (       a  Sv   g[        T 5      m[        TR                  5       5      mSUUU4S jjmU(       a  U 4S jT" 5        5        Sh  vN   gT" 5        Sh  vN   g N N7f)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   Nc              3     >^#    U [        T5      :X  a  Sv   g S/m[        TTU       5       H  nTR                  TS   TU    -  5        M     U4S jT" U S-   5       5        S h  vN   g  N7f)Nr   r7   c              3  @   >#    U  H  nT  H	  o"U-  v   M     M     g 7fr&   r'   )r(   rc   rd   powss      r+   r,   -_divisors.<locals>.rec_gen.<locals>.<genexpr>  s     D~!t!At~r   )r   r  rO   )r0   r  r  r`  rl  rec_gens     @r+   r  _divisors.<locals>.rec_gen  sd     B<G3D:be,-DHr!u,- .Dwq1u~DDDs   A"A.&A,'A.c              3  6   >#    U  H  oT:w  d  M
  Uv   M     g 7fr&   r'   )r(   rd   r0   s     r+   r,   _divisors.<locals>.<genexpr>  s     3y!FAAys   		)r   )r.   rJ   r   )r0   properr`  rl  r  s   ` @@@r+   	_divisorsr    sj      	Av!G1J	
!	"BE E 3wy3339 	4s$   A#B)A?*B9B:BBc                f    [        [        [        U 5      5      U5      nU(       a  U$ [        U5      $ )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
)r  r!   r   rJ   )r0   r   r  rV   s       r+   r   r     s*    @ 
6#a&>6	*B2*r
*r2   c                
   U(       d  gUS:w  a  [        X5      u  pU(       a  gU S:X  a  g[        [        U 5      R                  5        VVs/ s H  u  pEUS:  d  M  US-   PM     snn6 n U (       a  U(       a  U S-  n U $ s  snnf )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   )divmodr	   r.   rL   )r0   modulusr  r   r;   rU   s         r+   divisor_countr  4  s{    0 	Aa!Av	! 2 2 4> 4Aea!e 4>?AV	QH ?s   A?
	A?
c                    [        XSS9$ )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   r  )r   )r0   r   s     r+   proper_divisorsr  Z  s    , A488r2   c                    [        XSS9$ )z
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  r  )r  )r0   r  s     r+   proper_divisor_countr  s  s    & D99r2   c              #  L  #    U S::  a  U S:X  a  Sv   g[        U 5      R                  5        VVs/ s H	  u  pX-  PM     nnn[        S[        U5      -  5       H?  nSn[        UR	                  5       5       H  nUS-  (       a  XSU   -  nUS-  nM     Uv   MA     gs  snnf 7f)zHelper function for udivisors which generates the unitary divisors.

Parameters
==========

n : int
    a nonnegative integer

r   Nr@   )r.   rL   r  r   r   )r0   rd   ru   
factorpowsrT   rR   r;   s          r+   
_udivisorsr    s      	Av6G#,Q<#5#5#78#741!$#7J8 1c*o%&q||~&A1u]"!GA '  ' 9s   .B$B A$B$c                d    [        [        [        U 5      5      5      nU(       a  U$ [        U5      $ )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

)r  r!   r   rJ   r0   r   rV   s      r+   	udivisorsr    s(    B 
F3q6N	#B2*r
*r2   c                x    U S:X  a  gS[        [        U 5       Vs/ s H  oS:  d  M
  UPM     sn5      -  $ s  snf )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   r@   r   )r   r.   )r0   rd   s     r+   udivisor_countr    s8    8 	Avcil4l!e1l45554s   	7
7
c              #  X  #    U S::  a  g[        U 5       H  nSU-  nX:  d  M  X-  (       d  M  Uv   M      [        SU -  S-
  5       H$  nXs=:  a  S:  d  M  O  M  X-  (       d  M   Uv   M&     [        SU -  S-   5       H$  nXs=:  a  S:  d  M  O  M  X-  (       d  M   Uv   M&     g7f)z~Helper function for antidivisors which generates the antidivisors.

Parameters
==========

n : int
    a nonnegative integer

r@   Nr   )r  )r0   rR   ys      r+   _antidivisorsr    s      	Avq\aC5QUUG  qs1u:A::!%%G  qs1u:A::!%%G s'   B*B*&B*B*(&B*B*!	B*c                d    [        [        [        U 5      5      5      nU(       a  U$ [        U5      $ )a2  
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

)r  r!   r   rJ   r  s      r+   antidivisorsr    s'    8 
vc!f~	&B2*r
*r2   c                    [        [        U 5      5      n U S::  a  g[        SU -  S-
  5      [        SU -  S-   5      -   [        U 5      -   [        U S5      -
  S-
  $ )an  
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

r@   r   r   r  )r!   r   r  r0   s    r+   antidivisor_countr  "  sf    < 	s1vAAv1q!M!A#'$::a(A./123 3r2   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                    SSK Jn  U" U 5      $ )a  
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.numbersr  )r0   _totients     r+   r  r  F  s    Z JA;r2   zvThe `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.c                    SSK Jn  U" U 5      $ )a  
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)r  r  )r0   _reduced_totients     r+   r  r  w  s    P ZAr2   zrThe `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.c                    SSK Jn  U" X5      $ )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)r  r  )r0   r;   func_divisor_sigmas      r+   r  r    s    B Za##r2   c                   ^ TS:X  a4  [         R                  " S [        U 5      R                  5        5       5      $ [         R                  " U4S j[        U 5      R	                  5        5       5      $ )zCalculate 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  *   #    U  H	  oS -   v   M     g7frm   r'   )r(   ru   s     r+   r,   !_divisor_sigma.<locals>.<genexpr>  s     >(=1Q(=s   c              3  V   >#    U  H  u  pUTUS -   -  -  S -
  UT-  S -
  -  v   M      g7frm   r'   )r(   rd   ru   r;   s      r+   r,   r    s3     WBV$!a!QU)nq(AqD1H5BVs   &))rz   r{   r.   r   rL   )r0   r;   s    `r+   _divisor_sigmar    sP    " 	Avyy>	!(;(;(=>>>99W)A,BTBTBVWWWr2   c                    [        U 5      n [        U5      nU S::  a  [        S5      eUS::  a  [        S5      eSn[        U 5      R                  5        H  u  p4X#XA-  -  -  nM     U$ )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.   rL   )r0   r   r  rd   ru   s        r+   corer    sm    l 	q	Aq	AAv788	
a)**aL&&(DAQUOA )r2   ztThe `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.c                    SSK Jn  U" X5      $ )a  
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)r  r  )r0   r;   _udivisor_sigmas      r+   r  r  A	  s    | X1  r2   zfThe `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.c                    SSK Jn  U" U 5      $ )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)r  r  )r0   _primenus     r+   r  r  	  s    X JA;r2   zlThe `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.c                    SSK Jn  U" U 5      $ )a  
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)r  r  )r0   _primeomegas     r+   r  r  	  s    Z Pq>r2   c                t    [        U 5      nUS:  a  [        S5      eUS:  a  [        S5      e[        US-
     $ )zReturns 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   )nthr0   s     r+   mersenne_prime_exponentr  	  sB     	sA1uZ[[2vbcc#AE**r2   c                  ^  [        T 5      m T S:  a  gT S-  S:X  aM  T R                  5       S-   S-	  nSUS-
  -  SU-  S-
  -  T :w  a  gU[        ;   =(       d    [        SU-  S-
  5      $ T SS-  :  a  gT S-  S:X  a  g[	        U 4S jS	 5       5      (       a  g[        T 5      S:H  nU(       a   [        [        S
[        T 5      -  5      5      eU$ )a  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   Fr@   r   r   i  i   c              3  8   >#    U  H  u  pTU-  U:g  v   M     g 7fr&   r'   )r(   r)   r   r0   s      r+   r,   is_perfect.<locals>.<genexpr> 
  s     
C"B$!1q5A:"Bs   ))   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   rb   	abundancer`   r"   r.   )r0   r)   results   `  r+   
is_perfectr  	  s    0 	q	A1u1uz\\^aA%!a%La1f\*a/,,K0A!Q$(0KK 	2t8|3w!|

C"B
CCC q\QF %% (1|%4 5 6 	6 Mr2   c                $    [        U 5      SU -  -
  $ )a  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
r@   r  r  s    r+   r  r  4
  s    " !q1u$$r2   c                    [        U 5      n [        U 5      (       a  gU S-  S:H  =(       d    [        [        U 5      S:  5      $ )aP  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  rB   r  r  s    r+   is_abundantr  H
  s:    ( 	q	A!}}q5A:/ilQ.//r2   c                h    [        U 5      n [        U 5      (       a  g[        [        U 5      S:  5      $ )aU  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  r  s    r+   is_deficientr  b
  s-    ( 	q	A!}}	!q !!r2   c                j    X:g  =(       a)    X-   [        U 5      s=:H  =(       a    [        U5      :H  $ 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)   r0   s     r+   is_amicabler  |
  s0    , 6Eae~a0EEN14EEEEEr2   c                   ^  T S:  a  gT S-  =(       aC    [        T 5      (       + =(       a,    [        U 4S j[        T 5      R                  5        5       5      $ )zReturns 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  Fr@   c              3  \   >#    U  H!  u  pUS :H  =(       a    TS -
  US -
  -  S:H  v   M#     g7f)r   r   Nr'   )r(   rd   ru   r0   s      r+   r,    is_carmichael.<locals>.<genexpr>
  s3     R=QTQqAv01q5QU+q00=Qs   ),)r   rb   r.   rL   r  s   `r+   is_carmichaelr  
  sK     	3wq5 S^ SRYq\=O=O=QRRSr2   c                "   SU s=::  a  U::  an  O  OkU S-  S:X  a3  [        U S-   US5       Vs/ s H  n[        U5      (       d  M  UPM     sn$ [        XS5       Vs/ s H  n[        U5      (       d  M  UPM     sn$ [        S5      es  snf s  snf )z[Returns a list of the number of Carmichael in the range

See Also
========

is_carmichael

r   r@   r   zQThe provided range is not valid. x and y must be non-negative integers and x <= y)r  r  r`   )r:   r  rT   s      r+    find_carmichael_numbers_in_ranger  
  s|     	A{{q5A:$QUAq1F1!]15EA1FF$Q1~B~!q1AA~BBlmm	 GBs   BBB3Bc                    Sn/ n[        U5      U :  a7  [        U5      (       a  UR                  U5        US-  n[        U5      U :  a  M7  U$ )zoReturns the first n Carmichael numbers.

Parameters
==========

n : Integer

See Also
========

is_carmichael

r  r@   )r   r  rO   )r0   rT   carmichaelss      r+   find_first_n_carmichaelsr  
  sT     	AK
k
Q
q!	Q k
Q

 r2   c                    [        [        U 5      5      n[        U5      nUS::  a  [        S5      eUS:X  a  gSUS-
  U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`   )r0   r   nums      r+   drar  
  sO    * fQi.Cq	AAvCDD
axqQU##$r2   c                    [        [        U 5      5      n [        U5      nUS::  a  [        S5      eX:  a1  SnU S:  a   [        X5      u  pUS:X  a  gX#-  nU S:  a  M   Un X:  a  M1  U $ )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  )r0   r   mulr   s       r+   drmr  
  sx    0 	F1IAq	AAvCDD
%!e!<DAAvHC	 !e
  % Hr2   )r7   r   N)r@   )NTT)r@   r   r    NN)r   r@   r   r  )F)NTTTTFNF)NTTTFNF)NF)FF)r   F)r   )r0   rG   r;   rG   r  rG   )kr  
__future__r   bisectr   collectionsr   r   collections.abcr   rz   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   rY  r   r   r   r   	primetestr   r   r   generater   r   r   r   sympy.utilities.decoratorr   sympy.utilities.iterablesr    sympy.utilities.miscr!   r"   ecmr#   r1   rH   re   rh   r   r   r   r'  r   r%  r.  r8  rX  r[  r]  r\  r^  r*  rZ  r1  r   r.   rx  r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r'   r2   r+   <module>r     s   #  0 *  &  0 )   & "D D D K K 2 2  0 - 3  4<cL?D<N~R&j_Di. iX 4(pfWt,,%P G4	
C
>
G
?
+dN DHAFnb FJ38:*z8v F!+H#L92:,6"+J6B0+@"3H  jBD*	D*Z  zBD%	D%P  vBD>$	D>$BX,@F  xBD;!	D;!|  jBD)	D)X  pBD*	D*Z+*8v%(04"4F2S*n$2%@$r2   