o
    !ôjZ:  ã                   @   s¼   d dl mZmZ d dlmZ d dlmZmZmZm	Z
 d dlmZ d dlmZ d dlmZ G dd„ dƒZG d	d
„ d
ƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zddd„Zddd„ZdS )é    )ÚexpÚlog)Ú_randint)Ú	bit_scan1ÚgcdÚinvertÚsqrt)Ú_perfect_power)Úisprime)Ú_sqrt_mod_prime_powerc                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )ÚSievePolynomialc                 C   s6   || _ || _|d | _d| | | _|d | | _dS )a4  This class denotes the sieve polynomial.
        Provide methods to compute `(a*x + b)**2 - N` and
        `a*x + b` when given `x`.

        Parameters
        ==========

        a : parameter of the sieve polynomial
        b : parameter of the sieve polynomial
        N : number to be factored

        é   N)ÚaÚbÚa2ÚabÚb2)Úselfr   r   ÚN© r   úc/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/sympy/ntheory/qs.pyÚ__init__
   s
   
zSievePolynomial.__init__c                 C   s   | j | | j S ©N)r   r   ©r   Úxr   r   r   Úeval_u   s   zSievePolynomial.eval_uc                 C   s   | j | | j | | j S r   )r   r   r   r   r   r   r   Úeval_v    s   zSievePolynomial.eval_vN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   r   r   r   	   s    r   c                   @   s   e Zd ZdZdd„ ZdS )ÚFactorBaseElemz7This class stores an element of the `factor_base`.
    c                 C   s(   || _ || _|| _d| _d| _d| _dS )zÿ
        Initialization of factor_base_elem.

        Parameters
        ==========

        prime : prime number of the factor_base
        tmem_p : Integer square root of x**2 = n mod prime
        log_p : Compute Natural Logarithm of the prime
        N)ÚprimeÚtmem_pÚlog_pÚsoln1Úsoln2Úb_ainv)r   r!   r"   r#   r   r   r   r   '   s   
zFactorBaseElem.__init__N)r   r   r   Ú__doc__r   r   r   r   r   r    $   s    r    c           	      C   s¶   ddl m} g }d\}}| d| ¡D ]C}t||d d |ƒdkrU|dkr.|du r.t|ƒd }|dkr<|du r<t|ƒd }t||dƒd }tt|ƒd	 ƒ}| t	|||ƒ¡ q|||fS )
aç  Generate `factor_base` for Quadratic Sieve. The `factor_base`
    consists of all the points whose ``legendre_symbol(n, p) == 1``
    and ``p < num_primes``. Along with the prime `factor_base` also stores
    natural logarithm of prime and the residue n modulo p.
    It also returns the of primes numbers in the `factor_base` which are
    close to 1000 and 5000.

    Parameters
    ==========

    prime_bound : upper prime bound of the factor_base
    n : integer to be factored
    r   )Úsieve)NNé   r   iè  Niˆ  é   )
Úsympy.ntheory.generater(   Ú
primerangeÚpowÚlenr   Úroundr   Úappendr    )	Úprime_boundÚnr(   Úfactor_baseÚidx_1000Úidx_5000r!   Úresiduer#   r   r   r   Ú_generate_factor_base<   s   €
r7   c                 #   sž  � t d|  ƒd t |ƒ }|pd}|pt|ƒd }	 d\}	}
}tdƒD ]U}d}g }t |ƒ|k rZd}|dks9||v rF|||ƒ}|dks9||v s9|| j}||9 }| |¡ t |ƒ|k s/tt |ƒ| ƒ}|du srt|d ƒt|d ƒk rx|}
|}	|}q#|	}|
}g }|D ](}|| j}|| jt|| |ƒ | }d| |kr || }| || | ¡ q�t	|ƒ}t
||| ƒ}|D ]5‰|ˆj dkrÃdˆ_q¶t|ˆjƒ‰ ‡ ‡fdd	„|D ƒˆ_ˆ ˆj|  ˆj ˆ_ˆ ˆj |  ˆj ˆ_q¶|V  tddt|ƒd  ƒD ]S}t|ƒ}d||d ? d  d }|jd| ||   }|j}t
||| ƒ}|D ]'‰ˆjdu �r,�q"ˆj|ˆj|   ˆj ˆ_ˆj|ˆj|   ˆj ˆ_�q"|V  qúq)
a6   Generate sieve polynomials indefinitely.
    Information such as `soln1` in the `factor_base` associated with
    the polynomial is modified in place.

    Parameters
    ==========

    N : Number to be factored
    M : sieve interval
    factor_base : factor_base primes
    idx_1000 : index of prime number in the factor_base near 1000
    idx_5000 : index of prime number in the factor_base near to 5000
    randint : A callable that takes two integers (a, b) and returns a random integer
              n such that a <= n <= b, similar to `random.randint`.
    r   r   r)   T)NNNé2   Nc                    s   g | ]}d | ˆ  ˆj  ‘qS ©r   )r!   )Ú.0Zb_elem©Za_invÚfbr   r   Ú
