U
    9%e͞                     @  s  d dl mZ d dlmZ d dlmZmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZmZmZ d	d
lmZ d	dlmZmZmZmZmZ d dlmZ d dlmZm Z  d dl!m"Z"m#Z# dd Z$dd Z%dd Z&dd Z'dd Z(dXddZ)dd Z*e+fddZ,d d! Z-d"d# Z.d$d% Z/d&d' Z0d(d) Z1d*d+ Z2d,d- Z3d.d/ Z4d0d1 Z5d2d3 Z6dYd4d5Z7d6d7d8d9Z8d:d; Z9d<d= Z:G d>d? d?eZ;dZdAdBZ<d[dCdDZ=d\dFdGZ>d]dHdIZ?d^dJdKZ@dLdM ZAdNdO ZBdPdQ ZCdRdS ZDdTdU ZEdVdW ZFd@S )_    )annotations)Function)igcdigcdexmod_inverse)isqrt)S)Poly)ZZ)gf_crt1gf_crt2linear_congruence   )isprime)	factorinttrailingtotientmultiplicityperfect_power)as_int)_randintrandint)cycleproductc                 C  s&  ddl m} t| t| } }|dkr.td| | } | dkrBdS t| |dkrXtd|t}t| D ]N\}}|dkr||  |d 7  < t|d  D ]\}}||  |7  < qqld}| D ]\}}||| 9 }q| D ]:\}	}
t|
D ](}t	| ||	 |dkr||	 }q qqq|S )a  Returns the order of ``a`` modulo ``n``.

    The order of ``a`` modulo ``n`` is the smallest integer
    ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.

    Parameters
    ==========

    a : integer
    n : integer, n > 1. a and n should be relatively prime

    Examples
    ========

    >>> from sympy.ntheory import n_order
    >>> n_order(3, 7)
    6
    >>> n_order(4, 7)
    3
    r   )defaultdictr   z%n should be an integer greater than 1*The two numbers should be relatively prime)
collectionsr   r   
ValueErrorr   intr   itemsrangepow)anr   factorspxZkxpykyorderpe_ r,   \/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sympy/ntheory/residue_ntheory.pyn_order   s0    
r.   c                 #  s\    fddt  d  D }d}| k rX|D ]}t|| dkr. qNq.|V  |d7 }q"dS )aJ  
    Generates the primitive roots for a prime ``p``

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
    >>> list(_primitive_root_prime_iter(19))
    [2, 3, 10, 13, 14, 15]

    References
    ==========

    .. [1] W. Stein "Elementary Number Theory" (2011), page 44

    c                   s   g | ]} d  | qS )r   r,   .0ir)   r,   r-   
<listcomp>Y   s     z._primitive_root_prime_iter.<locals>.<listcomp>r      N)r   keysr!   )r)   vr"   pwr,   r2   r-   _primitive_root_prime_iterG   s    r8   c                 C  sN  t | } | dk rtd| dkr$dS t| }t|dkr<dS t|dkrd|ks\|d dkr`dS | D ]\}}|dkrh q~qhd}|| k r|d7 }|| dkrqt|| r|S qnd|kr| dkrdS dS t| d \}}|dkrBt|}t||d r|S td|| d D ]*}t	|| dkrt|| r|  S qt
t| S )a  
    Returns the smallest primitive root or None.

    Parameters
    ==========

    p : positive integer

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import primitive_root
    >>> primitive_root(19)
    2

    References
    ==========

    .. [1] W. Stein "Elementary Number Theory" (2011), page 44
    .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C

    r   zp is required to be positiver4   Nr         )r   r   r   lenr   is_primitive_rootlistprimitive_rootr    r   nextr8   )r)   fp1e1r1   r#   gr,   r,   r-   r>   e   sD    

