o
    8Va                    @   s  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 d dlmZ d dlmZ d d	lmZmZmZ d d
lmZmZ d dlmZ d dlmZ d dlmZmZ d dlm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z) d dl*m+Z+m,Z,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9m:Z: d dl;m<Z< d dl=m>Z> d dl?m@Z@mAZA d dlBmCZC ddgZDG dd  d eEZFG d!d" d"ZGG d#d$ d$eGZHG d%d& d&eGZIG d'd( d(eGZJG d)d* d*eGZKG d+d, d,eGZLG d-d. d.eGZMG d/d0 d0eGZNG d1d2 d2eGZOG d3d4 d4eGZPG d5d6 d6eGZQG d7d8 d8eGZRG d9d: d:eGZSeIeHeJeKeLeMeNeOePeQeReSgZTd;d< eTD ZUd=d> ZVd?d@ ZWdAdB ZXdCdD ZYdEdF ZZdGdH Z[dIdJ Z\edKdLdMdNdOfdPdZ]dQdR Z^ddSdTZ_edKdLdMfdUdVZ`ddWdZadXdYbeceU ea_dedKdLdMfdZd[Zedd\d]Zfd^d_ Zgd`da ZhedKdLdMfdbdcZiddde ZjedKdLdMfdfdgZkdhdi Zldjdk Zmdldm ZnedKdLdMfdndoZodpdq Zpdrds Zqdtdu Zrdvdw Zsdxdy Ztdzd{ Zud|d} Zvdd~dZwdd Zxdd Zydd Zzdd Z{dd Z|dddZ}dd Z~dddZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZeddLdMfddZdddZdddZdddZdd Zdd Zdd ZdddZeZdd ZdddZdd ZdNS )    )Add)check_assumptions)Tuple)as_intis_sequenceordered)factor_terms)_mexpand)Mul)Rational)igcdexilcmigcd)integer_nthrootisqrt)Eq)S)Symbolsymbols)_sympifysign)floor)sqrt)MutableDenseMatrix)divisors	factorintmultiplicityperfect_power)	nextprime)	is_squareisprime)sqrt_mod)GeneratorsNeeded)Polyfactor_list)signsimp)solveset_real)default_sort_keynumbered_symbols)
filldedentdiophantineclassify_diopc                       sL   e Zd ZdZ fddZ fddZdd Zdd	 Zd
d Zdd Z	  Z
S )DiophantineSolutionSeta  
    Container for a set of solutions to a particular diophantine equation.

    The base representation is a set of tuples representing each of the solutions.

    Parameters
    ==========

    symbols : list
        List of free symbols in the original equation.
    parameters: list
        List of parameters to be used in the solution.

    Examples
    ========

    Adding solutions:

        >>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet
        >>> from sympy.abc import x, y, t, u
        >>> s1 = DiophantineSolutionSet([x, y], [t, u])
        >>> s1
        set()
        >>> s1.add((2, 3))
        >>> s1.add((-1, u))
        >>> s1
        {(-1, u), (2, 3)}
        >>> s2 = DiophantineSolutionSet([x, y], [t, u])
        >>> s2.add((3, 4))
        >>> s1.update(*s2)
        >>> s1
        {(-1, u), (2, 3), (3, 4)}

    Conversion of solutions into dicts:

        >>> list(s1.dict_iterator())
        [{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}]

    Substituting values:

        >>> s3 = DiophantineSolutionSet([x, y], [t, u])
        >>> s3.add((t**2, t + u))
        >>> s3
        {(t**2, t + u)}
        >>> s3.subs({t: 2, u: 3})
        {(4, 5)}
        >>> s3.subs(t, -1)
        {(1, u - 1)}
        >>> s3.subs(t, 3)
        {(9, u + 3)}

    Evaluation at specific values. Positional arguments are given in the same order as the parameters:

        >>> s3(-2, 3)
        {(4, 1)}
        >>> s3(5)
        {(25, u + 5)}
        >>> s3(None, 2)
        {(t**2, t + 2)}
    c                    sB   t    t|stdt|stdt|| _t|| _d S )Nz$Symbols must be given as a sequence.z'Parameters must be given as a sequence.)super__init__r   
ValueErrortupler   
parameters)selfZsymbols_seqr2   	__class__ G/usr/lib/python3/dist-packages/sympy/solvers/diophantine/diophantine.pyr/   b   s   

zDiophantineSolutionSet.__init__c                    s@   t |t | jkrtdt | jt |f t t|  d S )Nz+Solution should have a length of %s, not %s)lenr   r0   r.   addr   r3   solutionr4   r6   r7   r9   n   s   zDiophantineSolutionSet.addc                 G   s   |D ]}|  | qd S N)r9   )r3   	solutionsr;   r6   r6   r7   updates   s   zDiophantineSolutionSet.updatec                 c   s&    t | D ]}tt| j|V  qd S r<   )r   dictzipr   r:   r6   r6   r7   dict_iteratorw   s   z$DiophantineSolutionSet.dict_iteratorc                 O   s2   t | j| j}| D ]}||j|i | q	|S r<   )r-   r   r2   r9   subs)r3   argskwargsresultr;   r6   r6   r7   rB   {   s   zDiophantineSolutionSet.subsc                 G   sB   t |t | jkrtdt | jt |f | tt| j|S )Nz0Evaluation should have at most %s values, not %s)r8   r2   r0   rB   listr@   )r3   rC   r6   r6   r7   __call__   s   zDiophantineSolutionSet.__call__)__name__
__module____qualname____doc__r/   r9   r>   rA   rB   rG   __classcell__r6   r6   r4   r7   r-   $   s    =r-   c                   @   sX   e Zd ZdZdZdddZdd Zedd Zed	d
 Z	dde
fddZdddZdS )DiophantineEquationTypeaf  
    Internal representation of a particular diophantine equation type.

    Parameters
    ==========

    equation :
        The diophantine equation that is being solved.
    free_symbols : list (optional)
        The symbols being solved for.

    Attributes
    ==========

    total_degree :
        The maximum of the degrees of all terms in the equation
    homogeneous :
        Does the equation contain a term of degree 0
    homogeneous_order :
        Does the equation contain any coefficient that is in the symbols being solved for
    dimension :
        The number of symbols being solved for
    Nc                 C   s   t |jdd| _|d ur|| _nt| jj| _| jjtd | js&td| j | _	t
dd | j	 D s<tdt| j | _d| j	v| _t| j	t| j@  | _t| j| _d | _d S )	NTZforcekeyz+equation should have 1 or more free symbolsc                 s       | ]}t |V  qd S r<   _is_int).0cr6   r6   r7   	<genexpr>       z3DiophantineEquationType.__init__.<locals>.<genexpr>zCoefficients should be Integers   )r   expandequationfree_symbolsrF   sortr(   r0   as_coefficients_dictcoeffallvalues	TypeErrorr$   total_degreehomogeneoussethomogeneous_orderr8   	dimension_parameters)r3   rZ   r[   r6   r6   r7   r/      s   
z DiophantineEquationType.__init__c                 C   s   dS )zf
        Determine whether the given equation can be matched to the particular equation type.
        Fr6   r3   r6   r6   r7   matches   s   zDiophantineEquationType.matchesc                 C   s   | j S r<   rf   rh   r6   r6   r7   n_parameters   s   z$DiophantineEquationType.n_parametersc                 C   s&   | j d u rtd| jf dd| _ | j S )Nzt_:%iTinteger)rg   r   rk   rh   r6   r6   r7   r2      s   
z"DiophantineEquationType.parametersreturnc                 C   s   t d| j )N"No solver has been written for %s.)NotImplementedErrorname)r3   r2   limitr6   r6   r7   solve   s   zDiophantineEquationType.solvec                 C   sL   |   std| j |d ur!t|| jkr!td| jt|f || _d S )Nz2This equation does not match the %s equation type.z#Expected %s parameter(s) but got %s)ri   r0   rq   r8   rk   rg   )r3   r2   r6   r6   r7   	pre_solve   s   
z!DiophantineEquationType.pre_solver<   NN)rH   rI   rJ   rK   rq   r/   ri   propertyrk   r2   r-   rs   rt   r6   r6   r6   r7   rM      s    


rM   c                   @   &   e Zd ZdZdZdd ZdddZdS )	
Univariatea  
    Representation of a univariate diophantine equation.

    A univariate diophantine equation is an equation of the form
    `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
    integer constants and `x` is an integer variable.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import Univariate
    >>> from sympy.abc import x
    >>> Univariate((x - 2)*(x - 3)**2).solve() # solves equation (x - 2)*(x - 3)**2 == 0
    {(2,), (3,)}

    Z
univariatec                 C   
   | j dkS NrX   rj   rh   r6   r6   r7   ri         
zUnivariate.matchesNc                 C   sJ   |  | t| j| jd}t| j| jd tjD ]}|	|f q|S )Nr2   r   )
rt   r-   r[   r2   r'   rZ   	intersectr   Integersr9   )r3   r2   rr   rE   ir6   r6   r7   rs      s
   
zUnivariate.solveru   rH   rI   rJ   rK   rq   ri   rs   r6   r6   r6   r7   rx      s
    rx   c                   @   rw   )	Lineara  
    Representation of a linear diophantine equation.

    A linear diophantine equation is an equation of the form `a_{1}x_{1} +
    a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
    integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import Linear
    >>> from sympy.abc import x, y, z
    >>> l1 = Linear(2*x - 3*y - 5)
    >>> l1.matches() # is this equation linear
    True
    >>> l1.solve() # solves equation 2*x - 3*y - 5 == 0
    {(3*t_0 - 5, 2*t_0 - 5)}

    Here x = -3*t_0 - 5 and y = -2*t_0 - 5

    >>> Linear(2*x - 3*y - 4*z -3).solve()
    {(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)}

    Zlinearc                 C   ry   rz   )rb   rh   r6   r6   r7   ri     r{   zLinear.matchesNc                    s  |  | | j | j}d v r d  }nd}t|| jd}|j}t|dkr>t| |d  \}}|s<||f |S |S 	  fdd|D }	g }
t|dkr|
t	|	d |	d  |	d |
d  |	d< |	d |
d  |	d< t
t|	d	 ddD ]!}t	|
d |	| }|
d | |
d< |	| | |	|< |
d| qz|
|	d  	 g }t
t|
D ]}g g }}tt|D ]n\}}|jr|tj}}|d }n| \}}|||d  }t||	| |
| | }\}}|tju rd |v r|    S n$t|tr|jd | |jd  }t|tr|jd | |jd  }|| || q|t|  t| }q|| || |S )
NrX   r   r|   c                    s   g | ]} | qS r6   r6   )rT   vr^   r6   r7   
<listcomp>V      z Linear.solve.<locals>.<listcomp>      )rt   r^   r[   r-   r2   r8   divmodr9   appendr   rangeinsert	enumerater   Z	make_args
is_Integerr   Oneas_coeff_Mulindexbase_solution_linear
isinstancerC   )r3   r2   rr   varrU   rE   paramsqrABr   Zgcdr=   Ztot_xZtot_yjargkpZpnewsolZsol_xZsol_yr6   r   r7   rs     sj   
*4






zLinear.solveru   r   r6   r6   r6   r7   r      s
    r   c                   @   ,   e Zd ZdZdZdd Zd	defddZdS )
