
    wg7                         d Z ddlZddl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 ddlmZmZ dd	Zd
 Zd Z ed      d        Zej                  Zd Zd Zd Zd Zd Zd Zy)ad  
The routines here were removed from numbers.py, power.py,
digits.py and factor_.py so they could be imported into core
without raising circular import errors.

Although the name 'intfunc' was chosen to represent functions that
work with integers, it can also be thought of as containing
internal/core functions that are needed by the classes of the core.
    N)	lru_cache   )sympify)S)gcdlcmsqrtiroot	bit_scan1gcdext)as_int
filldedentc                 b    |dk  rt        d      | syt        t        |       |      \  }}d|z   S )a  Return the number of digits needed to express n in give base.

    Examples
    ========

    >>> from sympy.core.intfunc import num_digits
    >>> num_digits(10)
    2
    >>> num_digits(10, 2)  # 1010 -> 4 digits
    4
    >>> num_digits(-100, 16)  # -64 -> 2 digits
    2


    Parameters
    ==========

    n: integer
        The number whose digits are counted.

    b: integer
        The base in which digits are computed.

    See Also
    ========
    sympy.ntheory.digits.digits, sympy.ntheory.digits.count_digits
    r   zbase must be int greater than 1r   )
ValueErrorinteger_logabs)nbaseets       W/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/core/intfunc.py
num_digitsr      s:    8 ax:;;s1vt$DAqq5L    c                    t        |       } t        |      }|dk  r,t        t        |       |       \  }}|xr |dz  | dk  k(  }||fS |dk  rt        d      | dk  r|dk7  ryt        |  |      \  }}|dfS | dk(  rt        d      | |k  rd| dk(  fS |dk(  r#| j	                         dz
  }|t        |       |k(  fS t        |      }d|z  |k(  r.t        | j	                         dz
        |z  }d||z  z  }||| k(  fS t        j                  t        j                  |       t        j                  |      z        }||z  }|| k  r|dz  }||z  }|| k  r||| kD  z
  || k(  xs ||z  | k(  fS )a  
    Returns ``(e, bool)`` where e is the largest nonnegative integer
    such that :math:`|n| \geq |b^e|` and ``bool`` is True if $n = b^e$.

    Examples
    ========

    >>> from sympy import integer_log
    >>> integer_log(125, 5)
    (3, True)
    >>> integer_log(17, 9)
    (1, False)

    If the base is positive and the number negative the
    return value will always be the same except for 2:

    >>> integer_log(-4, 2)
    (2, False)
    >>> integer_log(-16, 4)
    (0, False)

    When the base is negative, the returned value
    will only be True if the parity of the exponent is
    correct for the sign of the base:

    >>> integer_log(4, -2)
    (2, True)
    >>> integer_log(8, -2)
    (3, False)
    >>> integer_log(-8, -2)
    (3, True)
    >>> integer_log(-4, -2)
    (2, False)

    See Also
    ========
    integer_nthroot
    sympy.ntheory.primetest.is_square
    sympy.ntheory.factor_.multiplicity
    sympy.ntheory.factor_.perfect_power
    r      r   zbase must be 2 or more)r   FFzn cannot be 0)