r>   c                   s  t  t   dkr"td   t dkr@tddkrT d kS t}|dkrhdS |? }t|r|d tt|d  }nVt|}|sdS |\}}t|sdS ||d  |d  tt|d  }|	| t
 fdd|D S )ac  
    Returns True if ``a`` is a primitive root of ``p``.

    ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and
    totient(p) is the smallest positive number s.t.

        a**totient(p) cong 1 mod(p)

    Parameters
    ==========

    a : integer
    p : integer, p > 1. a and p should be relatively prime

    Examples
    ========

    >>> from sympy.ntheory import is_primitive_root, n_order, totient
    >>> is_primitive_root(3, 10)
    True
    >>> is_primitive_root(9, 10)
    False
    >>> n_order(3, 10) == totient(10)
    True
    >>> n_order(9, 10) == totient(10)
    False

    r   z%p should be an integer greater than 1r   r9   Fc                 3  s"   | ]}t  | d kV  qdS r   Nr!   )r0   primer"   Zgroup_orderr)   r,   r-   	<genexpr>   s     z$is_primitive_root.<locals>.<genexpr>)r   r   r   r   r   setr   r5   r   addall)r"   r)   tqr$   mr*   r,   rG   r-   r<      s2    
r<   c                 C  s   t |d }||? }td|d }t||}|dkrq8qt| ||}t|||}d}t|D ]L}	|t||| | }
t|
d|d |	  |}
|
| |d kr\|d|	 7 }q\t| |d d |t||d | | }|S )z
    Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``

    References
    ==========

    .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101

    r   r4   r   )r   r   legendre_symbolr!   r    )r"   r)   srL   drADrN   r1   Zadmxr,   r,   r-   _sqrt_mod_tonelli_shanks   s     

(rW   Fc                 C  s   |rt t| |S ztt|}t| |}t|}||d krH|| W S ||d k rZ|W S z$t|}||d kr||| W W S W n tk
r   Y nX |W S W n tk
r   Y dS X dS )a  
    Find a root of ``x**2 = a mod p``.

    Parameters
    ==========

    a : integer
    p : positive integer
    all_roots : if True the list of roots is returned or None

    Notes
    =====

    If there is no root it is returned None; else the returned root
    is less or equal to ``p // 2``; in general is not the smallest one.
    It is returned ``p // 2`` only if it is the only root.

    Use ``all_roots`` only when it is expected that all the roots fit
    in memory; otherwise use ``sqrt_mod_iter``.

    Examples
    ========

    >>> from sympy.ntheory import sqrt_mod
    >>> sqrt_mod(11, 43)
    21
    >>> sqrt_mod(17, 32, True)
    [7, 9, 23, 25]
    r4   N)sortedsqrt_mod_iterabsr   r?   StopIteration)r"   r)   	all_rootsitrS   r,   r,   r-   sqrt_mod  s&    


r^   c                  g  sx   t dd | D }t|}dg| }d}d| }}|rX|sX|d8 }t|| \}||< q2|sl|sl|rtd}nqt|V  q(dS )z
    Cartesian product generator

    Notes
    =====

    Unlike itertools.product, it works also with iterables which do not fit
    in memory. See https://bugs.python.org/issue10109

    Author: Fernando Sumudu
    with small changes
    c                 s  s   | ]}t t|V  qd S N)r   	enumerate)r0   r]   r,   r,   r-   rH   D  s     z_product.<locals>.<genexpr>NTr   r   F)tupler;   r?   )ZitersZ	inf_itersZ	num_itersZcur_valZfirst_vr1   r)   r,   r,   r-   _product7  s    