BinaryQuadratica  
    Representation of a binary quadratic diophantine equation.

    A binary quadratic diophantine equation is an equation of the
    form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`, where `A, B, C, D, E,
    F` are integer constants and `x` and `y` are integer variables.

    Examples
    ========

    >>> from sympy.abc import x, y
    >>> from sympy.solvers.diophantine.diophantine import BinaryQuadratic
    >>> b1 = BinaryQuadratic(x**3 + y**2 + 1)
    >>> b1.matches()
    False
    >>> b2 = BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2)
    >>> b2.matches()
    True
    >>> b2.solve()
    {(-1, -1)}

    References
    ==========

    .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
          Available: http://www.alpertron.com.ar/METHODS.HTM
    .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
          Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf

    Zbinary_quadraticc                 C   s   | j dko	| jdkS Nr   rb   rf   rh   r6   r6   r7   ri        zBinaryQuadratic.matchesNrn   c           9         s  |  | | j}| j}|\}}||d  }|||  }||d  }	||  || |tj dd t|||	 D \}}}	 t|| j}
|
j\}|d d| |	  }|dkr|	dkr|dkr׈  |  dkrt|\}}|s~|
	| f t |\}}|s|
	| f |
S t
  |  }|dd |D  }|D ].}t| |\}}|st  |  |\}}|st|  |\}}|s|
	||f q|
S |dkr|dkrt| j||gdj|gd}|D ]}|
	|d	 |d f q|
S t|t||	 | }|	 }t|| t|t|     sntd
dd} |d   |    }t||tj}|D ]}t|  |  | }|
	|d |d	 f qO|
S t|ṙfdd} fdd}tdtD ]:}t |d   |    rt  |d  |     r|
	||||f q|
S t|r|dkrt|}tddd\}}td| | | | d|   || ||  ||  ||    d| d |  ||   d| | d |   }t|} | D ]n\}!}"||" ||!  ||"  ||!  }#t|#d| |  }$t|!|" d|  }%t|!ts[t|"tr}tt |$|%d| | |dkr{t |$|%d| | |}|
j!|  q'|$j"r|%j"rt#|||$|%r|
	|$|%f q'|
S t| j|d d d dj|gd}|r|
	|$ d d d  |s|
S t%||\}&}'t&||\ }(t' |(}) dk r|)D ]8\}}| |fD ]-}| |fD ]$}|&t(||g |' }z|
	dd |D  W q t)y   Y qw qq|
S t*|)})t+|)D ]\}*}+|)	|* |+ f qt' d	}|d d },|d d	 }-t,dd |&d d |'d d  D r|)D ]P\}}||t   |,|-t     }.||t   |,|-t     }/tt|.|/ d }0tt|.|/ dt   }1|&t(|0|1g |' }|
	| qQ|
S t-dd |&d d |'d d  D  }2d	}3|,}4|-}5|4d	 |2 dks|5|2 dkr|4|,  |5 |-  |4|- |5|,  }4}5|3d	7 }3|4d	 |2 dks|5|2 dks|)D ]y\}*}+t|3D ]o}6t,dd |&t(|*|+g |' D rY|*t |+  |4t |5    }.|*t |+  |4t |5    }/t|.|/ d }7t|.|/ dt   }8|&t(|7|8g |' }|
	| |*|,  |- |+  |*|- |+|,  }*}+qq|
S )Nr   c                 S      g | ]}t |qS r6   r   rT   r   r6   r6   r7   r     r   z)BinaryQuadratic.solve.<locals>.<listcomp>   r   c                 S   s   g | ]}| qS r6   r6   )rT   termr6   r6   r7   r         r[   r|   rX   zT)realc                    sb       d   d   |       | d   |        S r   r6   u)EF_cegsqctr6   r7   <lambda>/  s   4 *z'BinaryQuadratic.solve.<locals>.<lambda>c                    sP     d   d  |      | d   |       S r   r6   r   )Dr   r   r   sqar   r6   r7   r   2  s   * "zu, vrl   r   c                 S   r   r6   r   rT   _r6   r6   r7   r   i  r   c                 s   rQ   r<   rR   r   r6   r6   r7   rV   w  rW   z(BinaryQuadratic.solve.<locals>.<genexpr>c                 S   s   g | ]}|j qS r6   )r   r   r6   r6   r7   r     r   c                 s   rQ   r<   rR   r   r6   r6   r7   rV     rW   ).rt   r[   r^   r   r   _remove_gcdr-   r2   r   r9   r   r   rZ   rs   r   r   r   r   r'   r}   r~   
diop_solverS   r   abs	divisibler    r   r	   r   r   r8   check_paramr>   r   is_solution_quadpop_transformation_to_DN_find_DNdiop_DNMatrixr0   rd   rF   r_   r   )9r3   r2   rr   r   r^   xyr   r   CrE   r   Zdiscrr   r   divdx0y0sZsolnarU   r   eqrootsrootZansZsolve_xZsolve_yZz0r   r;   Zs0Zt0Znumx_0y_0PQNZ
solns_pellXYTUZ_aZ_bZx_nZy_nLr   ZT_kZU_kr   ZXtZYtr6   )	r   r   r   r   r   r   r   r   r   r7   rs     s0  

(
    

~ m
(,`

>
  
E$A

4
($$& & $$$
*zBinaryQuadratic.solveru   rH   rI   rJ   rK   rq   ri   r-   rs   r6   r6   r6   r7   r     s
    r   c                   @      e Zd ZdZdZdd ZdS )InhomogeneousTernaryQuadraticz

    Representation of an inhomogeneous ternary quadratic.

    No solver is currently implemented for this equation type.

    Zinhomogeneous_ternary_quadraticc                 C   s*   | j dkr
| jdksdS | jsdS | j S )Nr   r   F)rb   rf   rc   re   rh   r6   r6   r7   ri     s
   z%InhomogeneousTernaryQuadratic.matchesNrH   rI   rJ   rK   rq   ri   r6   r6   r6   r7   r         r   c                   @   r   )
!HomogeneousTernaryQuadraticNormalaQ  
    Representation of a homogeneous ternary quadratic normal diophantine equation.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal
    >>> HomogeneousTernaryQuadraticNormal(4*x**2 - 5*y**2 + z**2).solve()
    {(1, 2, 4)}

    $homogeneous_ternary_quadratic_normalc                    sd   j dkr
jdksdS jsdS jsdS fddjD  t dko1t fddjD S )Nr   r   Fc                       g | ]	} j | r|qS r6   r   rT   r   rh   r6   r7   r         z=HomogeneousTernaryQuadraticNormal.matches.<locals>.<listcomp>c                 3       | ]	}|d   v V  qdS r   Nr6   r   nonzeror6   r7   rV         z<HomogeneousTernaryQuadraticNormal.matches.<locals>.<genexpr>rb   rf   rc   re   r^   r8   r_   r[   rh   r6   r   r3   r7   ri     s   $z)HomogeneousTernaryQuadraticNormal.matchesNrn   c                 C   s,  |  | | j}| j}|\}}}||d  }||d  }	||d  }
t||	|
dd\\}}}\}}}\}}}| | }| | }t|| jd}|dk rQ|dk rQ|S t| | |d u sot| | |d u sot| | |d u rq|S t||\}}}t|t	|\}}||9 }||9 }t
|||\}}}t|t|	krt|||t	|t	|t	|\}}}n-t|t|
krt|||t	|t	|t	|\}}}nt|||t	|t	|t	|\}}}t|||}t|||}t|||}t|||}t	|| | }t	|| | }t	|| | }|t
||| |S )Nr   T)stepsr|   r   )rt   r[   r^   
sqf_normalr-   r2   r"   descent_rational_pqr   r   r   holzerreconstructr   r9   )r3   r2   rr   r   r^   r   r   r   r   brU   Zsqf_of_aZsqf_of_bZsqf_of_cZa_1Zb_1Zc_1Za_2Zb_2Zc_2r   r   rE   z_0r   r   r   Zsq_lcmr6   r6   r7   rs     sP   



&&$z'HomogeneousTernaryQuadraticNormal.solveru   r   r6   r6   r6   r7   r     s
    r   c                   @   rw   )	HomogeneousTernaryQuadratica  
    Representation of a homogeneous ternary quadratic diophantine equation.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadratic
    >>> HomogeneousTernaryQuadratic(x**2 + y**2 - 3*z**2 + x*y).solve()
    {(-1, 2, 1)}
    >>> HomogeneousTernaryQuadratic(3*x**2 + y**2 - 3*z**2 + 5*x*y + y*z).solve()
    {(3, 12, 13)}

    homogeneous_ternary_quadraticc                    sf   j dkr
jdksdS jsdS jsdS fddjD  t dko1t fddjD  S )Nr   r   Fc                    r   r6   r   r   rh   r6   r7   r      r   z7HomogeneousTernaryQuadratic.matches.<locals>.<listcomp>c                 3   r   r   r6   r   r   r6   r7   rV   !  r   z6HomogeneousTernaryQuadratic.matches.<locals>.<genexpr>r   rh   r6   r   r7   ri     s   &z#HomogeneousTernaryQuadratic.matchesNc                    s,  |  | | j}| j |\}}}|||g}t|| jd}dd }	t fdd|D s ||  rt ||  |  ||  |  ||  }
|
 }t|d t|d  }|
D ]}t|d t|d  }||k ro|}|}qY|	t
|d  ||   |d  |S |d |d |d< |d< |	t| \}}}|d ur|	|||f |S  |d  dkr |d  dkr|d |d |d< |d< |	t| \}}}n2|d |d |d< |d< |	t| \}}}n ||  s ||  r |d  } ||  } ||  } |d  } ||  } |d  }t }d	|d  ||d < d	| | |d  ||d < d	| | |d  ||d < d	| | d| |  ||| < d||| < d||| < |	t||\}}}|d u rr|S t|| ||  d| \}}|| | || || }}}nr ||  dkr |d  dkr |d  dkrʈ |d  } ||  }t| |\}}|||}}}n:|d |d |d< |d< |	t| \}}}n"|d |d |d< |d< |	t| \}}}n
|	t| \}}}|d u r|S |	t
||| |S )
Nr|   c                 S   s   t | dkrt| d S dS )Nr   NNN)r8   rF   r   r6   r6   r7   
unpack_sol7  s   z5HomogeneousTernaryQuadratic.solve.<locals>.unpack_solc                 3       | ]	} |d   V  qdS r   r6   r   r   r6   r7   rV   <  r   z4HomogeneousTernaryQuadratic.solve.<locals>.<genexpr>r   rX   r   r   )rt   r[   r^   r-   r2   anyr+   r   r   r9   r   _diop_ternary_quadraticr?   r   _diop_ternary_quadratic_normal)r3   r2   rr   _varr   r   r   r   rE   r   solsr   Zmin_sumr   mr   r   r   r   r   r   r   r   r   _coeffr   r   r   r   r6   r   r7   rs   #  s   


,$ 
"
z!HomogeneousTernaryQuadratic.solveru   r   r6   r6   r6   r7   r     s
    r   c                   @   r   )InhomogeneousGeneralQuadraticz

    Representation of an inhomogeneous general quadratic.

    No solver is currently implemented for this equation type.

    Zinhomogeneous_general_quadraticc                 C   sB   | j dkr
| jdksdS | jsdS tdd | jD r| j S dS )Nr   r   FTc                 s       | ]}|j V  qd S r<   Zis_Mulr   r6   r6   r7   rV         z8InhomogeneousGeneralQuadratic.matches.<locals>.<genexpr>rb   rf   re   r   r^   rc   rh   r6   r6   r7   ri     s   z%InhomogeneousGeneralQuadratic.matchesNr   r6   r6   r6   r7   r    r   r  c                   @   r   )HomogeneousGeneralQuadraticz~

    Representation of a homogeneous general quadratic.

    No solver is currently implemented for this equation type.

    Zhomogeneous_general_quadraticc                 C   s@   | j dkr
