Source code for sympy.ntheory.residue_ntheory

[docs]defn_order(a,n):"""Returns the order of ``a`` modulo ``n``. The order of ``a`` modulo ``n`` is the smallest integer ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``. Examples ======== >>> from sympy.ntheory import n_order >>> n_order(3, 7) 6 >>> n_order(4, 7) 3 """a,n=as_int(a),as_int(n)ifigcd(a,n)!=1:raiseValueError("The two numbers should be relatively prime")group_order=totient(n)factors=factorint(group_order)order=1ifa>n:a=a%nforp,einfactors.items():exponent=group_orderforfinrange(0,e+1):if(a**(exponent))%n!=1:order*=p**(e-f+1)breakexponent=exponent//preturnorder

[docs]defis_quad_residue(a,p):""" Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination: >>> from sympy.ntheory import is_quad_residue >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] See Also ======== legendre_symbol, jacobi_symbol """a,p=as_int(a),as_int(p)ifp<1:raiseValueError('p must be > 0')ifa>=pora<0:a=a%pifa<2orp<3:returnTrueifnotisprime(p):ifp%2andjacobi_symbol(a,p)==-1:returnFalseforiinrange(2,p//2+1):ifi**2%p==a:returnTruereturnFalsedefsquare_and_multiply(a,n,p):ifn==1:returnaelifn%2==1:return((square_and_multiply(a,n//2,p)**2)*a)%pelse:return(square_and_multiply(a,n//2,p)**2)%preturn(square_and_multiply(a,(p-1)//2,p)%p)==1

[docs]deflegendre_symbol(a,p):""" Returns ======= 1. 0 if a is multiple of p 2. 1 if a is a quadratic residue of p 3. -1 otherwise p should be an odd prime by definition Examples ======== >>> from sympy.ntheory import legendre_symbol >>> [legendre_symbol(i, 7) for i in range(7)] [0, 1, 1, -1, 1, -1, -1] >>> list(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] See Also ======== is_quad_residue, jacobi_symbol """a,p=as_int(a),as_int(p)ifnotisprime(p)orp==2:raiseValueError("p should be an odd prime")_,a=divmod(a,p)ifnota:return0ifis_quad_residue(a,p):return1else:return-1