rb   c                 c  s^  t | tt | } }t|rv| | } | dkr<t| |d}nt| |d}|rt|tkr`|E dH  n|D ]}||V  qdnt|}g }g }| D ]Z\}}	| | dkrt| ||	}
|
s dS nt| ||	}
|
s dS ||
 |||	  qt	|t\}}}|tkr.t
| D ]}t|||||t}|V  qn,t
| D ]"}t|||||t}||V  q6dS )aI  
    Iterate over solutions to ``x**2 = a mod p``.

    Parameters
    ==========

    a : integer
    p : positive integer
    domain : integer domain, ``int``, ``ZZ`` or ``Integer``

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
    >>> list(sqrt_mod_iter(11, 43))
    [21, 22]
    r   r   N)r   rZ   r   
_sqrt_mod1_sqrt_mod_prime_powerr
   r   r   appendr   rb   r   )r"   r)   domainresrV   r@   r6   pvr%   exrxmmr*   rQ   ZvxrS   r,   r,   r-   rY   X  s@    

rY   c                 C  s$  || }| | } |dkr|dkr,t | gS | | dk sTt| |d d |dksTdS |d dkrvt| |d d |}n|d dkrt| |d d |}|dkrt| |d d |}qtd|  |d d |}d|  | | }t|d|| kr|}n
t| |}tt |t || gS |dkr |dkrV| d dkr:dS |dkrt }td|dD ]"}	|d|	  |d	|	  qVt|S t dt dt dt d
g}
d}g }|
D ]}|}||k r|d |  |? }|d r|d|d >  }|d7 }q||kr|| |d|d >  }|d|> k r||kr|d |  | dkr|| q|S t	| |d}
|
sldS |
d }|d |  }d}|}|}|d9 }||krq|}|d }t
d| |d }|||  | }|d |  }q||k r|| }t
d| |d }|||  | }||| gS dS )a  
    Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``

    Parameters
    ==========

    a : integer
    p : prime number
    k : positive integer

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
    >>> _sqrt_mod_prime_power(11, 43, 1)
    [21, 22]

    References
    ==========

    .. [1] P. Hackman "Elementary Number Theory" (2009), page 160
    .. [2] http://www.numbertheory.org/php/squareroot.html
    .. [3] [Gathen99]_
    r   r4   Nr9   r:         r   rO      )r
   r!   rW   rX   rI   r    rJ   r=   re   rd   r   )r"   r)   kpkrg   signbrV   rQ   r1   rvr#   rS   nxr1frr%   Zn1Zfrinvr,   r,   r-   rd     s    

$









rd   c                   s  | |  } | dkrh|d  |d dkrL d  fdd}| S   fdd}| S t | }| }|d dkrdS |d  | |? }dkr|| dkrd|  d > d d >  fd	d
}| S || dkr2t||| dkrdS d|  >  fdd}	|	 S || dkrt||| dkr^dS d|  d >  fdd}
|
 S nn|d  | |  }t||| 		dkrdS   ||  |    	fdd}| S dS )z~
    Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``

    see http://www.numbertheory.org/php/squareroot.html
    r   r4   r   c                  3  s    d} | k r| V  |  7 } qd S Nr   r,   r1   )pm1pnr,   r-   _iter0a  s    z_sqrt_mod1.<locals>._iter0ac                  3  s    d} | k r| V  |  7 } qd S rw   r,   rx   )pmrz   r,   r-   _iter0b  s    z_sqrt_mod1.<locals>._iter0bNc                  3  sF   d d > } d > }|k rB|}|k r8|V  || 7 }q |7 }qd S )Nr   r4   r,   )ro   r1   j)rN   ry   rz   pnm1r,   r-   _iter1*  s    
z_sqrt_mod1.<locals>._iter1c                  3  sN   t  } D ]>}d}|k r
| > | }|| kr>| | |V  |7 }qq
d S rw   rI   rJ   rQ   rS   r1   rV   )rN   rz   pnmrg   r,   r-   _iter29  s    
z_sqrt_mod1.<locals>._iter2c                  3  sR   t  } D ]B}d}|k r
| > |  }|| krB| | |V  |7 }qq
d S rw   r   r   )rN   rz   r   rg   r,   r-   _iter3I  s    
z_sqrt_mod1.<locals>._iter3c                  3  sZ   t  }   }D ]B}d}|k r||  }|| krJ| | || V  |7 }qqd S rw   r   )rQ   r|   rj   r1   rV   )rN   r)   rz   r   pnrres1r,   r-   _iter4^  s    

z_sqrt_mod1.<locals>._iter4)r   rd   )r"   r)   r#   r{   r}   r@   rS   Za1r   r   r   r   r,   )
rN   r)   r|   ry   rz   r   r   r   rg   r   r-   rc     s^    
	




rc   c                 C  s   t | t | } }|dk r"td| |ks2| dk r:| | } | dk sJ|dk rNdS t|s|d rpt| |dkrpdS t| |}|d	krdS dS t| |d d |dkS )
a  
    Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
    i.e a % p in set([i**2 % p for i in range(p)]).

    Examples
    ========

    If ``p`` is an odd
    prime, an iterative method is used to make the determination:

    >>> from sympy.ntheory import is_quad_residue
    >>> sorted(set([i**2 % 7 for i in range(7)]))
    [0, 1, 2, 4]
    >>> [j for j in range(7) if is_quad_residue(j, 7)]
    [0, 1, 2, 4]

    See Also
    ========

    legendre_symbol, jacobi_symbol
    r   zp must be > 0r   r4   r:   TrO   FN)r   r   r   jacobi_symbolr^   r!   )r"   r)   rS   r,   r,   r-   is_quad_residuel  s    
r   c                 C  s   | | } t | t |t |  } }}|dkr4td|dk rDtd|dkr`|dkrXdS | dkS | dkrldS |dkrxdS |dkrt| |S t| ||S )z
    Returns True if ``x**n == a (mod m)`` has solutions.

    References
    ==========

    .. [1] P. Hackman "Elementary Number Theory" (2009), page 76

    r   zm must be > 0zn must be >= 0r   FTr4   )r   r   r   _is_nthpow_residue_bignr"   r#   rN   r,   r,   r-   is_nthpow_residue  s"    