| jdksdS | jsdS tdd | jD r| jS dS )Nr   r   Fc                 s   r  r<   r  r   r6   r6   r7   rV     r  z6HomogeneousGeneralQuadratic.matches.<locals>.<genexpr>r  rh   r6   r6   r7   ri     s   z#HomogeneousGeneralQuadratic.matchesNr   r6   r6   r6   r7   r    r   r  c                   @   &   e Zd ZdZdZdd Zd	ddZdS )
GeneralSumOfSquaresa  
    Representation of the diophantine equation

    `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.

    Details
    =======

    When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
    no solutions. Refer [1]_ for more details.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfSquares
    >>> from sympy.abc import a, b, c, d, e
    >>> GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve()
    {(15, 22, 22, 24, 24)}

    By default only 1 solution is returned. Use the `limit` keyword for more:

    >>> sorted(GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve(limit=3))
    [(15, 22, 22, 24, 24), (16, 19, 24, 24, 24), (16, 20, 22, 23, 26)]

    References
    ==========

    .. [1] Representing an integer as a sum of three squares, [online],
        Available:
        http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
    general_sum_of_squaresc                    sR    j dkr
 jdksdS  jsdS tdd  jD rdS t fdd jD S )Nr   r   Fc                 s   r  r<   r  r   r6   r6   r7   rV     r  z.GeneralSumOfSquares.matches.<locals>.<genexpr>c                 3   &    | ]}|d kr j | d kV  qdS rX   Nr   r   rh   r6   r7   rV        $ )rb   rf   re   r   r^   r_   rh   r6   rh   r7   ri     s   zGeneralSumOfSquares.matchesNrX   c           
         s   |  | | j}t| jd  }| j}t|| jd}|dk s"|dk r$|S dd |D   ddk}d}t||ddD ]#}	|rN|	 fd	dt
|	D  n|	|	 |d7 }||kr^ |S q;|S )
NrX   r|   r   c                 S      g | ]	}|j r	d ndqS r   rX   Zis_nonpositiverT   r   r6   r6   r7   r     r   z-GeneralSumOfSquares.solve.<locals>.<listcomp>r   Tzerosc                       g | ]
\}} | | qS r6   r6   rT   r   r   Zsignsr6   r7   r         )rt   r[   intr^   rf   r-   r2   countsum_of_squaresr9   r   )
r3   r2   rr   r   r   nrE   negstookr   r6   r  r7   rs     s(   

zGeneralSumOfSquares.solverz   r   r6   r6   r6   r7   r
    s
     	r
  c                   @   s2   e Zd ZdZdZdd Zedd Zdd	d
ZdS )GeneralPythagoreana  
    Representation of the general pythagorean equation,
    `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import GeneralPythagorean
    >>> from sympy.abc import a, b, c, d, e, x, y, z, t
    >>> GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve()
    {(t_0**2 + t_1**2 - t_2**2, 2*t_0*t_2, 2*t_1*t_2, t_0**2 + t_1**2 + t_2**2)}
    >>> GeneralPythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2).solve(parameters=[x, y, z, t])
    {(-10*t**2 + 10*x**2 + 10*y**2 + 10*z**2, 15*t**2 + 15*x**2 + 15*y**2 + 15*z**2, 15*t*x, 12*t*y, 60*t*z)}
    Zgeneral_pythagoreanc                    s    j dkr
 jdksdS  jsdS tdd  jD rdS t fdd jD r+dS t fdd jD s9dS tt fdd jD  jd kS )	Nr   r   Fc                 s   r  r<   r  r   r6   r6   r7   rV   #  r  z-GeneralPythagorean.matches.<locals>.<genexpr>c                 3   r  r  r   r   rh   r6   r7   rV   %  r  c                 3   s"    | ]}t t j| V  qd S r<   )r    r   r^   r   rh   r6   r7   rV   '  s     c                 3   s    | ]
}t  j| V  qd S r<   )r   r^   r   rh   r6   r7   rV   +  s    )rb   rf   re   r   r^   r_   r   sumrh   r6   rh   r7   ri     s   &zGeneralPythagorean.matchesc                 C   s
   | j d S rz   rj   rh   r6   r6   r7   rk   -  s   
zGeneralPythagorean.n_parametersNrX   c                    s  |  | | j}| j}| jt||d d  t||d d   t||d d   dk r<| D ]	}||  ||< q2t|| jd}d}t|D ]\}}	t||	d  dkrY|}qI|j t	dd  D }
|
d d  d   g}|
 fdd	td D  |d | |
g ||d   }d}t|D ];\}}	||ks|dkr|dks|dkr|dkrt|tt||	d  }qt||	d  }t|t|r|n|d }qt|D ]\}}	|||  tt||	d   ||< q|| |S )
Nr   r   rX   r|   r   c                 s   s    | ]}|d  V  qdS r   r6   )rT   Zm_ir6   r6   r7   rV   F  rW   z+GeneralPythagorean.solve.<locals>.<genexpr>c                    s$   g | ]}d  |   d    qS r   r6   r   r  r  r6   r7   r   H     $ z,GeneralPythagorean.solve.<locals>.<listcomp>)rt   r^   r[   rf   r   keysr-   r2   r   r   extendr   r   r   r   _oddr9   )r3   r2   rr   r^   r   rP   rE   r   r   r   Zithr   r   Zlcmr   r6   r"  r7   rs   1  s8   
@"(&
zGeneralPythagorean.solverz   )	rH   rI   rJ   rK   rq   ri   rv   rk   rs   r6   r6   r6   r7   r    s    
r  c                   @   r   )	CubicThuea  
    Representation of a cubic Thue diophantine equation.

    A cubic Thue diophantine equation is a polynomial of the form
    `f(x, y) = r` of degree 3, where `x` and `y` are integers
    and `r` is a rational number.

    No solver is currently implemented for this equation type.

    Examples
    ========

    >>> from sympy.abc import x, y
    >>> from sympy.solvers.diophantine.diophantine import CubicThue
    >>> c1 = CubicThue(x**3 + y**2 + 1)
    >>> c1.matches()
    True

    Z
cubic_thuec                 C   s   | j dko	| jdkS )Nr   r   r   rh   r6   r6   r7   ri   q  r   zCubicThue.matchesNr   r6   r6   r6   r7   r'  Z  s    r'  c                   @   r	  )
GeneralSumOfEvenPowersas  
    Representation of the diophantine equation

    `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`

    where `e` is an even, integer power.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfEvenPowers
    >>> from sympy.abc import a, b
    >>> GeneralSumOfEvenPowers(a**4 + b**4 - (2**4 + 3**4)).solve()
    {(2, 3)}

    Zgeneral_sum_of_even_powersc                    sT    j dksdS  j d dkrdS t fdd jD sdS t fdd jD S )Nr   Fr   r   c                 3   s*    | ]}|d kr|j o|j jkV  qdS r  )is_Powexprb   r   rh   r6   r7   rV     s   ( z1GeneralSumOfEvenPowers.matches.<locals>.<genexpr>c                 3   r  r  r   r   rh   r6   r7   rV     r  )rb   r_   r^   rh   r6   rh   r7   ri     s   
zGeneralSumOfEvenPowers.matchesNrX   c                    s   |  | | j}| j}d }| D ]}|jr|| r|j}qt|}|d  }t|| jd}	|dk s6|dk r8|	S dd |D   	ddk}
d}t
|||D ]#}|
ra|	 fddt|D  n|	| |d7 }||krq |	S qN|	S )NrX   r|   r   c                 S   r  r  r  r  r6   r6   r7   r     r   z0GeneralSumOfEvenPowers.solve.<locals>.<listcomp>r   c                    r  r6   r6   r  r   r6   r7   r     r  )rt   r[   r^   r$  r)  r*  r8   r-   r2   r  power_representationr9   r   )r3   r2   rr   r   r^   r   r   r   r  rE   r  r  r   r6   r   r7   rs     s4   


zGeneralSumOfEvenPowers.solverz   r   r6   r6   r6   r7   r(  u  s
    	r(  c                 C   s   h | ]}|j qS r6   )rq   )rT   