<listcomp>�   s    z(_generate_polynomial.<locals>.<listcomp>)r   r.   Úranger!   r0   r   Úabsr"   r   Úsumr   r$   r&   r%   r   r   r   )r   ÚMr3   r4   r5   ÚrandintZ
approx_valÚstartÚendZbest_aZbest_qÚ
best_ratioÚ_r   ÚqZrand_pÚpÚratioÚBÚvalZq_lÚgammar   ÚgÚiÚvÚneg_powr   r;   r   Ú_generate_polynomialY   sr   €

ÿ

ú €
 ËrQ   c                 C   s¤   dgd|  d  }|D ]D}|j du rqt| |j  |j d|  |jƒD ]}||  |j7  < q"|jdkr4qt| |j |j d|  |jƒD ]}||  |j7  < qCq|S )a¨  Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
    that does not divide the coefficient `a` we add log_p over the sieve_array
    such that ``-M <= soln1 + i*p <=  M`` and ``-M <= soln2 + i*p <=  M`` where `i`
    is an integer. When p = 2 then log_p is only added using
    ``-M <= soln1 + i*p <=  M``.

    Parameters
    ==========

    M : sieve interval
    factor_base : factor_base primes
    r   r   r)   N)r$   r>   r!   r#   r%   )rA   r3   Úsieve_arrayÚfactorÚidxr   r   r   Ú_gen_sieve_array¤   s   
"
"ÿrU   c                 C   s’   | dk r| d9 } d}nd}t |dƒD ]2\}}| |j rqd}| |j } | |j dkr:|d7 }| |j } | |j dks*|d rD|d|> 7 }q|| fS )zê Check if `num` is smooth with respect to the given `factor_base`
    and compute its factorization vector.

    Parameters
    ==========

    num : integer whose smootheness is to be checked
    factor_base : factor_base primes
    r   éÿÿÿÿr)   r   )Ú	enumerater!   )Únumr3   ÚvecrN   r<   Úer   r   r   Ú_check_smoothness¿   s"   



þ€r[   c                 C   s,  t |ƒt | ƒd  | d }g }tƒ }	d|d j }
t|| ƒD ]q\}}||k r)q | |¡}t||ƒ\}}|dkrE| | |¡||f¡ q ||
k r‘t|ƒr‘| | dkrY|	 	|¡ q | |¡}||v rŠ| 
|¡\}}}|| t|| ƒ |  }|| |d  }||N }| |||f¡ q |||f||< q ||	fS )a)  Trial division stage. Here we trial divide the values generetated
    by sieve_poly in the sieve interval and if it is a smooth number then
    it is stored in `smooth_relations`. Moreover, if we find two partial relations
    with same large prime then they are combined to form a smooth relation.
    First we iterate over sieve array and look for values which are greater
    than accumulated_val, as these values have a high chance of being smooth
    number. Then using these values we find smooth relations.
    In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
    with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
    to form a smooth relation.

    Parameters
    ==========

    N : Number to be factored
    M : sieve interval
    factor_base : factor_base primes
    sieve_array : stores log_p values
    sieve_poly : polynomial from which we find smooth relations
    partial_relations : stores partial relations with one large prime
    ERROR_TERM : error term for accumulated_val
    r   r*   é€   rV   r)   r   )r   Úsetr!   rW   r   r[   r0   r   r
   ÚaddÚpopr   )r   rA   r3   rR   Z
sieve_polyÚpartial_relationsÚ
ERROR_TERMZaccumulated_valÚsmooth_relationsZproper_factorZpartial_relation_upper_boundr   rK   rO   rY   rX   ÚuZu_prevZv_prevZvec_prevr   r   r   Ú_trial_division_stageÛ   s2   