r   c                 C  sv   t |dkst| |dkrHt| D ]\}}t| |||s& dS q&dS t|}t|t|| }t| |t|dkS )z=Returns True if `x^n = a \pmod{n}` has solutions for `n > 2`.Nr   FT)r>   r   r   r   #_is_nthpow_residue_bign_prime_powerr   r   r!   )r"   r#   rN   rF   powerr@   ro   r,   r,   r-   r     s    r   c                 C  s   | | rR|dkr"t | |t||S |d@ r.dS t|}| tdt|d | dkS | t||; } | shdS t|| }|| r~dS t||}t| | |||| S dS )zRReturns True/False if a solution for `x^n = a \pmod{p^k}`
    does/does not exist.r4   r   TFN)r   r!   r   minr   r   )r"   r#   r)   ro   cmur|   r,   r,   r-   r     s    

r   c                 C  sJ   t |}g }| D ]\}}||g|  q|D ]}t| ||d} q2| S )NF)r   r   extend_nthroot_mod1)rQ   rM   r)   r@   r6   rr   r*   Zqxr,   r,   r-   _nthroot_mod2  s    r   c                 C  sD  t |}t|st| ||}n|d }|d | dks:td}|| dkr\|d7 }|| }q>t| |d | }|| }	d|	 | }
t| |
|}t| ||}t||| |}t|||}t||	| |}t||d }|| | }|g}t||d | |}|}t|d D ]}|| | }|| q|r<|	  |S t
|S )z
    Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``

    References
    ==========

    .. [1] A. M. Johnston "A Generalized qth Root Algorithm"

    r   r   )r>   r   r   AssertionErrorr   r!   discrete_logr    re   sortr   )rQ   rM   r)   r\   rC   rS   r@   ro   f1zrV   ru   s1hrL   g2Zg3rg   hxr1   r,   r,   r-   r     s:    

r   c                   s  ddl m  t}i }| D ]$\}}t }|dkrH||| n||D ]}	||	|}
|
dkr|}t|
|}td|D ]"}||9 }|	||	||  | }	q~||	 qP|}|	h}|t	||k r||9 }t }|D ]8}|||dkrq||kr|| |||  | }qq|}q||B }qP|t kr8g   S ||t	||< q g }g | D ]"\}}
| |
t| qXt fddt| D S )a  
    Helper function for _nthroot_mod_composite and polynomial_congruence.

    Parameters
    ==========

    m : positive integer
    prime_modulo_method : function to calculate the root of the congruence
    equation for the prime divisors of m
    diff_method : function to calculate derivative of expression at any
    given point
    expr_val : function to calculate value of the expression at any
    given point
    r   crtr   c                   s   h | ]} t |d  qS )r   )r=   r/   r   rN   r,   r-   	<setcomp>I  s     z_help.<locals>.<setcomp>)Zsympy.ntheory.modularr   r   r   rI   updater   r    rJ   r!   re   r=   rX   r   )rN   Zprime_modulo_methodZdiff_methodZexpr_valr@   ddr)   r*   Z	tot_rootsrootdiffZppowZm_invr~   new_baseZroots_in_baseZ	new_rootsro   r"   rV   yr,   r   r-   _help  sL    