diop_classr6   r6   r7   	<setcomp>  r   r-  c                 C   s$   zt |  W dS  ty   Y d S w )NT)r   r0   r   r6   r6   r7   rS     s   rS   c                  G   s   t t| S r<   )r1   sortedr.  r6   r6   r7   _sorted_tuple     r0  c                     s   zt |   W n- ty)   ttd | }t|dk r|  Y S t dd |D   Y n ty3   tdw  dkr:| S t fdd| D S )Nr   c                 S   s   g | ]}|  d  qS r   )as_content_primitiver   r6   r6   r7   r         z_remove_gcd.<locals>.<listcomp>z-_remove_gcd(a,b,c) or _remove_gcd(*container)rX   c                    s   g | ]}|  qS r6   r6   r   r   r6   r7   r     r   )r   r0   rF   filterr8   ra   r1   )r   Zfxr6   r5  r7   r     s   r   c                 C   s   t t||  t|S r<   )r   r   r   r   r   r6   r6   r7   r     s   r   c                 C   s.   t | |\}}t|t|d kr|S |d S )Nr   rX   )r   r   )r   r   wr   r6   r6   r7   _nint_or_floor  s   r9  c                 C   s   | d dkS Nr   r   r6   r.  r6   r6   r7   r&    r1  r&  c                 C   s   | d dkS r:  r6   r.  r6   r6   r7   _even  r1  r;  r   Trl   NFc           )   	      s  ddl m}m}m} t| } t| tr| j| j } zt	| j
ddjjtd |r[t|s3tdfdd|D }|kr[tt|tt|fd	d
t| ||dD W S |  \} |jrht W S  jst }t|| }	 fdd
|	D W S |} t| } | jrJ | jddid } t| }
tdd |
jD rJ |
 } |  sJ W n tt fy   tt!dw d}d}d}zt"| \}}}|rt|}t#j$t%j$g}t&j$t'j$t(j$g}||v rd}n||v r|dkrdt	||d}d}d}t)dd |}|D ]}z|| }W n t*y   d}Y nw t+|o&t+|}q	t	||d}|D ]!}z||d  }W n t*yH   d}Y nw t+|oQt+|}q2t||gs^d}ny|scd}ns|dkrt	||d}d}d}t)dd |}|D ]}z|| }W n t*y   d}Y nw t+|ot+|}q}t	||d}|D ]!}z||d  }W n t*y   d}Y nw t+|ot+|}qt||gsd}n|sd}|dkr| dfg}ntW n/ tt,fy   t-| }|d j.r|d dkrt| |d  |||d Y S |d }Y nw t }|D ]Y}|\}} t"|dd\}!} }"t/|dd0 \} }t1||}#|"t2j$t&j$t'j$t3j$fv rP|4t5|!|# q|"t(j$t#j$t%j$t6j$fv rn|#D ]|4t5|! q_qt,d|" d|v r~|7d t8dgt }$|s| 9t|$j:r|4|$ t }%|D ]Xt;dd D r|rt|}&|%<|& q|rt	|}'t	t=fdd|'}'t|'}&|%<|& q|rt|}(|%<|( q|%4 q|%4 q|%S ) a;	  
    Simplify the solution procedure of diophantine equation ``eq`` by
    converting it into a product of terms which should equal zero.

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

    For example, when solving, `x^2 - y^2 = 0` this is treated as
    `(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved
    independently and combined. Each term is solved by calling
    ``diop_solve()``. (Although it is possible to call ``diop_solve()``
    directly, one must be careful to pass an equation in the correct
    form and to interpret the output correctly; ``diophantine()`` is
    the public-facing function to use in general.)

    Output of ``diophantine()`` is a set of tuples. The elements of the
    tuple are the solutions for each variable in the equation and
    are arranged according to the alphabetic ordering of the variables.
    e.g. For an equation with two variables, `a` and `b`, the first
    element of the tuple is the solution for `a` and the second for `b`.

    Usage
    =====

    ``diophantine(eq, t, syms)``: Solve the diophantine
    equation ``eq``.
    ``t`` is the optional parameter to be used by ``diop_solve()``.
    ``syms`` is an optional list of symbols which determines the
    order of the elements in the returned tuple.

    By default, only the base solution is returned. If ``permute`` is set to
    True then permutations of the base solution and/or permutations of the
    signs of the values will be returned when applicable.

    Examples
    ========

    >>> from sympy.solvers.diophantine import diophantine
    >>> from sympy.abc import a, b
    >>> eq = a**4 + b**4 - (2**4 + 3**4)
    >>> diophantine(eq)
    {(2, 3)}
    >>> diophantine(eq, permute=True)
    {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}

    Details
    =======

    ``eq`` should be an expression which is assumed to be zero.
    ``t`` is the parameter to be used in the solution.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> diophantine(x**2 - y**2)
    {(t_0, -t_0), (t_0, t_0)}

    >>> diophantine(x*(2*x + 3*y - z))
    {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)}
    >>> diophantine(x**2 + 3*x*y + 4*x)
    {(0, n1), (3*t_0 - 4, -t_0)}

    See Also
    ========

    diop_solve()
    sympy.utilities.iterables.permute_signs
    sympy.utilities.iterables.signed_permutations
    r   )subsetspermute_signssigned_permutationsTrN   rO   z/syms should be given as a sequence, e.g. a listc                    s   g | ]}| v r|qS r6   r6   r   )r   r6   r7   r   O  r4  zdiophantine.<locals>.<listcomp>c                    s$   h | ] t  fd dD qS )c                    s   g | ]} |  qS r6   r6   r   )dict_sym_indexr   r6   r7   r   R  r4  z)diophantine.<locals>.<setcomp>.<listcomp>)r1   )rT   )r?  r   )r   r7   r-  R  s    zdiophantine.<locals>.<setcomp>)permutec                    s$   h | ]}t  t|r|qS r6   )r	   rB   r@   rT   r   )r   r   r6   r7   r-  Z  r#  as_AddFrX   c                 s   r  r<   )	is_number)rT   r   r6   r6   r7   rV   a  r  zdiophantine.<locals>.<genexpr>z@
    Equation should be a polynomial with Rational coefficients.r   r   c                 S      | d | d  S Nr   rX   r6   )r   r6   r6   r7   r         zdiophantine.<locals>.<lambda>c                 S   rD  rE  r6   r   r6   r6   r7   r     rF  r  )paramsymsr@  _dict)Zevaluatezunhandled type: %sr6   c                 s   rQ   r<   rR   rA  r6   r6   r7   rV     rW   c                    s    | d | d   d  d  kS rE  r6   rG  r   r6   r7   r          )>sympy.utilities.iterablesr<  r=  r>  r   r   r   ZlhsZrhsrF   rY   r[   r\   r(   r   ra   r?   r@   r   r8   r+   Zas_numer_denomrC  rd   r   as_independentr$   r   ZgensZas_exprZis_polynomialr#   AssertionErrorr*   r,   r
  rq   r(  r   r   r   mapKeyErrorboolrp   r%   Zis_Rationalr&   r   r   r   r  r9   merge_solutionrx   remover1   rB   Zis_zeror_   r>   r6  ))r   rH  rI  r@  r<  r=  r>  r  ZdsolZgoodr   Zdo_permute_signsZdo_permute_signs_varZpermute_few_signsr   rU   r   Zlen_varZpermute_signs_forZpermute_signs_checkZvar_mulZxy_coeffZx_coeffZvar1_mul_var2Z	v1_mul_v2r^   Zv1termsZflr   r   baser   var_teq_typer;   ZnullZ
final_solnZpermuted_signZlstZpermuted_sign_varr6   )r   r?  r   r   r7   r+     s:  I









c                 C   s   g }d|v rdS t |}tdddd}| D ]}||v r#|t| q|t| qt|| D ]\}}t|fi |jdu rDt   S q0t|S )a'  
    This is used to construct the full solution from the solutions of sub
    equations.

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

    For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`,
    solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are
    found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But
    we should introduce a value for z when we output the solution for the
    original equation. This function converts `(t, t)` into `(t, t, n_{1})`
    where `n_{1}` is an integer parameter.
    Nr6   r  TrX   )rm   startF)iterr)   r   nextr@   r   Zassumptions0r1   )r   rW  r;   r   r   r   valZsymbr6   r6   r7   rS    s   
rS  c                 C   s.   t D ]}||  r|| j|d  S qd S )Nr|   )all_diop_classesri   rs   )r   r   	diop_typer6   r6   r7   _diop_solve"  s
   r_  c                 C   s   t | dd\}}}|tjkrt| |S |tjkrt| |S |tjkr(t| ddS |tjkr3t	| ddS |t
jkr=t| |S |tjkrFt| S |tjkrRt| tjdS |tjkr^t| tjdS |durl|tvrlttdtd| )	a  
    Solves the diophantine equation ``eq``.

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

    Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses
    ``classify_diop()`` to determine the type of the equation and calls
    the appropriate solver function.

    Use of ``diophantine()`` is recommended over other helper functions.
    ``diop_solve()`` can return either a set or a tuple depending on the
    nature of the equation.

    Usage
    =====

    ``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t``
    as a parameter if needed.

    Details
    =======

    ``eq`` should be an expression which is assumed to be zero.
    ``t`` is a parameter to be used in the solution.

    Examples
    ========

    >>> from sympy.solvers.diophantine import diop_solve
    >>> from sympy.abc import x, y, z, w
    >>> diop_solve(2*x + 3*y - 5)
    (3*t_0 - 5, 5 - 2*t_0)
    >>> diop_solve(4*x + 3*y - 4*z + 5)
    (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
    >>> diop_solve(x + 3*y - 4*z + w - 6)
    (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)
    >>> diop_solve(x**2 + y**2 - 5)
    {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}


    See Also
    ========

    diophantine()
    FrJ  T)parameterizerr   Nz
    Alhough this type of equation was identified, it is not yet
    handled. It should, however, be listed in `diop_known` at the
    top of this file. Developers should see comments at the end of
    `classify_diop`.
            ro   )r,   r   rq   diop_linearr   diop_quadraticr   diop_ternary_quadraticr   diop_ternary_quadratic_normalr  diop_general_pythagoreanrx   diop_univariater
  diop_general_sum_of_squaresr   ZInfinityr(  diop_general_sum_of_even_powers
diop_knownr0   r*   rp   )r   rH  r   r^   rX  r6   r6   r7   r   (  s,   /










r   c                 C   s^   d}d }t D ]}|| }| rd} nq|r)|j|r#t|j|jfS |j|jfS ttd)NFTz
        This equation is not yet recognized or else has not been
        simplified sufficiently to put it in a form recognized by
        diop_classify().)r]  ri   r[   r?   r^   rq   rp   r*   )r   rK  Zmatchedr^  r,  r6   r6   r7   r,   }  s   $
a  
    Helper routine used by diop_solve() to find information about ``eq``.

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

    Returns a tuple containing the type of the diophantine equation
    along with the variables (free symbols) and their coefficients.
    Variables are returned as a list and coefficients are returned
    as a dict with the key being the respective term and the constant
    term is keyed to 1. The type is one of the following:

    * %s

    Usage
    =====

    ``classify_diop(eq)``: Return variables, coefficients and type of the
    ``eq``.

    Details
    =======

    ``eq`` should be an expression which is assumed to be zero.
    ``_dict`` is for internal use: when True (default) a dict is returned,
    otherwise a defaultdict which supplies 0 for missing keys is returned.

    Examples
    ========

    >>> from sympy.solvers.diophantine import classify_diop
    >>> from sympy.abc import x, y, z, w, t
    >>> classify_diop(4*x + 6*y - 4)
    ([x, y], {1: -4, x: 4, y: 6}, 'linear')
    >>> classify_diop(x + 3*y -4*z + 5)
    ([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
    >>> classify_diop(x**2 + y**2 - x*y + x + 5)
    ([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic')
    z
    * c                 C   s   t | dd\}}}|tjkrLd}|dur td|t|f dd}t| j|d}|du r6|dgt|j  }t|dkrBt|d S tdgt|j S dS )	am  
    Solves linear diophantine equations.

    A linear diophantine equation is an equation of the form `a_{1}x_{1} +
    a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
    integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.

    Usage
    =====

    ``diop_linear(eq)``: Returns a tuple containing solutions to the
    diophantine equation ``eq``. Values in the tuple is arranged in the same
    order as the sorted variables.

    Details
    =======

    ``eq`` is a linear diophantine equation which is assumed to be zero.
    ``param`` is the parameter to be used in the solution.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_linear
    >>> from sympy.abc import x, y, z
    >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0
    (3*t_0 - 5, 2*t_0 - 5)

    Here x = -3*t_0 - 5 and y = -2*t_0 - 5

    >>> diop_linear(2*x - 3*y - 4*z -3)
    (t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)

    See Also
    ========

    diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(),
    diop_general_sum_of_squares()
    FrJ  Nz%s_0:%iTrl   r|   r   )	r,   r   rq   r   r8   rs   r2   rF   r1   )r   rH  r   r^   r^  r2   rE   r6   r6   r7   rb    s   (
rb  c                 C   s   t ||| \}}} | dkr#|dur!|dk r| }|| | | fS dS tt|t|\}}}|t|9 }|t|9 }t| |rc|dur[|dk rK| }| | ||  | | ||  fS | | | | fS dS )a  
    Return the base solution for the linear equation, `ax + by = c`.

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

    Used by ``diop_linear()`` to find the base solution of a linear
    Diophantine equation. If ``t`` is given then the parametrized solution is
    returned.

    Usage
    =====

    ``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients
    in `ax + by = c` and ``t`` is the parameter to be used in the solution.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import base_solution_linear
    >>> from sympy.abc import t
    >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
    (-5, 5)
    >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
    (0, 0)
    >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
    (3*t - 5, 5 - 2*t)
    >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
    (7*t, -5*t)
    r   Nr   r   ru   )r   r   r   r   r   )rU   r   r   r   r   r   r   r6   r6   r7   r     s"   
 r   c                 C   s@   t | dd\}}}|tjkrdd t| |d tjD S dS )a  
    Solves a univariate diophantine equations.

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

    A univariate diophantine equation is an equation of the form
    `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
    integer constants and `x` is an integer variable.

    Usage
    =====

    ``diop_univariate(eq)``: Returns a set containing solutions to the
    diophantine equation ``eq``.

    Details
    =======

    ``eq`` is a univariate diophantine equation which is assumed to be zero.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_univariate
    >>> from sympy.abc import x
    >>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0
    {(2,), (3,)}

    FrJ  c                 S   s   h | ]}t |fqS r6   r  r   r6   r6   r7   r-  X      z"diop_univariate.<locals>.<setcomp>r   N)r,   rx   rq   r'   r}   r   r~   r   r   r^   r^  r6   r6   r7   rg  6  s   
