
    wg9Z                         d Z ddlmZ ddlmZ ddlmZmZm	Z	m
ZmZmZmZmZmZmZ ddlmZ ddlmZmZ dZd Zd	 Zd
 ZddZ
d Zd Zd Zd Zd Zd Z d Z!d Z"d Z#d Z$d Z%y)z
Primality testing

    )count)sympify)
gmpygcdjacobi	is_square	bit_scan1is_fermat_prpis_euler_prpis_selfridge_prpis_strong_selfridge_prpis_strong_bpsw_prp)_lucas_sequence)as_int
filldedent)3                        =   Y   k      i	  i_  i  i  i  i  i  iG  i%  i&  i+  iM  iT  iZ  iѭ  iP i i iL ig i) i;1 iU ii- iA. idj i%} i_@ini1ii,i;6iYiؑiAsi1Pli{i8c                 z    t        |       t        |      }} |dk(  r| dk(  xs t        | dz        S t        | |      S )a  Returns True if ``n`` is prime or is an odd composite integer that
    is coprime to ``a`` and satisfy the modular arithmetic congruence relation:

    .. math ::
        a^{n-1} \equiv 1 \pmod{n}

    (where mod refers to the modulo operation).

    Parameters
    ==========

    n : Integer
        ``n`` is a positive integer.
    a : Integer
        ``a`` is a positive integer.
        ``a`` and ``n`` should be relatively prime.

    Returns
    =======

    bool : If ``n`` is prime, it always returns ``True``.
           The composite number that returns ``True`` is called an Fermat pseudoprime.

    Examples
    ========

    >>> from sympy.ntheory.primetest import is_fermat_pseudoprime
    >>> from sympy.ntheory.factor_ import isprime
    >>> for n in range(1, 1000):
    ...     if is_fermat_pseudoprime(n, 2) and not isprime(n):
    ...         print(n)
    341
    561
    645

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Fermat_pseudoprime
       r   )r   boolr
   nas     \/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/ntheory/primetest.pyis_fermat_pseudoprimer%      sA    R !9fQiqAAvAv$a!e$A    c                 0   t        |       t        |      }} |dk  rt        d      | dk  rt        d      | dk(  ry|dk(  r| dk(  xs t        | dz        S | dz  dk(  r| dk(  S t        | |      dk7  rt        d      t	        || dz
  dz  |       d| dz
  fv S )a  Returns True if ``n`` is prime or is an odd composite integer that
    is coprime to ``a`` and satisfy the modular arithmetic congruence relation:

    .. math ::
        a^{(n-1)/2} \equiv \pm 1 \pmod{n}

    (where mod refers to the modulo operation).

    Parameters
    ==========

    n : Integer
        ``n`` is a positive integer.
    a : Integer
        ``a`` is a positive integer.
        ``a`` and ``n`` should be relatively prime.

    Returns
    =======

    bool : If ``n`` is prime, it always returns ``True``.
           The composite number that returns ``True`` is called an Euler pseudoprime.

    Examples
    ========

    >>> from sympy.ntheory.primetest import is_euler_pseudoprime
    >>> from sympy.ntheory.factor_ import isprime
    >>> for n in range(1, 1000):
    ...     if is_euler_pseudoprime(n, 2) and not isprime(n):
    ...         print(n)
    341
    561

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
    r   z%a should be an integer greater than 0z%n should be an integer greater than 0Fr   r   z*The two numbers should be relatively prime)r   
ValueErrorr    r   powr!   s     r$   is_euler_pseudoprimer*   H   s    P !9fQiqA1u@AA1u@AAAvAvAv$a!e$1uzAv
1ayA~EFFq1q5Q,"q!a%j00r&   c                 z    t        |       t        |      }} |dk(  r| dk(  xs t        | dz        S t        | |      S )a  Returns True if ``n`` is prime or is an odd composite integer that
    is coprime to ``a`` and satisfy the modular arithmetic congruence relation:

    .. math ::
        a^{(n-1)/2} \equiv \left(\frac{a}{n}\right) \pmod{n}

    (where mod refers to the modulo operation).

    Parameters
    ==========

    n : Integer
        ``n`` is a positive integer.
    a : Integer
        ``a`` is a positive integer.
        ``a`` and ``n`` should be relatively prime.

    Returns
    =======

    bool : If ``n`` is prime, it always returns ``True``.
           The composite number that returns ``True`` is called an Euler-Jacobi pseudoprime.

    Examples
    ========

    >>> from sympy.ntheory.primetest import is_euler_jacobi_pseudoprime
    >>> from sympy.ntheory.factor_ import isprime
    >>> for n in range(1, 1000):
    ...     if is_euler_jacobi_pseudoprime(n, 2) and not isprime(n):
    ...         print(n)
    561

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Jacobi_pseudoprime
    r   r   )r   r    r   r!   s     r$   is_euler_jacobi_pseudoprimer,      sA    N !9fQiqAAvAv$a!e$1r&   c                 H    |rt        |       } | dk  ry| dv ryt        |       S )a  Return True if n == a * a for some integer a, else False.
    If n is suspected of *not* being a square then this is a
    quick method of confirming that it is not.

    Examples
    ========

    >>> from sympy.ntheory.primetest import is_square
    >>> is_square(25)
    True
    >>> is_square(2)
    False

    References
    ==========

    .. [1]  https://mersenneforum.org/showpost.php?p=110896

    See Also
    ========
    sympy.core.intfunc.isqrt
    r   F)r   r   T)r   gmpy_is_square)r"   preps     r$   r   r      s/    . 1Iq5;!r&   c                     t        |||       }|dk(  s|| dz
  k(  ryt        |dz
        D ]   }t        |d|       }|| dz
  k(  r y|dk(  s  y y)zMiller-Rabin strong pseudoprime test for one base.
    Return False if n is definitely composite, True if n is
    probably prime, with a probability greater than 3/4.

    r   Tr   F)r)   range)r"   basestb_s         r$   _testr7      sf     	D!QAAva!e1q5\ 1aLA:6 r&   c                     ddl m} t        |       } | dk  ryt        | dz
        }| |z	  }|D ]*  }|| k\  r|| z  }|dk\  s ||      }t	        | |||      r* y y)aG  Perform a Miller-Rabin strong pseudoprime test on n using a
    given list of bases/witnesses.

    References
    ==========

    .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
           A Computational Perspective", Springer, 2nd edition, 135-138

    A list of thresholds and the bases they require are here:
    https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants

    Examples
    ========

    >>> from sympy.ntheory.primetest import mr
    >>> mr(1373651, [2, 3])
    False
    >>> mr(479001599, [31, 73])
    True

    r   )ZZr   Fr   T)sympy.polys.domainsr9   r   r	   r7   )r"   basesr9   r3   r4   r2   s         r$   mrr<      sv    . 'q	A1u!a%A	QA 19AID19d8DD!Q' r&   c                 ~    t        d      D ]/  }|dz  dz
  }t        ||       }|dk(  r||dfc S |dk(  s)|| z  s/ y y)	a  Calculates the "extra strong" parameters (D, P, Q) for n.

    Parameters
    ==========

    n : int
        positive odd integer

    Returns
    =======

    D, P, Q: "extra strong" parameters.
             ``(0, 0, 0)`` if we find a nontrivial divisor of ``n``.

    Examples
    ========

    >>> from sympy.ntheory.primetest import _lucas_extrastrong_params
    >>> _lucas_extrastrong_params(101)
    (12, 4, 1)
    >>> _lucas_extrastrong_params(15)
    (0, 0, 0)

    References
    ==========
    .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
           https://oeis.org/A217719
    .. [2] https://en.wikipedia.org/wiki/Lucas_pseudoprime

    r   r      r   r   )r   r   r   N)r   r   )r"   PDjs       r$   _lucas_extrastrong_paramsrC     sR    > 1X qD1H1aL7q!9!VAr&   c                 :    t        |       } | dk  ryt        |       S )a  Standard Lucas compositeness test with Selfridge parameters.  Returns
    False if n is definitely composite, and True if n is a Lucas probable
    prime.

    This is typically used in combination with the Miller-Rabin test.

    References
    ==========
    .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
           http://mpqs.free.fr/LucasPseudoprimes.pdf
    .. [2] OEIS A217120: Lucas Pseudoprimes
           https://oeis.org/A217120
    .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime

    Examples
    ========

    >>> from sympy.ntheory.primetest import isprime, is_lucas_prp
    >>> for i in range(10000):
    ...     if is_lucas_prp(i) and not isprime(i):
    ...         print(i)
    323
    377
    1159
    1829
    3827
    5459
    5777
    9071
    9179
    r   F)r   r   r"   s    r$   is_lucas_prprF   3  s#    D 	q	A1uAr&   c                 :    t        |       } | dk  ryt        |       S )a-  Strong Lucas compositeness test with Selfridge parameters.  Returns
    False if n is definitely composite, and True if n is a strong Lucas
    probable prime.

    This is often used in combination with the Miller-Rabin test, and
    in particular, when combined with M-R base 2 creates the strong BPSW test.

    References
    ==========
    .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
           http://mpqs.free.fr/LucasPseudoprimes.pdf
    .. [2] OEIS A217255: Strong Lucas Pseudoprimes
           https://oeis.org/A217255
    .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
    .. [4] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test

    Examples
    ========

    >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
    >>> for i in range(20000):
    ...     if is_strong_lucas_prp(i) and not isprime(i):
    ...        print(i)
    5459
    5777
    10877
    16109
    18971
    r   F)r   r   rE   s    r$   is_strong_lucas_prprH   [  s#    @ 	q	A1u"1%%r&   c                 @   t        |       } | dk(  ry| dk  s| dz  dk(  ryt        |       ryt        |       \  }}}|dk(  ryt        | dz         }| dz   |z	  }t	        | |||      \  }}}|dk(  r|dk(  s|| dz
  k(  ryt        d|      D ]  }|dk(  r y||z  dz
  | z  } y)aC  Extra Strong Lucas compositeness test.  Returns False if n is
    definitely composite, and True if n is an "extra strong" Lucas probable
    prime.

    The parameters are selected using P = 3, Q = 1, then incrementing P until
    (D|n) == -1.  The test itself is as defined in [1]_, from the
    Mo and Jones preprint.  The parameter selection and test are the same as
    used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
    page on Wikipedia.

    It is 20-50% faster than the strong test.

    Because of the different parameters selected, there is no relationship
    between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
    In particular, one is not a subset of the other.

    References
    ==========
    .. [1] Jon Grantham, Frobenius Pseudoprimes,
           Math. Comp. Vol 70, Number 234 (2001), pp. 873-891,
           https://doi.org/10.1090%2FS0025-5718-00-01197-2
    .. [2] OEIS A217719: Extra Strong Lucas Pseudoprimes
           https://oeis.org/A217719
    .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime

    Examples
    ========

    >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
    >>> for i in range(20000):
    ...     if is_extra_strong_lucas_prp(i) and not isprime(i):
    ...        print(i)
    989
    3239
    5777
    10877
    r   Tr   Fr   )r   r.   rC   r	   r   r1   )	r"   rA   r@   Qr3   kUVr6   s	            r$   is_extra_strong_lucas_prprN     s    Z 	q	AAv1uQ1a'*GAq!Av 	!a%A	