r   c                   s*   t | fddfdd fddS )zG
    Find the solutions to ``x**n = a mod m`` when m is not prime.
    c                   s   t  | dS )NT)nthroot_modr2   r"   r#   r,   r-   <lambda>Q      z(_nthroot_mod_composite.<locals>.<lambda>c                   s   t |  d | |  | S )Nr   rE   r   r)   )r#   r,   r-   r   R  r   c                   s   t | |  | S r_   rE   r   r   r,   r-   r   S  r   )r   r   r,   r   r-   _nthroot_mod_compositeL  s
    
r   c                 C  sV  | | } t | t |t |  } }}|dkr8t| ||S t|sLt| ||S | | dkr^dgS t| ||sv|rrg S dS |d | dkrt| |||S |}|d }d}||k r||| |f\} }}}|rt||\}}t|||}	t|	|d }	|	|  | }	|| }}||	 } }q|dkr.|r(| g}
n| }
n$|dkrDt| ||S t| |||}
|
S )a  
    Find the solutions to ``x**n = a mod p``.

    Parameters
    ==========

    a : integer
    n : positive integer
    p : positive integer
    all_roots : if False returns the smallest root, else the list of roots

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import nthroot_mod
    >>> nthroot_mod(11, 4, 19)
    8
    >>> nthroot_mod(11, 4, 19, True)
    [8, 11]
    >>> nthroot_mod(68, 3, 109)
    23
    r4   r   Nr   )	r   r^   r   r   r   r   divmodr!   r   )r"   r#   r)   r\   paZpbrr   rM   rS   r   rg   r,   r,   r-   r   V  s@    