rg  c                 C   s
   | |  S )zN
    Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.
    r6   r7  r6   r6   r7   r   \  s   
r   c                 C   sR   t | dd\}}}|tjkr'|dur|tdddg}nd}tt| j|dS dS )a  
    Solves quadratic diophantine equations.

    i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a
    set containing the tuples `(x, y)` which contains the solutions. If there
    are no solutions then `(None, None)` is returned.

    Usage
    =====

    ``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine
    equation. ``param`` is used to indicate the parameter to be used in the
    solution.

    Details
    =======

    ``eq`` should be an expression which is assumed to be zero.
    ``param`` is a parameter to be used in the solution.

    Examples
    ========

    >>> from sympy.abc import x, y, t
    >>> from sympy.solvers.diophantine.diophantine import diop_quadratic
    >>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
    {(-1, -1)}

    References
    ==========

    .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
          Available: http://www.alpertron.com.ar/METHODS.HTM
    .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
          Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf

    See Also
    ========

    diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(),
    diop_general_pythagorean()
    FrJ  Nr   Trl   r|   )r,   r   rq   r   rd   rs   )r   rH  r   r^   r^  r2   r6   r6   r7   rc  c  s   +
rc  c                    s8   t t| ||f t fdd| D  }t|dkS )z
    Check whether `(u, v)` is solution to the quadratic binary diophantine
    equation with the variable list ``var`` and coefficient dictionary
    ``coeff``.

    Not intended for use by normal users.
    c                    s   g | ]\}}||   qS r6   )Zxreplacer  Zrepsr6   r7   r     s    z$is_solution_quad.<locals>.<listcomp>r   )r?   r@   r   itemsr	   )r   r^   r   r   r   r6   ro  r7   r     s   r   c                    s  | dk rR|dkrdgS |dk rg S |dkrPg }t t|D ]0}td|  ||d  }|rM|D ]\}}||| || f | dkrL||| || f q.q|S dS | dkru|dk r\g S |dkred|fgS t|d\}}	|	rs||fgS g S t| d\}
}	|	r|dkr|
| |fgS g }ttt||d  d|
  d D ]&}zt| |d  | d\}}	W n ty   d}	Y nw |	r|||f q|S d|d   k r| k rn nt	| |S |dkrdgS t
|dkrtdd| }d}g }g }|D ]&}|d }||d  ||d  |dkr|d|
 kr n|d }qt|rf|dkr3||d  }||d  }nG|}|d| d k r]t|}||d  ||d  |d7 }|d| d k s>|| }|| }n|dkrx||d  }||d  }ng S ||fgS g }g }t |}|D ]}t||d r|| q|D ]}||d   t| t
 d	d
} fdd|D }t
 dkr|dd |D  }|D ]}t|t
 | }d}g }g }|D ]}||d  ||d  |dkrUt
|d dkrU||d  }||d  }|d | |d    kr||| || f n6t| dg krSt| d}||||d d  |d d | |    |||d d  ||d d    f  n|d }|t|t
 | krf nqڐqȐq|S )a3  
    Solves the equation `x^2 - Dy^2 = N`.

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

    Mainly concerned with the case `D > 0, D` is not a perfect square,
    which is the same as the generalized Pell equation. The LMM
    algorithm [1]_ is used to solve this equation.

    Returns one solution tuple, (`x, y)` for each class of the solutions.
    Other solutions of the class can be constructed according to the
    values of ``D`` and ``N``.

    Usage
    =====

    ``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and
    ``t`` is the parameter to be used in the solutions.

    Details
    =======

    ``D`` and ``N`` correspond to D and N in the equation.
    ``t`` is the parameter to be used in the solutions.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_DN
    >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
    [(3, 1), (393, 109), (36, 10)]

    The output can be interpreted as follows: There are three fundamental
    solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
    and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means
    that `x = 3` and `y = 1`.

    >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
    [(49299, 1570)]

    See Also
    ========

    find_DN(), diop_bf_DN()

    References
    ==========

    .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
        Robertson, July 31, 2004, Pages 16 - 17. [online], Available:
        https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
    r   rk  rX   r   r   F   r   TZ	all_rootsc                    s    g | ]}|t  d  kr|qS r!  r   r   r  r6   r7   r   G  rL  zdiop_DN.<locals>.<listcomp>c                 S   s   g | ]}|r| qS r6   r6   r   r6   r6   r7   r   J  rm  N)r   square_factor
cornacchiar   r   r   r   r   r0   _special_diop_DNr   PQar&  r[  r   r"   r   length)r   r   r   r   r   r   r   r   ZsN_exactsDsqZpqar   Gr   r   r   r  Zfsr   fZzsr   r   r   r6   rt  r7   r     s   6

(








Rr   c                 C   s6  t | }|dfg}d}	 |d }|t|krnt||\}}|dkr)|||f |d7 }qd}d}	d\}
}d\}}g }d}	 t|| |	 }||	 | }| |d  |	 }	|| |
 }|| | }|D ]\}}|d | |d   |kr~||| || f qc|d7 }|	dkr|d dkr	 |S ||}
}||}}q?)a1  
    Solves the equation `x^2 - Dy^2 = N` for the special case where
    `1 < N**2 < D` and `D` is not a perfect square.
    It is better to call `diop_DN` rather than this function, as
    the former checks the condition `1 < N**2 < D`, and calls the latter only
    if appropriate.

    Usage
    =====

    WARNING: Internal method. Do not call directly!

    ``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`.

    Details
    =======

    ``D`` and ``N`` correspond to D and N in the equation.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import _special_diop_DN
    >>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3
    [(7, 2), (137, 38)]

    The output can be interpreted as follows: There are two fundamental
    solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and
    (137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means
    that `x = 7` and `y = 2`.

    >>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20
    [(445, 9), (17625560, 356454), (698095554475, 14118073569)]

    See Also
    ========

    diop_DN()

    References
    ==========

    .. [1] Section 4.4.4 of the following book:
        Quadratic Diophantine Equations, T. Andreescu and D. Andrica,
        Springer, 2015.
    rX   r   Tr   r   rX   rX   r   )r   r   r   r   r   )r   r   Zsqrt_Dr   r~  f2r  r   r   r   ZG0ZG1ZB0ZB1r=   r   r   ZG2ZB2r6   r6   r7   rw  l  sF   6
	

rw  c                 C   s   t  }t| |d }t| | |dd}|sdS |D ]S}||d k r#q||}}	 ||| }}| |d  |k r9nq)|| |d   }	|	| dkrm|	| }	t|	d\}
}|rm| |krb||
k rb|
|}}
|t|t|
f q|S )a9  
    Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`.

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

    Uses the algorithm due to Cornacchia. The method only finds primitive
    solutions, i.e. ones with `\gcd(x, y) = 1`. So this method can't be used to
    find the solutions of `x^2 + y^2 = 20` since the only solution to former is
    `(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the
    solutions with `x \leq y` are found. For more details, see the References.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import cornacchia
    >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35
    {(2, 3), (4, 1)}
    >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25
    {(4, 3)}

    References
    ===========

    .. [1] A. Nitaj, "L'algorithme de Cornacchia"
    .. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's
        method, [online], Available:
        http://www.numbertheory.org/php/cornacchia.html

    See Also
    ========

    sympy.utilities.iterables.signed_permutations
    r   Trr  Nr   )rd   r   r"   r   r9   r  )r   r   r  r   Za1r   r   r   r   Zm1r   rz  r6   r6   r7   rv    s0   #

rv  c                 c   s    d }}d }}|  }|}| }	|}
	 t |	t| |
 }|| | }|| | }|| | }|	|
||||fV  ||}}||}}||}}||
 |	 }	||	d  |
 }
q)a  
    Returns useful information needed to solve the Pell equation.

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

    There are six sequences of integers defined related to the continued
    fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`},
    {`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns
    these values as a 6-tuple in the same order as mentioned above. Refer [1]_
    for more detailed information.

    Usage
    =====

    ``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding
    to `P_{0}`, `Q_{0}` and `D` in the continued fraction
    `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`.
    Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import PQa
    >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4
    >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0)
    (13, 4, 3, 3, 1, -1)
    >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1)
    (-1, 1, 1, 4, 1, 3)

    References
    ==========

    .. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P.
        Robertson, July 31, 2004, Pages 4 - 8. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
    r   rX   Tr   )r   r   )ZP_0ZQ_0r   ZA_i_2ZB_i_1ZA_i_1ZB_i_2ZG_i_2ZG_i_1ZP_iZQ_iZa_iZA_iZB_iZG_ir6   r6   r7   rx  	  s&   %


rx  c              	   C   s  t | } t |}g }t| d}|d d }t|dkr t| |S |dkr:d}tt||d  d|   dd d }nT|dk rett||   d\}}|sP|d7 }tt||d  d|    dd d }n)| dk rldgS | dkrud|fgS t| d\}	}|r|	| |f|	 | |fgS dgS t||D ]8}
zt|| |
d   d\}}W n ty   d}Y nw |r|||
f t||
| |
| |s|| |
f q|S )a  
    Uses brute force to solve the equation, `x^2 - Dy^2 = N`.

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

    Mainly concerned with the generalized Pell equation which is the case when
    `D > 0, D` is not a perfect square. For more information on the case refer
    [1]_. Let `(t, u)` be the minimal positive solution of the equation
    `x^2 - Dy^2 = 1`. Then this method requires
    `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small.

    Usage
    =====

    ``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in
    `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions.

    Details
    =======

    ``D`` and ``N`` correspond to D and N in the equation.
    ``t`` is the parameter to be used in the solutions.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_bf_DN
    >>> diop_bf_DN(13, -4)
    [(3, 1), (-3, 1), (36, 10)]
    >>> diop_bf_DN(986, 1)
    [(49299, 1570)]

    See Also
    ========

    diop_DN()

    References
    ==========

    .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
        Robertson, July 31, 2004, Page 15. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
    rX   r   r   r   rk  F)	r   r   r   r   r  r   r0   r   
equivalent)r   r   r   r   r   r   ZL1ZL2rz  r{  r   r   r6   r6   r7   
diop_bf_DNL	  sF   -

(*
r  c                 C   s0   t | | || |  |ot | | ||  |S )aV  
    Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N`
    belongs to the same equivalence class and False otherwise.

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

    Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same
    equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by
    `N`. See reference [1]_. No test is performed to test whether `(u, v)` and
    `(r, s)` are actually solutions to the equation. User should take care of
    this.

    Usage
    =====

    ``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions
    of the equation `x^2 - Dy^2 = N` and all parameters involved are integers.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import equivalent
    >>> equivalent(18, 5, -18, -5, 13, -1)
    True
    >>> equivalent(3, 1, -18, 393, 109, -4)
    False

    References
    ==========

    .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
        Robertson, July 31, 2004, Page 12. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf

    )r   )r   r   r   r   r   r   r6   r6   r7   r  	  s   0$r  c                 C   s\   ddl m} || ||}t|d tu r$t|d }t|d }|| S d}t|}|| S )aw  
    Returns the (length of aperiodic part + length of periodic part) of
    continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`.

    It is important to remember that this does NOT return the length of the
    periodic part but the sum of the lengths of the two parts as mentioned
    above.

    Usage
    =====

    ``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to
    the continued fraction `\\frac{P + \sqrt{D}}{Q}`.

    Details
    =======

    ``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction,
    `\\frac{P + \sqrt{D}}{Q}`.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import length
    >>> length(-2 , 4, 5) # (-2 + sqrt(5))/4
    3
    >>> length(-5, 4, 17) # (-5 + sqrt(17))/4
    4

    See Also
    ========
    sympy.ntheory.continued_fraction.continued_fraction_periodic
    r   )continued_fraction_periodicr   rX   )Z sympy.ntheory.continued_fractionr  typerF   r8   )r   r   r   r  r   ZrptZnonrptr6   r6   r7   ry  	  s   "ry  c                 C   *   t | dd\}}}|tjkrt||S dS )aD  
    This function transforms general quadratic,
    `ax^2 + bxy + cy^2 + dx + ey + f = 0`
    to more easy to deal with `X^2 - DY^2 = N` form.

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

    This is used to solve the general quadratic equation by transforming it to
    the latter form. Refer [1]_ for more detailed information on the
    transformation. This function returns a tuple (A, B) where A is a 2 X 2
    matrix and B is a 2 X 1 matrix such that,

    Transpose([x y]) =  A * Transpose([X Y]) + B

    Usage
    =====

    ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be
    transformed.

    Examples
    ========

    >>> from sympy.abc import x, y
    >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN
    >>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
    >>> A
    Matrix([
    [1/26, 3/26],
    [   0, 1/13]])
    >>> B
    Matrix([
    [-6/13],
    [-4/13]])

    A, B  returned are such that Transpose((x y)) =  A * Transpose((X Y)) + B.
    Substituting these values for `x` and `y` and a bit of simplifying work
    will give an equation of the form `x^2 - Dy^2 = N`.

    >>> from sympy.abc import X, Y
    >>> from sympy import Matrix, simplify
    >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x
    >>> u
    X/26 + 3*Y/26 - 6/13
    >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y
    >>> v
    Y/13 - 4/13

    Next we will substitute these formulas for `x` and `y` and do
    ``simplify()``.

    >>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v))))
    >>> eq
    X**2/676 - Y**2/52 + 17/13

    By multiplying the denominator appropriately, we can get a Pell equation
    in the standard form.

    >>> eq * 676
    X**2 - 13*Y**2 + 884

    If only the final equation is needed, ``find_DN()`` can be used.

    See Also
    ========

    find_DN()

    References
    ==========

    .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
           John P.Robertson, May 8, 2003, Page 7 - 11.
           https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
    FrJ  N)r,   r   rq   r   rn  r6   r6   r7   transformation_to_DN	  s   N

r  c                 C   s$  | \}}||d  }|||  }||d  }|| }|| }|d }	dd t ||||||	D \}}}}}}	tddd\}
}|rtd| |\}}t||d \}}|
d || |
| d|d ||| ||d    |
|| ||| | || |  d|	| | i}t|
|g|\}}tddtj| t| | ddg| tddtj| t| | ddg| fS |rtd| |\}}t||d \}}|
d ||
| d|d || |
d||| d|	| ||d   i}t|
|g|\}}tddtj| dddg| tddtj| dddg| tt| | dg fS |rtd| |\}}t||d \}}|
d || |
| d|d ||
d|dd|	| ||d   i}t|
|g|\}}tdddddtj| g| tdddddtj| g| tdt| | g fS tddtj| dddgtddgfS )	Nr   rX   c                 S   r   r6   r   r   r6   r6   r7   r   Y
  r   z)_transformation_to_DN.<locals>.<listcomp>X, YTrl   r   )r   r   r   r   r   r   r   )r   r^   r   r   r   r   rU   r   r   r~  r   r   r   r   r   r   ZA_0B_0r6   r6   r7   r   N
  s8   (`P@R<R&r   c                 C   r  )a  
    This function returns a tuple, `(D, N)` of the simplified form,
    `x^2 - Dy^2 = N`, corresponding to the general quadratic,
    `ax^2 + bxy + cy^2 + dx + ey + f = 0`.

    Solving the general quadratic is then equivalent to solving the equation
    `X^2 - DY^2 = N` and transforming the solutions by using the transformation
    matrices returned by ``transformation_to_DN()``.

    Usage
    =====

    ``find_DN(eq)``: where ``eq`` is the quadratic to be transformed.

    Examples
    ========

    >>> from sympy.abc import x, y
    >>> from sympy.solvers.diophantine.diophantine import find_DN
    >>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
    (13, -884)

    Interpretation of the output is that we get `X^2 -13Y^2 = -884` after
    transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned
    by ``transformation_to_DN()``.

    See Also
    ========

    transformation_to_DN()

    References
    ==========

    .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
           John P.Robertson, May 8, 2003, Page 7 - 11.
           https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
    FrJ  N)r,   r   rq   r   rn  r6   r6   r7   find_DN
  s   '