€rd   c                 c   sJ  � dd„ |D ƒ}t |ƒ}dg| }t|ƒD ]=}d|> }t|ƒD ]2}|| |@  }	rQ|	|| A }
|||< d||< t|d |ƒD ]}|| |@ rN||  |
N  < q> nqqt|||ƒD ]I\}}}|raqY|d |d }}t|||ƒD ]\}}}|r‡||@ r‡||d 9 }||d 9 }qpt|ƒ}dt|| | ƒ }  k r�| k r¢n qY|V  qYdS )a˜   Finds proper factor of N using fast gaussian reduction for modulo 2 matrix.

    Parameters
    ==========

    N : Number to be factored
    smooth_relations : Smooth relations vectors matrix
    col : Number of columns in the matrix

    Reference
    ==========

    .. [1] A fast algorithm for gaussian elimination over GF(2) and
    its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige
    c                 S   s   g | ]}|d  ‘qS r9   r   )r:   Z
s_relationr   r   r   r=     s    z _find_factor.<locals>.<listcomp>Fr)   Tr   N)r.   r>   ÚzipÚisqrtr   )r   rb   ÚcolÚmatrixÚrowÚmarkÚposÚmrN   rH   Zadd_colÚjÚmatÚrelrc   rO   Úm1Úmat1Zrel1rM   r   r   r   Ú_find_factor  s@   €
€ù€	€&€õrr   é   éÒ  c                 C   s   t t| ||||ƒƒS )aœ  Performs factorization using Self-Initializing Quadratic Sieve.
    In SIQS, let N be a number to be factored, and this N should not be a
    perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
    ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
    In order to find these integers X and Y we try to find relations of form
    t**2 = u modN where u is a product of small primes. If we have enough of
    these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
    the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.

    Here, several optimizations are done like using multiple polynomials for
    sieving, fast changing between polynomials and using partial relations.
    The use of partial relations can speeds up the factoring by 2 times.

    Parameters
    ==========

    N : Number to be Factored
    prime_bound : upper bound for primes in the factor base
    M : Sieve Interval
    ERROR_TERM : Error term for checking smoothness
    seed : seed of random number generator

    Returns
    =======

    set(int) : A set of factors of N without considering multiplicity.
               Returns ``{N}`` if factorization fails.

    Examples
    ========

    >>> from sympy.ntheory import qs
    >>> qs(25645121643901801, 2000, 10000)
    {5394769, 4753701529}
    >>> qs(9804659461513846513, 2000, 10000)
    {4641991, 2112166839943}

    See Also
    ========

    qs_factor

    References
    ==========

    .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
    .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
    )r]   Ú	qs_factor)r   r1   rA   ra   Úseedr   r   r   Úqs:  s   1rw   c              	   C   sò  | dk rt dƒ‚i }g }i }| d dkr2d}| d } | d dkr.| d } |d7 }| d dks ||d< t| ƒr<d|| < |S t| dƒ }	rM|	\}
}|||
< |S | }t|ƒ}t|| ƒ\}}}t|ƒd d }t| |||||ƒD ]G}t||ƒ}t| ||||||ƒ\}}||7 }|D ]%}|| rŒq…d}|| }|| dkr¦|| }|d7 }|| dks˜|||< q…|t|ƒkr³ nqlt	| |t|ƒd ƒD ]0}|| dkrîd}|| }|| dkrà|| }|d7 }|| dksÒ|||< |dksìt|ƒrî nq¾|dkr÷d||< |S )aª   Performs factorization using Self-Initializing Quadratic Sieve.

    Parameters
    ==========

    N : Number to be Factored
    prime_bound : upper bound for primes in the factor base
    M : Sieve Interval
    ERROR_TERM : Error term for checking smoothness
    seed : seed of random number generator

    Returns
    =======

    dict[int, int] : Factors of N.
                     Returns ``{N: 1}`` if factorization fails.
                     Note that the key is not always a prime number.

    Examples
    ========

    >>> from sympy.ntheory import qs_factor
    >>> qs_factor(1009 * 100003, 2000, 10000)
    {1009: 1, 100003: 1}

    See Also
    ========

    qs

    r   zN should be greater than 1r   r)   é   éi   éd   )
Ú
ValueErrorr
   r	   r   r7   r.   rQ   rU   rd   rr   )r   r1   rA   ra   rv   Úfactorsrb   r`   rZ   Úresultr2   ZN_copyrB   r4   r5   r3   Ú	thresholdrM   rR   Zs_relZp_frH   rS   r   r   r   ru   n  sp    þ
þ
ÿþ€ru   N)rs   rt   )Úmathr   r   Úsympy.core.randomr   Úsympy.external.gmpyr   r   r   r   rf   Úsympy.ntheory.factor_r	   Úsympy.ntheory.primetestr
   Zsympy.ntheory.residue_ntheoryr   r   r    r7   rQ   rU   r[   rd   rr   rw   ru   r   r   r   r   Ú<module>   s     K2
-4