r   z	list[int])returnc                   s.   t    fddt d d D }t|S )z
    Returns the list of quadratic residues.

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import quadratic_residues
    >>> quadratic_residues(7)
    [0, 1, 2, 4]
    c                   s   h | ]}t |d  qS )r4   rE   r/   r2   r,   r-   r     s     z%quadratic_residues.<locals>.<setcomp>r4   r   )r   r    rX   )r)   rS   r,   r2   r-   quadratic_residues  s    r   c                 C  sZ   t | t | } }t|r"|dkr*td| | } | s:dS t| |d d |dkrVdS dS )a  
    Returns the Legendre symbol `(a / p)`.

    For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
    defined as

    .. math ::
        \genfrac(){}{}{a}{p} = \begin{cases}
             0 & \text{if } p \text{ divides } a\\
             1 & \text{if } a \text{ is a quadratic residue modulo } p\\
            -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
        \end{cases}

    Parameters
    ==========

    a : integer
    p : odd prime

    Examples
    ========

    >>> from sympy.ntheory import legendre_symbol
    >>> [legendre_symbol(i, 7) for i in range(7)]
    [0, 1, 1, -1, 1, -1, -1]
    >>> sorted(set([i**2 % 7 for i in range(7)]))
    [0, 1, 2, 4]

    See Also
    ========

    is_quad_residue, jacobi_symbol

    r4   zp should be an odd primer   r   rO   )r   r   r   r!   )r"   r)   r,   r,   r-   rP     s    #rP   c                 C  s   t | t | } }|dk s"|d s*td| dk s:| |krB| |; } | sRt|dkS |dksb| dkrfdS t| |dkrxdS d}| dkr| d dkr| dkr| dL } |d dkr| }q||  } }| d |d   krdkrn n| }| |; } q||S )	a  
    Returns the Jacobi symbol `(m / n)`.

    For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
    is defined as the product of the Legendre symbols corresponding to the
    prime factors of ``n``:

    .. math ::
        \genfrac(){}{}{m}{n} =
            \genfrac(){}{}{m}{p^{1}}^{\alpha_1}
            \genfrac(){}{}{m}{p^{2}}^{\alpha_2}
            ...
            \genfrac(){}{}{m}{p^{k}}^{\alpha_k}
            \text{ where } n =
                p_1^{\alpha_1}
                p_2^{\alpha_2}
                ...
                p_k^{\alpha_k}

    Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
    then ``m`` is a quadratic nonresidue modulo ``n``.

    But, unlike the Legendre symbol, if the Jacobi symbol
    `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
    modulo ``n``.

    Parameters
    ==========

    m : integer
    n : odd positive integer

    Examples
    ========

    >>> from sympy.ntheory import jacobi_symbol, legendre_symbol
    >>> from sympy import S
    >>> jacobi_symbol(45, 77)
    -1
    >>> jacobi_symbol(60, 121)
    1

    The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
    be demonstrated as follows:

    >>> L = legendre_symbol
    >>> S(45).factors()
    {3: 2, 5: 1}
    >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
    True

    See Also
    ========

    is_quad_residue, legendre_symbol
    r   r4   z#n should be an odd positive integerr   rl   )r:   rm   r9   r:   )r   r   r   r   )rN   r#   r~   r,   r,   r-   r     s,    9
 
r   c                   @  s   e Zd ZdZedd ZdS )mobiusa  
    Mobius function maps natural number to {-1, 0, 1}

    It is defined as follows:
        1) `1` if `n = 1`.
        2) `0` if `n` has a squared prime factor.
        3) `(-1)^k` if `n` is a square-free positive integer with `k`
           number of prime factors.

    It is an important multiplicative function in number theory
    and combinatorics.  It has applications in mathematical series,
    algebraic number theory and also physics (Fermion operator has very
    concrete realization with Mobius Function model).

    Parameters
    ==========

    n : positive integer

    Examples
    ========

    >>> from sympy.ntheory import mobius
    >>> mobius(13*7)
    1
    >>> mobius(1)
    1
    >>> mobius(13*7*5)
    -1
    >>> mobius(13**2)
    0

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
    .. [2] Thomas Koshy "Elementary Number Theory with Applications"

    c                 C  sz   |j r|jdk	r"tdntd|jr.tjS |tjkr>tjS |jrvt	|}t
dd | D rhtjS tjt| S d S )NTzn should be a positive integerzn should be an integerc                 s  s   | ]}|d kV  qdS rD   r,   r/   r,   r,   r-   rH   ]  s     zmobius.eval.<locals>.<genexpr>)
is_integerZis_positiver   	TypeErrorZis_primer   ZNegativeOneZOneZ
is_Integerr   anyvaluesZZeror;   )clsr#   r"   r,   r,   r-   evalP  s    


zmobius.evalN)__name__
__module____qualname____doc__classmethodr   r,   r,   r,   r-   r   (  s   'r   Nc                 C  sV   || ; }|| ; }|dkr| }d}t |D ] }||kr<|  S || |  }q(tddS )a  
    Trial multiplication algorithm for computing the discrete logarithm of
    ``a`` to the base ``b`` modulo ``n``.

    The algorithm finds the discrete logarithm using exhaustive search. This
    naive method is used as fallback algorithm of ``discrete_log`` when the
    group order is very small.

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
    >>> _discrete_log_trial_mul(41, 15, 7)
    3

    See Also
    ========

    discrete_log

    References
    ==========

    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
        Vanstone, S. A. (1997).
    Nr   Log does not exist)r    r   )r#   r"   rr   r(   rV   r1   r,   r,   r-   _discrete_log_trial_mulb  s    r   c           	      C  s   || ; }|| ; }|dkr"t || }t|d }i }d}t|D ]}|||< || |  }q>t|| }t||| }|}t|D ],}||kr|| ||    S || |  }qztddS )ae  
    Baby-step giant-step algorithm for computing the discrete logarithm of
    ``a`` to the base ``b`` modulo ``n``.

    The algorithm is a time-memory trade-off of the method of exhaustive
    search. It uses `O(sqrt(m))` memory, where `m` is the group order.

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
    >>> _discrete_log_shanks_steps(41, 15, 7)
    3

    See Also
    ========

    discrete_log

    References
    ==========

    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
        Vanstone, S. A. (1997).
    Nr   r   )r.   r   r    r   r!   r   )	r#   r"   rr   r(   rN   TrV   r1   r   r,   r,   r-   _discrete_log_shanks_steps  s$    

r   
   c              
   C  s  || ; }|| ; }|dkr"t || }t|}t|D ]}|d|d }|d|d }	t||| t||	|  |  }
|
d }|dkr||
 |  }|}|	d | }nJ|dkr|
|
 |  }|| | }|	|	 | }n||
 |  }|d | }|	}t|D ]}|
d }|dkr"||
 |  }
|	d | }	nH|dkrR|
|
 |  }
|| | }|	|	 | }	n||
 |  }
|d | }|d }|dkr|| |  }|d | }nH|dkr|| |  }|| | }|| | }n|| |  }|d | }|d }|dkr
|| |  }|d | }nH|dkr:|| |  }|| | }|| | }n|| |  }|d | }|
|kr|	| | }zBt||||  | }t||| | |  dkr|W     S W n tk
r   Y nX  q2qq2tddS )ag  
    Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
    the base ``b`` modulo ``n``.

    It is a randomized algorithm with the same expected running time as
    ``_discrete_log_shanks_steps``, but requires a negligible amount of memory.

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
    >>> _discrete_log_pollard_rho(227, 3**7, 3)
    7

    See Also
    ========

    discrete_log

    References
    ==========

    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
        Vanstone, S. A. (1997).
    Nr   r:   r   z&Pollard's Rho failed to find logarithm)r.   r   r    r!   r   r   )r#   r"   rr   r(   retriesZrseedr   r1   ZaabaZxar   xbabZbbr~   rS   r*   r,   r,   r-   _discrete_log_pollard_rho  s|    






r   c                 C  s   ddl m} || ; }|| ; }|dkr.t|| }t|}dgt| }t| D ]\}\}}	t|	D ]n}
t||| | }t|t	||  |||
d   | }t||| | }t
| |||d}||  |||
  7  < qdqP|dd | D |\}}|S )a  
    Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
    the base ``b`` modulo ``n``.

    In order to compute the discrete logarithm, the algorithm takes advantage
    of the factorization of the group order. It is more efficient when the
    group order factors into many small primes.

    Examples
    ========

    >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
    >>> _discrete_log_pohlig_hellman(251, 210, 71)
    197

    See Also
    ========

    discrete_log

    References
    ==========

    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
        Vanstone, S. A. (1997).
    r   r   Nr   Tc                 S  s   g | ]\}}|| qS r,   r,   )r0   pirir,   r,   r-   r3   I  s     z0_discrete_log_pohlig_hellman.<locals>.<listcomp>)Zmodularr   r.   r   r;   r`   r   r    r!   r   r   )r#   r"   rr   r(   r   r@   lr1   r   r   r~   ZgjZajZbjcjrR   r+   r,   r,   r-   _discrete_log_pohlig_hellman  s     