r  c                 C   s  | \}}t ddd\}}t| |\}}|t||g | d }|t||g | d }	|d ||d   || |||    |d ||d    |||   |||   |d  }
t|
t||f||	f}| }||d   ||d   |d  ||d   fS )Nr  Trl   r   rX   r   )r   r   r   r	   rB   r@   r]   )r   r^   r   r   r   r   r   r   r   r   r   Z
simplifiedr6   r6   r7   r   
  s   \0r   c                 C   s   ddl m} | jr| jst| |g|dS |jr"|js"t| |g|dS tddd\}}||  ||   \}}||j rCt| |g|dS || |d |||d  }	|	 \}
}	t|	|dS )	z
    If there is a number modulo ``a`` such that ``x`` and ``y`` are both
    integers, then return a parametric representation for ``x`` and ``y``
    else return (None, None).

    Here ``x`` and ``y`` are functions of ``t``.
    r   )clear_coefficientsr|   zm, nTrl   rX   )r   )	sympy.simplify.simplifyr  rC  r   r-   r   r3  r   r_  )r   r   r   r   r  r  r  rU   r   r   Zjunkr6   r6   r7   r   
  s   
r   c           	      C   sz   t | dd\}}}|tjtjfv r;t||}t|dkr&t|d \}}}nd\}}}|r6t|||f||S |||fS dS )a  
    Solves the general quadratic ternary form,
    `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.

    Returns a tuple `(x, y, z)` which is a base solution for the above
    equation. If there are no solutions, `(None, None, None)` is returned.

    Usage
    =====

    ``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution
    to ``eq``.

    Details
    =======

    ``eq`` should be an homogeneous expression of degree two in three variables
    and it is assumed to be zero.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic
    >>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2)
    (1, 0, 1)
    >>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2)
    (1, 0, 2)
    >>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2)
    (28, 45, 105)
    >>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
    (9, 1, 5)
    FrJ  r   r   N)r,   r   rq   r   r   r8   rF   _parametrize_ternary_quadratic	r   r`  r   r^   r^  r   r   r   r   r6   r6   r7   rd  
  s   "


rd  c                    sR   t  fdd D }t| rt|| d S t| r't|| d S d S )Nc                       g | ]}| |  qS r6   r6   r   r   r6   r7   r     r4  z+_diop_ternary_quadratic.<locals>.<listcomp>r   )r   r   ri   rs   r   )r   r^   r   r6   r   r7   r     s   r   c                 C   s(   t | dd\}}}|dv rt||S dS )a<  
    Returns the transformation Matrix that converts a general ternary
    quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`)
    to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is
    not used in solving ternary quadratics; it is only implemented for
    the sake of completeness.
    FrJ  r   r   N)r,   _transformation_to_normalrn  r6   r6   r7   transformation_to_normal  s   
r  c                    sT  t | }| \}}}t fdd| D sT ||  } ||  } ||  }d}	|s1d}	||}}tdd| | fdd| | fdf}
|	rR|
dd |
dd |
S  |d	  dkr |d	  dkr| d	 | d |d< |d	< t| }
|
dd	 |
dd	 |
S | d | d |d< |d< t| }
|
dd |
dd |
S  ||  dks ||  dkrB |d	  } ||  } ||  } |d	  } ||  } |d	  }t }d
|d	  ||d	 < d
| | |d	  ||d	 < d
| | |d	  ||d	 < d
| | d	| |  ||| < d||| < d||| < t||}tdddt| d	|  t| d	|  ddddddg	| S  ||  dkr |d	  dkr |d	  dkretddg dS | d	 | d |d< |d	< t| }
|
dd	 |
dd	 |
S | d | d |d< |d< t| }
|
dd |
dd |
S tdS )Nc                 3   r   r   r6   r   r   r6   r7   rV   *  r   z,_transformation_to_normal.<locals>.<genexpr>FTrX   r   )r   r   rX   r   r   r   r   )	rX   r   r   r   rX   rX   r   rX   r   )	rF   r   r   Zrow_swapZcol_swapr  r?   r   Zeye)r   r^   r   r   r   r   r   r   rU   Zswapr   r   r   r   r   r   r   r  ZT_0r6   r   r7   r  %  st   

&

" 
>


r  c                 C   sH   t | dd\}}}|dv r"tt||d \}}}t|||f||S dS )a  
    Returns the parametrized general solution for the ternary quadratic
    equation ``eq`` which has the form
    `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.

    Examples
    ========

    >>> from sympy import Tuple, ordered
    >>> from sympy.abc import x, y, z
    >>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic

    The parametrized solution may be returned with three parameters:

    >>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2)
    (p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)

    There might also be only two parameters:

    >>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2)
    (2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2)

    Notes
    =====

    Consider ``p`` and ``q`` in the previous 2-parameter
    solution and observe that more than one solution can be represented
    by a given pair of parameters. If `p` and ``q`` are not coprime, this is
    trivially true since the common factor will also be a common factor of the
    solution values. But it may also be true even when ``p`` and
    ``q`` are coprime:

    >>> sol = Tuple(*_)
    >>> p, q = ordered(sol.free_symbols)
    >>> sol.subs([(p, 3), (q, 2)])
    (6, 12, 12)
    >>> sol.subs([(q, 1), (p, 1)])
    (-1, 2, 2)
    >>> sol.subs([(q, 0), (p, 1)])
    (2, -4, 4)
    >>> sol.subs([(q, 1), (p, 0)])
    (-3, -6, 6)

    Except for sign and a common factor, these are equivalent to
    the solution of (1, 2, 2).

    References
    ==========

    .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
           London Mathematical Society Student Texts 41, Cambridge University
           Press, Cambridge, 1998.

    FrJ  r  r   N)r,   rF   r   r  )r   r   r^   r^  r   r   r   r6   r6   r7   parametrize_ternary_quadraticy  s   7r  c              	   C   s<  d|vsJ | \}}}t |}|d u rdS | ddkrdS |dkr@|d |d |d< |d< t|||f||\}}}	|||	fS |\}
}}tddd\}}}tdd	 | D }t|t|
||f|| || | || | f}|j	|dd
\}}|| }
|| t|| |  }|| t|| |  }t
|
||S )NrX   r   r   r   zr, p, qTrl   c                 s   s    | ]	\}}|| V  qd S r<   r6   )rT   r   r   r6   r6   r7   rV     r   z1_parametrize_ternary_quadratic.<locals>.<genexpr>)rB  )rF   r  r  r   r   rp  r	   rB   r@   rN  r   )r;   r   r^   r   r   r   r   Zy_pZx_pZz_pr   r   r   r   r   r   r   Zeq_1r   r   r6   r6   r7   r    s0   