Q1AaAq)GAq!Av16Q!a%Z1a[ 6qS1WM r&   c                    t        |       } | dk  rt        d      t        | dz
        }| |z	  }||j                         k  rt        d      | dz  dk(  r| dk(  S |dz  rt	        d| dz	  |       | dz
  k(  S t        |       ryt        d|       D ]2  }t        ||       }|dk(  rt	        || dz	  |       | dz
  k(  c S |dk(  s2 y y)	a<   Test if the Proth number `n = k2^m + 1` is prime. where k is a positive odd number and `2^m > k`.

    Parameters
    ==========

    n : Integer
        ``n`` is Proth number

    Returns
    =======

    bool : If ``True``, then ``n`` is the Proth prime

    Raises
    ======

    ValueError
        If ``n`` is not Proth number.

    Examples
    ========

    >>> from sympy.ntheory.primetest import proth_test
    >>> proth_test(41)
    True
    >>> proth_test(57)
    False

    References
    ==========

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

    r   zn is not Proth numberr   r   Fr   r?   N)r   r(   r	   
bit_lengthr)   r.   r1   r   )r"   mrK   r#   rB   s        r$   
proth_testrR     s    F 	q	A1u011!a%A	QA1<<>0111uzAv1u1a1fa AE))a 1a[ 1aL7q!q&!$A--6r&   c                 f    d}d| z  dz
  }t        | dz
        D ]  }t        |d|      dz
  } |dk(  S )a   Test if the Mersenne number `M_p = 2^p-1` is prime.

    Parameters
    ==========

    p : int
        ``p`` is an odd prime number

    Returns
    =======

    bool : If ``True``, then `M_p` is the Mersenne prime

    Examples
    ========

    >>> from sympy.ntheory.primetest import _lucas_lehmer_primality_test
    >>> _lucas_lehmer_primality_test(5) # 2**5 - 1 = 31 is prime
    True
    >>> _lucas_lehmer_primality_test(11) # 2**11 - 1 = 2047 is not prime
    False

    See Also
    ========

    is_mersenne_prime

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test

    r>   r   r   r   )r1   r)   )pvrQ   r6   s       r$   _lucas_lehmer_primality_testrV     sI    D 	