"r   c                 C  s   t | t |t |  } }}|dkr.t|| }|dkr>t|}|dk rTt| |||S |r||dk rnt| |||S t| |||S t| |||S )a  
    Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.

    This is a recursive function to reduce the discrete logarithm problem in
    cyclic groups of composite order to the problem in cyclic groups of prime
    order.

    It employs different algorithms depending on the problem (subgroup order
    size, prime order or not):

        * Trial multiplication
        * Baby-step giant-step
        * Pollard's Rho
        * Pohlig-Hellman

    Examples
    ========

    >>> from sympy.ntheory import discrete_log
    >>> discrete_log(41, 15, 7)
    3

    References
    ==========

    .. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html
    .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
        Vanstone, S. A. (1997).

    Ni  l    J))r   r.   r   r   r   r   r   )r#   r"   rr   r(   Zprime_orderr,   r,   r-   r   M  s    
r   c                 C  s  t | } t |}t |}t |}| | } || }|| }| dkrNt|| |S |dkrg }|d dkrp|d | | | d dkr|d |S t|rt| |}||9 }||9 }|d dkr|| }|| d | | }t||dd}t }|D ]}	||	|d  |  qt|S t|| d|  |  d|  | dd}t }|D ]<}	td|  |	| d|  | }
|
D ]}|||  qnqJt|S )z
    Find the solutions to ``a x**2 + b x + c = 0 mod p.

    Parameters
    ==========

    a : int
    b : int
    c : int
    p : int
        A positive integer.
    r   r4   r   r9   T)r\   )	r   r   re   r   r   r^   rI   rJ   rX   )r"   rr   r   r)   rootsZinv_arR   r   rg   r1   r   r~   r,   r,   r-   quadratic_congruence~  sF    