$r  c           	      C   st   t | dd\}}}|tjkr8t||}t|dkr#t|d \}}}nd\}}}|r3t|||f||S |||fS dS )a  
    Solves the quadratic ternary diophantine equation,
    `ax^2 + by^2 + cz^2 = 0`.

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

    Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the
    equation will be a quadratic binary or univariate equation. If solvable,
    returns a tuple `(x, y, z)` that satisfies the given equation. If the
    equation does not have integer solutions, `(None, None, None)` is returned.

    Usage
    =====

    ``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form
    `ax^2 + by^2 + cz^2 = 0`.

    Examples
    ========

    >>> from sympy.abc import x, y, z
    >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal
    >>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2)
    (1, 0, 1)
    >>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2)
    (1, 0, 2)
    >>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2)
    (4, 9, 1)
    FrJ  r   r   N)r,   r   rq   r   r8   rF   r  r  r6   r6   r7   re    s   



re  c                    s&   t  fdd D }t|| d S )Nc                    r  r6   r6   r   r   r6   r7   r     r4  z2_diop_ternary_quadratic_normal.<locals>.<listcomp>r   )r   r   rs   )r   r^   r   r6   r   r7   r     s   r   c                 C   s   t | ||}tdd |D }tdd t||D  }\}}}	t||}
||
 }||
 }t||	}|| }|	| }	t||	}|| }|| }||9 }||9 }|	|
9 }	|r]|||||	ffS |||	fS )a  
    Return `a', b', c'`, the coefficients of the square-free normal
    form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise
    prime.  If `steps` is True then also return three tuples:
    `sq`, `sqf`, and `(a', b', c')` where `sq` contains the square
    factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`;
    `sqf` contains the values of `a`, `b` and `c` after removing
    both the `gcd(a, b, c)` and the square factors.

    The solutions for `ax^2 + by^2 + cz^2 = 0` can be
    recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import sqf_normal
    >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11)
    (11, 1, 5)
    >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True)
    ((3, 1, 7), (5, 55, 11), (11, 1, 5))

    References
    ==========

    .. [1] Legendre's Theorem, Legrange's Descent,
           http://public.csusm.edu/aitken_html/notes/legendre.pdf


    See Also
    ========

    reconstruct()
    c                 s   rQ   r<   )ru  r   r6   r6   r7   rV   6  rW   zsqf_normal.<locals>.<genexpr>c                 S   s   g | ]
\}}||d   qS r!  r6   r  r6   r6   r7   r   7  r  zsqf_normal.<locals>.<listcomp>)r   r1   r@   r   )r   r   rU   r   ABCr|  Zsqfr   r   r   ZpcpaZpbr6   r6   r7   r     s$   ""



r   c                 C   s,   t | tr| nt| }tdd | D  S )a  
    Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square
    free. `a` can be given as an integer or a dictionary of factors.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import square_factor
    >>> square_factor(24)
    2
    >>> square_factor(-36*3)
    6
    >>> square_factor(1)
    1
    >>> square_factor({3: 2, 2: 1, -1: 1})  # -18
    3

    See Also
    ========
    sympy.ntheory.factor_.core
    c                 S   s   g | ]
\}}||d   qS r!  r6   )rT   r   r   r6   r6   r7   r   c  r  z!square_factor.<locals>.<listcomp>)r   r?   r   r
   rp  )r   r~  r6   r6   r7   ru  L  s   ru  c                 C   s<   t t| |}| D ]\}}|dkrtd||9 }q|S )a  
    Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2`
    from the `z` value of a solution of the square-free normal form of the
    equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square
    free and `gcd(a', b', c') == 1`.
    rX   za and b should be square-free)r   r   rp  r0   )r   r   r   r~  r   r   r6   r6   r7   r   f  s   
r   c                 C   s  t | t |krt|| \}}}|||fS | dkrdS |dkr!dS |dkr'dS t| |}|d |  | }|dkr=d}d}n#t|}	d}|	D ]}
tt ||
 d\}}|r_t||
 |}} nqE|durt| |\}}}t|  | ||  || | |||  S dS )a!  
    Return a non-trivial solution to `w^2 = Ax^2 + By^2` using
    Lagrange's method; return None if there is no such solution.
    .

    Here, `A \neq 0` and `B \neq 0` and `A` and `B` are square free. Output a
    tuple `(w_0, x_0, y_0)` which is a solution to the above equation.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import ldescent
    >>> ldescent(1, 1) # w^2 = x^2 + y^2
    (1, 1, 0)
    >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2
    (2, -1, 0)

    This means that `x = -1, y = 0` and `w = 2` is a solution to the equation
    `w^2 = 4x^2 - 7y^2`

    >>> ldescent(5, -1) # w^2 = 5x^2 - y^2
    (2, 1, -1)

    References
    ==========

    .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
           London Mathematical Society Student Texts 41, Cambridge University
           Press, Cambridge, 1998.
    .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
           [online], Available:
           http://eprints.nottingham.ac.uk/60/1/kvxefz87.pdf
    rX   rX   rX   r   rX   r   rX   r   Nr   r   )r   ldescentr"   r   r   r   r   )r   r   r8  r   r   r   r   r  r   r   r   ZsQrz  Wr   r   r6   r6   r7   r  u  s4   "

*r  c                 C   s   t | t |krt|| \}}}|||fS |dkrdS | dkr!dS ||  kr(dS || kr;td| \}}}| | ||fS t| |}t|| |\}}|d | |d   | }t|}	||	d  }
t| |
\}}}t|| | | |  || ||  |
|	 | S )a  
    Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2`
    using Lagrange's descent method with lattice-reduction. `A` and `B`
    are assumed to be valid for such a solution to exist.

    This is faster than the normal Lagrange's descent algorithm because
    the Gaussian reduction is used.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import descent
    >>> descent(3, 1) # x**2 = 3*y**2 + z**2
    (1, 0, 1)

    `(x, y, z) = (1, 0, 1)` is a solution to the above equation.

    >>> descent(41, -113)
    (-16, -3, 1)

    References
    ==========

    .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
           Mathematics of Computation, Volume 00, Number 0.
    rX   r  r  )r   rX   rX   r   r   )r   r   r"   gaussian_reduceru  r   )r   r   r   r   r   r8  r   r   r   Zt_2Zt_1Zx_1Zz_1Zy_1r6   r6   r7   r     s&   


0r   c                 C   s  d}d}t ||| ||dk r|d  |d  f}t|| ||t|| ||k r+||}}t|| ||t|| ||krnt ||| ||t ||| || }||d ||d   |d ||d   f}}t|| ||t|| ||ks9||}}t ||| ||t ||| ||d k st|d |d  |d |d  f| ||t|| ||kr|}n|d |d  |d |d  f}|d |  ||d   |d fS )a  
    Returns a reduced solution `(x, z)` to the congruence
    `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal.

    Details
    =======

    Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)`

    References
    ==========

    .. [1] Gaussian lattice Reduction [online]. Available:
           http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404
    .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
           Mathematics of Computation, Volume 00, Number 0.
    r  r  r   rX   r   )dotnorm)r8  r   r   r   r   r   rU   r6   r6   r7   r    s   
 .
\  r  c           	      C   s@   | \}}|\}}|| ||  || ||   t || |  S )z
    Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and
    `v = (v_{1}, v_{2})` which is defined in order to reduce solution of
    the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`.
    rs  )	r   r   r8  r   r   u_1u_2Zv_1Zv_2r6   r6   r7   r    s   0r  c                 C   s$   | \}}t t||f||f|||S )z
    Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product
    defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}`
    where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`.
    )r   r  )r   r8  r   r   r  r  r6   r6   r7   r  #  s   r  c                 C   s$  t |r	d| }n|d }|| | }d}	 || d  ||d  ||d  }	}
}|	|
 |kr9|dkr8tdn| ||}}}t|	|
||krJnt|||  }\}}d|v rZn|| | || |   || }}t||}t|rt||}t|| tj	ksJ n!|| }t || ||  ||  r|d7 }t|| tj
ksJ ||d  ||d   ||d   }|| | || |  || |  }t|| d| |  |} t|| d| |  |}t|| d| |  |}tdd | ||fD sJ |d7 }qtd	d
 |||fD S )ae  
    Simplify the solution `(x, y, z)` of the equation
    `ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to
    a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`.

    The algorithm is an interpretation of Mordell's reduction as described
    on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in
    reference [2]_.

    References
    ==========

    .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,
           Mathematics of Computation, Volume 00, Number 0.
    .. [2] Diophantine Equations, L. J. Mordell, page 48.

    r   r   Tzbad starting solutionNrX   c                 s   r  r<   )r   r   r6   r6   r7   rV   g  r  zholzer.<locals>.<genexpr>c                 S   r   r6   rl  r   r6   r6   r7   r   j  r   zholzer.<locals>.<listcomp>)r&  r0   maxr   r   r;  r9  r   r   ZHalfr   r_   r1   )r   r   r   r   r   rU   r   Zsmallstept1t2Zt3r   r   r   Zuvr   r   r   r   r   r8  r   r   r6   r6   r7   r   -  sF   
($

$$#r   r  c                 C   s^   t | dd\}}}|tjkr-|du rd}ntd|t|f dd}tt| j|dd S dS )	a  
    Solves the general pythagorean equation,
    `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.

    Returns a tuple which contains a parametrized solution to the equation,
    sorted in the same order as the input variables.

    Usage
    =====

    ``diop_general_pythagorean(eq, param)``: where ``eq`` is a general
    pythagorean equation which is assumed to be zero and ``param`` is the base
    parameter used to construct other parameters by subscripting.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean
    >>> from sympy.abc import a, b, c, d, e
    >>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2)
    (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2)
    >>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2)
    (10*m1**2  + 10*m2**2  + 10*m3**2 - 10*m4**2, 15*m1**2  + 15*m2**2  + 15*m3**2  + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4)
    FrJ  Nz%s1:%iTrl   r|   r   )r,   r  rq   r   r8   rF   rs   )r   rH  r   r^   r^  r   r6   r6   r7   rf  m  s   
rf  rX   c                 C   4   t | dd\}}}|tjkrtt| j|dS dS )a  
    Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.

    Returns at most ``limit`` number of solutions.

    Usage
    =====

    ``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which
    is assumed to be zero. Also, ``eq`` should be in the form,
    `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.

    Details
    =======

    When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
    no solutions. Refer [1]_ for more details.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares
    >>> from sympy.abc import a, b, c, d, e
    >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345)
    {(15, 22, 22, 24, 24)}

    Reference
    =========

    .. [1] Representing an integer as a sum of three squares, [online],
        Available:
        http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
    FrJ  ra  N)r,   r
  rq   rd   rs   r   rr   r   r^   r^  r6   r6   r7   rh    s   "