r   r   r   r   
bit_lengthtrailingintmathfloorlog10)r   br   r   n_ds         r   r   r   :   s   T 	q	Aq	A1u3q6A2&1 "!a%AE"!tAv1221u6A2q!1%xAv))1u!q&yAvLLNQ(1+"""A!tqy"#Q&1Q3Z"'z

4::a=4::a=01A	
aB
'	Q
a ' Q<"'/RUaZ00r   c                 0    | syt        t        |             S )aG  Count the number of trailing zero digits in the binary
    representation of n, i.e. determine the largest power of 2
    that divides n.

    Examples
    ========

    >>> from sympy import trailing
    >>> trailing(128)
    7
    >>> trailing(63)
    0

    See Also
    ========
    sympy.ntheory.factor_.multiplicity

    r   )r   r   r   s    r   r   r      s    & SVr   i   c                      t        |       dk  rt        dt        |       z        t        t        t	        t
        |              S )a  Computes nonnegative integer greatest common divisor.

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

    The algorithm is based on the well known Euclid's algorithm [1]_. To
    improve speed, ``igcd()`` has its own caching mechanism.
    If you do not need the cache mechanism, using ``sympy.external.gmpy.gcd``.

    Examples
    ========

    >>> from sympy import igcd
    >>> igcd(2, 4)
    2
    >>> igcd(5, 10, 15)
    5

    References
    ==========

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

    r   z,igcd() takes at least 2 arguments (%s given))len	TypeErrorr   
number_gcdmapr   argss    r   igcdr.      s;    4 4y1}FTRSSz3vt,-..r   c                    t        t        |             t        t        |            }} | |k  r|| }} dt        j                  j                  z  }| j                         |kD  r|dk7  r| j                         |z
  }t        | |z	        t        ||z	        }}d\  }}}}		 ||z   dk  rn|||z   ||z   z  }
||
|z  z
  ||
|	z  z
  }}||z   dk  rnX||}}||	||
|z  z
  |f\  }}}}	||	z   dk  rn:||z   ||	z   z  }
||
|z  z
  ||
|z  z
  }}||z   dk  rn||}}||	|||
|	z  z
  f\  }}}}	|dk(  r|| |z  }} || z  ||z  z   || z  |	|z  z   }} | j                         |kD  r|dk7  r|r
|| |z  }} |r
| S )a  Computes greatest common divisor of two integers.

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

    Euclid's algorithm for the computation of the greatest
    common divisor ``gcd(a, b)``  of two (positive) integers
    $a$ and $b$ is based on the division identity
    $$ a = q \times b + r$$,
    where the quotient  $q$  and the remainder  $r$  are integers
    and  $0 \le r < b$. Then each common divisor of  $a$  and  $b$
    divides  $r$, and it follows that  ``gcd(a, b) == gcd(b, r)``.
    The algorithm works by constructing the sequence
    r0, r1, r2, ..., where  r0 = a, r1 = b,  and each  rn
    is the remainder from the division of the two preceding
    elements.

    In Python, ``q = a // b``  and  ``r = a % b``  are obtained by the
    floor division and the remainder operations, respectively.
    These are the most expensive arithmetic operations, especially
    for large  a  and  b.

    Lehmer's algorithm [1]_ is based on the observation that the quotients
    ``qn = r(n-1) // rn``  are in general small integers even
    when  a  and  b  are very large. Hence the quotients can be
    usually determined from a relatively small number of most
    significant bits.

    The efficiency of the algorithm is further enhanced by not
    computing each long remainder in Euclid's sequence. The remainders
    are linear combinations of  a  and  b  with integer coefficients
    derived from the quotients. The coefficients can be computed
    as far as the quotients can be determined from the chosen
    most significant parts of  a  and  b. Only then a new pair of
    consecutive remainders is computed and the algorithm starts
    anew with this pair.

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm

    r   r   )r   r   r   r   )r   r   sysint_infobits_per_digitr   r   )ar"   nbitsr   xyABCDqx_qyB_qDA_qCs                 r   igcd_lehmerr?      s   X vay>3vay>qA1u!1 +++E
,,.5
 Q!V LLNU"16{CQK1  
1a6 1uzQAE"A
 QUAAI$Dd{Q dqAAq1q5y$.JAq!Q 1uzQAE"AQUAAI$Dd{QdqAAtQQY.JAq!Qq z 6 a!eqA 1uq1u}a!ea!em1e ,,.5
 Q!Vj !a%1  Hr   c                      t        |       dk  rt        dt        |       z        t        t        t	        t
        |              S )zComputes integer least common multiple.

    Examples
    ========

    >>> from sympy import ilcm
    >>> ilcm(5, 10)
    10
    >>> ilcm(7, 3)
    21
    >>> ilcm(5, 10, 15)
    30

    r   z,ilcm() takes at least 2 arguments (%s given))r(   r)   r   
number_lcmr+   r   r,   s    r   ilcmrB   V  s;     4y1}FTRSSz3vt,-..r   c                 Z    | s|syt        t        |       t        |            \  }}}|||fS )a0  Returns x, y, g such that g = x*a + y*b = gcd(a, b).

    Examples
    ========

    >>> from sympy.core.intfunc import igcdex
    >>> igcdex(2, 3)
    (-1, 1, 1)
    >>> igcdex(10, 12)
    (-1, 1, 2)

    >>> x, y, g = igcdex(100, 2004)
    >>> x, y, g
    (-20, 1, 4)
    >>> x*100 + y*2004
    4

    )r   r   r   )r   r   )r3   r"   gr5   r6   s        r   igcdexrE   j  s1    & SVSV$GAq!a7Nr   c                    d}	 t        |       t        |      }} |dk7  r|dk7  rt        | |      \  }}}|dk(  r||z  }|t        d| d|d      |S # t        $ r t        |       t        |      }} | j                  r|j                  st        t        d            |dkD  }|t        j                  t        j                  fvrt        d|z        |rd| z  }Y w xY w)	a  
    Return the number $c$ such that, $a \times c = 1 \pmod{m}$
    where $c$ has the same sign as $m$. If no such value exists,
    a ValueError is raised.

    Examples
    ========

    >>> from sympy import mod_inverse, S

    Suppose we wish to find multiplicative inverse $x$ of
    3 modulo 11. This is the same as finding $x$ such
    that $3x = 1 \pmod{11}$. One value of x that satisfies
    this congruence is 4. Because $3 \times 4 = 12$ and $12 = 1 \pmod{11}$.
    This is the value returned by ``mod_inverse``:

    >>> mod_inverse(3, 11)
    4
    >>> mod_inverse(-3, 11)
    7

    When there is a common factor between the numerators of
    `a` and `m` the inverse does not exist:

    >>> mod_inverse(2, 4)
    Traceback (most recent call last):
    ...
    ValueError: inverse of 2 mod 4 does not exist

    >>> mod_inverse(S(2)/7, S(5)/2)
    7/2

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
    .. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
    Nr   z
                Expected numbers for arguments; symbolic `mod_inverse`
                is not implemented
                but symbolic expressions can be handled with the
                similar function,
                sympy.polys.polytools.invertz*m > 1 did not evaluate; try to simplify %szinverse of z (mod z) does not exist)
r   rE   r   r   	is_numberr)   r   r   truefalse)r3   mcr5   _rD   bigs          r   mod_inverserO     s    N 	Aay&)16a2gQlGAq!AvE& 	yAqIJJH)  qz71:10	 	 !eqvvqww''IAMNNAA#s   :A BCCc                 \    | dk  rt        d      t        t        t        |                   S )af   Return the largest integer less than or equal to `\sqrt{n}`.

    Parameters
    ==========

    n : non-negative integer

    Returns
    =======

    int : `\left\lfloor\sqrt{n}\right\rfloor`

    Raises
    ======

    ValueError
        If n is negative.
    TypeError
        If n is of a type that cannot be compared to ``int``.
        Therefore, a TypeError is raised for ``str``, but not for ``float``.

    Examples
    ========

    >>> from sympy.core.intfunc import isqrt
    >>> isqrt(0)
    0
    >>> isqrt(9)
    3
    >>> isqrt(10)
    3
    >>> isqrt("30")
    Traceback (most recent call last):
        ...
    TypeError: '<' not supported between instances of 'str' and 'int'
    >>> from sympy.core.numbers import Rational
    >>> isqrt(Rational(-1, 2))
    Traceback (most recent call last):
        ...
    ValueError: n must be nonnegative

    r   zn must be nonnegative)r   r   r	   r&   s    r   isqrtrQ     s+    V 	1u011tCF|r   c                 ^    t        t        |       t        |            \  }}t        |      |fS )a@  
    Return a tuple containing x = floor(y**(1/n))
    and a boolean indicating whether the result is exact (that is,
    whether x**n == y).

    Examples
    ========

    >>> from sympy import integer_nthroot
    >>> integer_nthroot(16, 2)
    (4, True)
    >>> integer_nthroot(26, 2)
    (5, False)

    To simply determine if a number is a perfect square, the is_square
    function should be used:

    >>> from sympy.ntheory.primetest import is_square
    >>> is_square(26)
    False

    See Also
    ========
    sympy.ntheory.primetest.is_square
    integer_log
    )r
   r   r   )r6   r   r5   r"   s       r   integer_nthrootrS     s*    6 F1I&DAqq619r   )
   )__doc__r   r0   	functoolsr   r   	singletonr   sympy.external.gmpyr   r*   r   rA   r	   r
   r   r   sympy.utilities.miscr   r   r   r   r   r.   igcd2r?   rB   rE   rO   rQ   rS    r   r   <module>r\      s     
   ; ; 3!HM1`0 4/ /< 	Od/(2BJ-`r   