&r   c                 C  s   g }t | }td|D ]f}d}td|d D ],}|t|t|| d || |   | }q,|| d  }|| dkr|| q|S )zA helper function used by polynomial_congruence.
    It returns the root of a polynomial modulo prime number
    by naive search from [0, p).

    Parameters
    ==========

    coefficients : list of integers
    p : prime number
    r   r   rO   )r;   r    r!   r   re   )coefficientsr)   r   rankr1   f_valcoeffr,   r,   r-   _polynomial_congruence_prime  s    *r   c                 C  sb   d}t |}td|d D ]>}|| s(q|t| || d ||| d  ||   | }q|| S )zA helper function used by polynomial_congruence.
    It returns the derivative of the polynomial evaluated at the
    root (mod p).

    Parameters
    ==========

    coefficients : list of integers
    p : prime number
    root : integer
    r   r   r4   r;   r    r!   )r   r   r)   r   r   r   r,   r,   r-   
_diff_poly  s     r   c                 C  sX   t |}d}td|d D ](}|t| || d |||   | }q||d  }|| S )zA helper function used by polynomial_congruence.
    It returns value of the polynomial at root (mod p).

    Parameters
    ==========

    coefficients : list of integers
    p : prime number
    root : integer
    r   r   rO   r   )r   r   r)   r   r   r   r,   r,   r-   	_val_poly  s    r   c                 C  s@   |   stdt| }|js&td|jtks8td| S )z}
    return coefficients of expr if it is a univariate polynomial
    with integer coefficients else raise a ValueError.
    z%The expression should be a polynomialz#The expression should be univariatez6The expression should should have integer coefficients)Zis_polynomialr   r	   Zis_univariaterf   r
   Z
all_coeffs)exprZ
polynomialr,   r,   r-   _valid_expr  s    
r   c                   s   t |  fdd D  t }|dkr8t f S |dkrPtd f S  d dkrd d  t krt d  |d dS trt S t fd	d
 fdd
 fdd
S )a  
    Find the solutions to a polynomial congruence equation modulo m.

    Parameters
    ==========

    coefficients : Coefficients of the Polynomial
    m : positive integer

    Examples
    ========

    >>> from sympy.ntheory import polynomial_congruence
    >>> from sympy.abc import x
    >>> expr = x**6 - 2*x**5 -35
    >>> polynomial_congruence(expr, 6125)
    [3257]
    c                   s   g | ]}|  qS r,   r,   )r0   num)rN   r,   r-   r3     s     z)polynomial_congruence.<locals>.<listcomp>r:   r4   r   r   rO   Tc                   s
   t  | S r_   )r   r2   r   r,   r-   r   #  r   z'polynomial_congruence.<locals>.<lambda>c                   s   t |  |S r_   )r   r   r   r,   r-   r   $  r   c                   s   t |  |S r_   )r   r   r   r,   r-   r   %  r   )r   )r   r;   r   sumr   r   r   r   )r   rN   r   r,   )r   rN   r-   polynomial_congruence  s      



r   )F)F)N)N)Nr   N)N)NN)G
__future__r   Zsympy.core.functionr   Zsympy.core.numbersr   r   r   Zsympy.core.powerr   Zsympy.core.singletonr   Zsympy.polysr	   Zsympy.polys.domainsr
   Zsympy.polys.galoistoolsr   r   r   Z	primetestr   Zfactor_r   r   r   r   r   Zsympy.utilities.miscr   Zsympy.core.randomr   r   	itertoolsr   r   r.   r8   r>   r<   rW   r^   rb   r   rY   rd   rc   r   r   r   r   r   r   r   r   r   r   rP   r   r   r   r   r   r   r   r   r   r   r   r   r   r,   r,   r,   r-   <module>   s\   5B< 
4!9ri)
/9

B.R:
'
.
e
1
13