rh  c                 C   r  )a  
    Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
    where `e` is an even, integer power.

    Returns at most ``limit`` number of solutions.

    Usage
    =====

    ``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which
    is assumed to be zero. Also, ``eq`` should be in the form,
    `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers
    >>> from sympy.abc import a, b
    >>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4))
    {(2, 3)}

    See Also
    ========

    power_representation
    FrJ  ra  N)r,   r(  rq   rd   rs   r  r6   r6   r7   ri    s   
ri  c                 c   s~    ddl m} |r|du r|| |D ]}t|V  qdS td|d D ]}|| |D ]}t|}d|t|  | V  q*q#dS )aD  
    Returns a generator that can be used to generate partitions of an integer
    `n`.

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

    A partition of `n` is a set of positive integers which add up to `n`. For
    example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned
    as a tuple. If ``k`` equals None, then all possible partitions are returned
    irrespective of their size, otherwise only the partitions of size ``k`` are
    returned. If the ``zero`` parameter is set to True then a suitable
    number of zeros are added at the end of every partition of size less than
    ``k``.

    ``zero`` parameter is considered only if ``k`` is not None. When the
    partitions are over, the last `next()` call throws the ``StopIteration``
    exception, so this function should always be used inside a try - except
    block.

    Details
    =======

    ``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size
    of the partition which is also positive integer.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import partition
    >>> f = partition(5)
    >>> next(f)
    (1, 1, 1, 1, 1)
    >>> next(f)
    (1, 1, 1, 2)
    >>> g = partition(5, 3)
    >>> next(g)
    (1, 1, 3)
    >>> next(g)
    (1, 2, 2)
    >>> g = partition(5, 3, zeros=True)
    >>> next(g)
    (0, 0, 5)

    r   )ordered_partitionsNrX   r2  )rM  r  r1   r   r8   )r  r   r  r  r   r  r6   r6   r7   	partition  s   .r  c                 C   s   | d dksdS | d dkrd}nd}t || d d | dkr/t|}t || d d | dkst || d d | }| }|d | krN||| }}|d | ksAt|| t|fS )a   
    Represent a prime `p` as a unique sum of two squares; this can
    only be done if the prime is congruent to 1 mod 4.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares
    >>> prime_as_sum_of_two_squares(7)  # can't be done
    >>> prime_as_sum_of_two_squares(5)
    (1, 2)

    Reference
    =========

    .. [1] Representing a number as a sum of four squares, [online],
        Available: http://schorn.ch/lagrange.html

    See Also
    ========
    sum_of_squares()
    r   rX   N   rq  r   r   )powr   r  )r   r   r   r6   r6   r7   prime_as_sum_of_two_squares  s   r  c           	      C   s>  i ddddddddd	d
dddddddddddddddddddddd d!d"d#d$i}d%}| d%krAd&S t d'| }| d'|  } | d( d)krTd*S | | v rs||  \}}}td| | d| | d| | S t| d\}}|rd| | d%d%fS d*}| d( dkrt|r|n|d }t|d+d,D ].}| |d  d }t|rt|\}}td| | d| ||  d| t||    S qd*S | d( dks| d( d-krt|r|n|d }n
t|r|d n|}t|d+d,D ]'}| |d  }t|rt|\}}td| | d| | d| |   S qd*S ).a  
    Returns a 3-tuple `(a, b, c)` such that `a^2 + b^2 + c^2 = n` and
    `a, b, c \geq 0`.

    Returns None if `n = 4^a(8m + 7)` for some `a, m \in Z`. See
    [1]_ for more details.

    Usage
    =====

    ``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares
    >>> sum_of_three_squares(44542)
    (18, 37, 207)

    References
    ==========

    .. [1] Representing a number as a sum of three squares, [online],
        Available: http://schorn.ch/lagrange.html

    See Also
    ========

    sum_of_squares()
    rX   )rX   r   r   r   r  r   )rX   rX   rX   
   )rX   r   r   "   )r   r   r   :   )r      r   U   )   r  r      )r      r      )r   r        )r  	   r  ir  )r  r     i  )r  r     i  )r  r     i  )rX      r   i  )r     !   ir  )r  r  $   i  )r      '   i%  )8   9   r  r   )r   r   r   r   r  r  Nr   r   r  )	r   r$  r0  r   r&  r   r!   r  r   )	r  Zspecialr   r   r   r   r   rz  r   r6   r6   r7   sum_of_three_squaresB  st   &
$4
(r  c                 C   s   | dkrdS t d| }| d|  } | d dkrd}| d } n| d dks*| d dkr1d}| d } nd}t| \}}}td| | d| | d| | d| | S )	a{  
    Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`.

    Here `a, b, c, d \geq 0`.

    Usage
    =====

    ``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares
    >>> sum_of_four_squares(3456)
    (8, 8, 32, 48)
    >>> sum_of_four_squares(1294585930293)
    (0, 1234, 2161, 1137796)

    References
    ==========

    .. [1] Representing a number as a sum of four squares, [online],
        Available: http://schorn.ch/lagrange.html

    See Also
    ========

    sum_of_squares()
    r   )r   r   r   r   r   r  r  r   r  rX   )r   r  r0  )r  r   r   r   r   r   r6   r6   r7   sum_of_four_squares  s   


.r  c                 c   s>   dd | ||fD \} }}| dk r-|d r+t |  |||D ]}tdd |D V  qdS |dk s5|dk r?ttd	||f | dkrL|rJd
| V  dS |dkru|dkrZ| fV  dS t| }|rs|\}}t||\}}	|	ss|| fV  dS |dkrt| ||dD ]}|V  qdS |dkrt| |}
|
sdS |s| dkr|dkr|| kr| | dv r	 dS |
durt| V  dS |dkr|dkrt| }|r|d | dkrdS | |krt	| |d  |d }t
||| g |D ]	}tt|V  q|rt	| |d }td|D ]}t
||| g |D ]}tt|d
||   V  q	qdS dS )ab  
    Returns a generator for finding k-tuples of integers,
    `(n_{1}, n_{2}, . . . n_{k})`, such that
    `n = n_{1}^p + n_{2}^p + . . . n_{k}^p`.

    Usage
    =====

    ``power_representation(n, p, k, zeros)``: Represent non-negative number
    ``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the
    solutions is allowed to contain zeros.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import power_representation

    Represent 1729 as a sum of two cubes:

    >>> f = power_representation(1729, 3, 2)
    >>> next(f)
    (9, 10)
    >>> next(f)
    (1, 12)

    If the flag `zeros` is True, the solution may contain tuples with
    zeros; any such solutions will be generated after the solutions
    without zeros:

    >>> list(power_representation(125, 2, 3, zeros=True))
    [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)]

    For even `p` the `permute_sign` function can be used to get all
    signed values:

    >>> from sympy.utilities.iterables import permute_signs
    >>> list(permute_signs((1, 12)))
    [(1, 12), (-1, 12), (1, -12), (-1, -12)]

    All possible signed permutations can also be obtained:

    >>> from sympy.utilities.iterables import signed_permutations
    >>> list(signed_permutations((1, 12)))
    [(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)]
    c                 S   r   r6   r   r   r6   r6   r7   r     r   z(power_representation.<locals>.<listcomp>r   r   c                 s   s    | ]}| V  qd S r<   r6   r   r6   r6   r7   rV     r  z'power_representation.<locals>.<genexpr>NrX   zA
    Expecting positive integers for `(p, k)`, but got `(%s, %s)`r2  r  r  rq  )r  r  r  rq  r   r   rX   T)r+  r1   r0   r*   r   r   r  _can_do_sum_of_squaresr  r   pow_rep_recursivereversedr   )r  r   r   r  r   ber   r   r   r   Zfeasibler   r   r6   r6   r7   r+    sp   .

(
r+  c                 c   s    |dkr|dkrt |V  d S | dkrB|dkrDt| d ||||E d H  |t| | }|dkrFt| |d ||| g |E d H  d S d S d S d S rE  )r1   r  r  )Zn_ir   Zn_remainingrU  r   Zresidualr6   r6   r7   r  7  s   $r  c                 c   s    t | d||E dH  dS )ay  Return a generator that yields the k-tuples of nonnegative
    values, the squares of which sum to n. If zeros is False (default)
    then the solution will not contain zeros. The nonnegative
    elements of a tuple are sorted.

    * If k == 1 and n is square, (n,) is returned.

    * If k == 2 then n can only be written as a sum of squares if
      every prime in the factorization of n that has the form
      4*k + 3 has an even multiplicity. If n is prime then
      it can only be written as a sum of two squares if it is
      in the form 4*k + 1.

    * if k == 3 then n can be written as a sum of squares if it does
      not have the form 4**m*(8*k + 7).

    * all integers can be written as the sum of 4 squares.

    * if k > 4 then n can be partitioned and each partition can
      be written as a sum of 4 squares; if n is not evenly divisible
      by 4 then n can be written as a sum of squares only if the
      an additional partition can be written as sum of squares.
      For example, if k = 6 then n is partitioned into two parts,
      the first being written as a sum of 4 squares and the second
      being written as a sum of 2 squares -- which can only be
      done if the condition above for k = 2 can be met, so this will
      automatically reject certain partitions of n.

    Examples
    ========

    >>> from sympy.solvers.diophantine.diophantine import sum_of_squares
    >>> list(sum_of_squares(25, 2))
    [(3, 4)]
    >>> list(sum_of_squares(25, 2, True))
    [(3, 4), (0, 5)]
    >>> list(sum_of_squares(25, 4))
    [(1, 2, 2, 4)]

    See Also
    ========

    sympy.utilities.iterables.signed_permutations
    r   N)r+  )r  r   r  r6   r6   r7   r  C  s   -r  c                 C   s   |dk rdS | dk rdS | dkrdS |dkrt | S |dkrN| dv r$dS t| r2| d dkr0dS dS t| }| D ]\}}|d dkrK|d rK dS q:dS |dkra| dtd|   d	 d
kradS dS )a  Return True if n can be written as the sum of k squares,
    False if it can't, or 1 if ``k == 2`` and ``n`` is prime (in which
    case it *can* be written as a sum of two squares). A False
    is returned only if it can't be written as ``k``-squares, even
    if 0s are allowed.
    rX   Fr   Tr   )rX   r   r   r   r  r  )r    r!   r   rp  r   )r  r   r~  r   r  r6   r6   r7   r  s  s2   r  r<   )T)F)rX   )NF)Zsympy.core.addr   Zsympy.core.assumptionsr   Zsympy.core.containersr   Zsympy.core.compatibilityr   r   r   Zsympy.core.exprtoolsr   Zsympy.core.functionr	   Zsympy.core.mulr
   Zsympy.core.numbersr   r   r   r   Zsympy.core.powerr   r   Zsympy.core.relationalr   Zsympy.core.singletonr   Zsympy.core.symbolr   r   Zsympy.core.sympifyr   Z$sympy.functions.elementary.complexesr   Z#sympy.functions.elementary.integersr   Z(sympy.functions.elementary.miscellaneousr   Zsympy.matrices.denser   r   Zsympy.ntheory.factor_r   r   r   r   Zsympy.ntheory.generater   Zsympy.ntheory.primetestr    r!   Zsympy.ntheory.residue_ntheoryr"   Zsympy.polys.polyerrorsr#   Zsympy.polys.polytoolsr$   r%   r  r&   Zsympy.solvers.solvesetr'   Zsympy.utilitiesr(   r)   Zsympy.utilities.miscr*   __all__rd   r-   rM   rx   r   r   r   r   r   r  r  r
  r  r'  r(  r]  rj  rS   r0  r   r   r9  r&  r;  r+   rS  r_  r   r,   joinr/  Zfunc_docrb  r   rg  r   rc  r   r   rw  rv  rx  r  r  ry  r  r   r  r   r   rd  r   r  r  r  r  re  r   r   ru  r   r  r   r  r  r  r   rf  rh  ri  r  r  r  r  r+  Zsum_of_powersr  r  r  r6   r6   r6   r7   <module>   s    cN  I `W GNA
  

#
U&*
:9&5 H_B?['-S3,
3TA
(,
9E5)
@
#
(
&9+P
3o
0