A	1qA1q5\ 1aL16Mr&   c                     t        |       } | dk  ry| | dz   z  ry| j                         }|t        v ry|dk  st        |      syt	        |      }|rt        t        d|z              |S )a  Returns True if  ``n`` is a Mersenne prime, else False.

    A Mersenne prime is a prime number having the form `2^i - 1`.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import is_mersenne_prime
    >>> is_mersenne_prime(6)
    False
    >>> is_mersenne_prime(127)
    True

    References
    ==========

    .. [1] https://mathworld.wolfram.com/MersennePrime.html

    r   FTi@z`
            This Mersenne Prime, 2^%s - 1, should
            be added to SymPy's known values.)r   rP   MERSENNE_PRIME_EXPONENTSisprimerV   r(   r   )r"   rT   results      r$   is_mersenne_primer[   -  s    ( 	q	A1uAE{	A$$:~WQZ )!,F %134%5 6 7 	7 Mr&   c                 j   t        |       } | dv ry| dk  s| dz  dk(  s| dz  dk(  s| dz  dk(  ry| dk  ry| d	z  dk(  sX| d
z  dk(  sP| dz  dk(  sH| dz  dk(  s@| dz  dk(  s8| dz  dk(  s0| dz  dk(  s(| dz  dk(  s | dz  dk(  s| dz  dk(  s| dz  dk(  s| dz  dk(  ry| dk  ry| dk  rt        d| dz	  |       d| dz
  fv xr | dvS ddlm} | |j                  d   k  r|j                  |       \  }}||k(  S t        t        |       S | dk  rt        | dg      S | dk  rt        | ddg      S | d k  rt        | g d!      S | d"k  rt        | g d#      S | d$k  rt        | g d%      S | d&k  rt        | g d'      S | d(k  rt        | g d)      S | d*k  rt        | g d+      S | d,k  rt        | g d-      S t        |       S ).a  
    Test if n is a prime number (True) or not (False). For n < 2^64 the
    answer is definitive; larger n values have a small probability of actually
    being pseudoprimes.

    Negative numbers (e.g. -2) are not considered prime.

    The first step is looking for trivial factors, which if found enables
    a quick return.  Next, if the sieve is large enough, use bisection search
    on the sieve.  For small numbers, a set of deterministic Miller-Rabin
    tests are performed with bases that are known to have no counterexamples
    in their range.  Finally if the number is larger than 2^64, a strong
    BPSW test is performed.  While this is a probable prime test and we
    believe counterexamples exist, there are no known counterexamples.

    Examples
    ========

    >>> from sympy.ntheory import isprime
    >>> isprime(13)
    True
    >>> isprime(15)
    False

    Notes
    =====

    This routine is intended only for integer input, not numerical
    expressions which may represent numbers. Floats are also
    rejected as input because they represent numbers of limited
    precision. While it is tempting to permit 7.0 to represent an
    integer there are errors that may "pass silently" if this is
    allowed:

    >>> from sympy import Float, S
    >>> int(1e3) == 1e3 == 10**3
    True
    >>> int(1e23) == 1e23
    True
    >>> int(1e23) == 10**23
    False

    >>> near_int = 1 + S(1)/10**19
    >>> near_int == int(near_int)
    False
    >>> n = Float(near_int, 10)  # truncated by precision
    >>> n % 1 == 0
    True
    >>> n = Float(near_int, 20)
    >>> n % 1 == 0
    False

    See Also
    ========

    sympy.ntheory.generate.primerange : Generates all primes in a given range
    sympy.functions.combinatorial.numbers.primepi : Return the number of primes less than or equal to n
    sympy.ntheory.generate.prime : Return the nth prime

    References
    ==========
    .. [1] https://en.wikipedia.org/wiki/Strong_pseudoprime
    .. [2] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
           http://mpqs.free.fr/LucasPseudoprimes.pdf
    .. [3] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
    )r   r   r   Tr   r   r   r   F1   r      r   r   r         r   %   )   +   /   i
  i5  r   )i   i{  i/  i  i=  )siever?   i6 l   j_| i94l   85Pl   p8K0T l   ?_F)l   |a?bU l   $|3r_ l   (P7 l   k^AH )r   l   @0 l   e7:`V! l   "SV=Q-O	 l   v- )r   l   morl   \^E~8l   )VmAl   vKHu8 l   ~_!@)r   l   \]A l   bY+5l   0Prl   MK	Tl   0KOM l            )r   iE  i$  in  i i= ikl   7y_@I7 )r   r   r   r   r^   r   r   r   r_   r`   r   ra   l   %!HnfW )r   r   r   r   r^   r   r   r   r_   r`   r   ra   rb   )	r   r)   sympy.ntheory.generatere   _listsearch_gmpyr   r<   )r"   r3   lus       r$   rY   rY   W  s*   J 	q	A 	I~1uQ1Q1Q12v	Q1}RA!b&Q1r6a-	B1}RA!b&Q1r6a-	B1}RA!b&Q1r6a-4x5y1a1fa QAJ.^1<^3^^ 2AGGBKxx{1Av
 !!$$ 	6z!)*++9}!(*=>??<!VWW>!TUU!dee!wxx!GHH##!ABB$$!EFFJ a  r&   c                 .   t        |       } | j                         \  }}t        |d      }t        |d      }|dk(  r t        |      }t	        |      xr |dz  dk(  S |dk(  r t        |      }t	        |      xr |dz  dk(  S t	        |dz  |dz  z         S )z}Test if num is a Gaussian prime number.

    References
    ==========

    .. [1] https://oeis.org/wiki/Gaussian_primes
    F)strictr   r>   r   r   )r   as_real_imagr   absrY   )numr#   r5   s      r$   is_gaussian_primerq     s     #,CDAqqAqAAvFqz(a!eqj(	
aFqz(a!eqj(1a4!Q$;r&   N)T)&__doc__	itertoolsr   sympy.core.sympifyr   sympy.external.gmpyr   ri   r   r   r   r.   r	   r
   r   r   r   r   sympy.external.ntheoryr   sympy.utilities.miscr   r   rX   r%   r*   r,   r7   r<   rC   rF   rH   rN   rR   rV   r[   rY   rq    r&   r$   <module>ry      s   
  &5 5 5
 3 3e ,^51p*Z@('T%P%P#&LEP8v&R'Te!^ r&   