Example #1
0
def fpsp(n):
    #Si n es par acaba el programa
    if n%2==0:
        print str(n) + " es par."
        return (2,False)
    #Si n es impar
    else:
        #Calcula s y t tales que n-1=2^st con t impar
        s = mpot(2,n-1)
        t = (n-1)/pow(2,s)

        #Tomamos una base b aleatoria entre 1 y n-1
        base = random.randint(1,n-1)

        #Comprobamos si gcd(base,n) es 1
        #Si no lo es
        if not sp.gcd(base,n)==1:
            print str(sp.gcd(n,base)) + " es divisor de " + str(n) + "."
            return (base,False)
        #Si lo es
        else:
            #Comprueba ahora b^t=+-1mod n
            #Si lo es
            if pow(base,t,n) == 1 or pow(base,t,n) == (-1%n):
                return (base,True)
            #Si no lo es
            else:
                i=1
                while i<=s-1 :
                    if pow(base,t*pow(2,i),n) == (-1%n):
                        return (i,base,True)
                    i=i+1
            return (base,False)
Example #2
0
 def sympy_gcd(self, p, q):
     sympy_p = self.sympy_from_upolynomial(p)
     sympy_q = self.sympy_from_upolynomial(q)
     if (p.ring().modulus() is None):
         return sympy.gcd(sympy_p, sympy_q)
     else:
         return sympy.gcd(sympy_p, sympy_q, modulus=p.ring().modulus())
Example #3
0
def factordet(Mat):
    """
    Extract common factors of the determinant of the matrix.

    Examples
    ========

    >>> from sympy import *
    >>> x, y, z = symbols('x y z')
    >>> A = Matrix([[x,x*y],[y*z,z]])
    >>> factordet(A)
    x*z
    """
    fact = 1
    ncols = Mat.cols
    for i in range(ncols):
        col = Mat.col(i)
        common = gcd(list(col))
        if (common != 0)&(common != 1):
            fact *= common
            Mat[i] = Matrix(list(map(cancel, col/common)))
    for j in range(Mat.rows):
        row = Mat.row(j)
        common = gcd(list(row))
        if (common != 0)&(common != 1):
            fact *= common
            Mat[j*ncols] = Matrix([list(map(cancel, row/common))])
    return fact
	def __generate_polydesc(self):
		# Symbols
		a,x,y = sp.symbols('a x y')
		A,X,MAX = sp.symbols('A X MAX')
		
		# Attractor limits
		x_min = (4*a**2 - a**3) / 16
		x_max = a / 4
		
		# Functions
		#  f  : Attr  -> Attr
		#  g  : Attr  -> [0,1]
		#  gi : [0,1] -> Attr
		#  F  = g o f o gi : [0,1] -> [0,1]
		f  = lambda x: a*x*(1-x)
		g  = lambda x: (x - x_min) / (x_max - x_min)
		gi_expr = sp.solve(g(x) - y, x)[0]
		gi = lambda y_val: gi_expr.subs(y,y_val)
		F_expr = g(f(gi(x))).simplify()
		F = lambda x_val: F_expr.subs(x,x_val)
		
		# Parameters
		# From [Pisarchik]: 3.57 < a < 4
		a_min = sp.Rational(387,100) #357
		a_max = sp.Rational(400,100)
		
		# Map [0,1] -> [a_max,a_min]
		h  = lambda a: (a - a_min) / (a_max - a_min)
		hi_expr = sp.solve(h(a)-x,a)[0]
		hi = lambda x_val: hi_expr.subs(x,x_val)
		
		# Discretization of F
		FD = lambda X: (MAX * F(X/MAX)).subs(a, hi(A/MAX)).simplify()
		#FD(X).diff(C) = MAX*(1849*A**2 + 22102*A*MAX + 16049*MAX**2)/(1849*A**2 + 22102*A*MAX + 56049*MAX**2)

		# Taylor coefficients
		C  = [(FD(X).taylor_term(i,X) / X**i).simplify() for i in range(3)]
		
		# Polynomial descriptor
		num = [c.as_numer_denom()[0] for c in C]
		den = [c.as_numer_denom()[1] for c in C]
		ngcd = sp.gcd(sp.gcd(num[0],num[1]),num[2])
		dgcd = sp.gcd(sp.gcd(den[0],den[1]),den[2])

		# Descriptor
		discrete.__polydesc = {
			'num' : tuple([n/ngcd for n in num]),
			'den' : tuple([d/dgcd for d in den]),
			'N'   : ngcd,
			'D'   : dgcd
		}
		discrete.__polydesc = {
			'num' : tuple([n/ngcd for n in num]),
			'den' : tuple([d/dgcd for d in den]),
			'N'   : ngcd,
			'D'   : dgcd
		}
Example #5
0
def psp(n):
    #Tomamos una base aleatoria entre 1 y n-1
    base=random.randint(1,n-1)
    #Comprobamos si gcd(b,n)=1
    #Si es false
    if not sp.gcd(base,n)==1:
        print str(sp.gcd(n,base)) + " es divisor de " + str(n) + "."
        return (base,False)
    #Si es true
    else:
        #comprueba si b(n−1)≡1 mod n
        if not pow(base,n-1,n)==1:
            return (base,False)
        else:
            return (base,True)
Example #6
0
    def order(self, strategy="relator_based"):
        """
        Returns the order of the finitely presented group ``self``. It uses
        the coset enumeration with identity group as subgroup, i.e ``H=[]``.

        Examples
        ========

        >>> from sympy.combinatorics.free_groups import free_group
        >>> from sympy.combinatorics.fp_groups import FpGroup
        >>> F, x, y = free_group("x, y")
        >>> f = FpGroup(F, [x, y**2])
        >>> f.order(strategy="coset_table_based")
        2

        """
        from sympy import S, gcd
        if self._order != None:
            return self._order
        if self._coset_table != None:
            self._order = len(self._coset_table.table)
        elif len(self.generators) == 1:
            self._order = gcd([r.array_form[0][1] for r in self.relators])
        elif self._is_infinite():
            self._order = S.Infinity
        else:
            gens, C = self._finite_index_subgroup()
            if C:
                ind = len(C.table)
                self._order = ind*self.subgroup(gens, C=C).order()
            else:
                self._order = self.index([])
        return self._order
Example #7
0
def smith_column_step(col, t, var):

    nr = len(col)
    L0 = sp.eye(nr)
    col = col.expand()
    at = col[t]

    for k, ak in enumerate(col):
        if k == t or ak == 0:
            continue
        GCD = sp.gcd(at, ak)
        alpha_t = sp.simplify(at/GCD)
        gamma_k = sp.simplify(ak/GCD)

        sigma, tau = solve_bezout_eq(alpha_t, gamma_k, var)

        L0[t, t] = sigma
        L0[t, k] = tau
        L0[k, t] = -gamma_k
        L0[k, k] = alpha_t

        new_col = sp.expand(L0*col)
        # Linksmultiplikation der Spalte mit L0 liefert eine neue Spalte
        # mit Einträgen beta bei t und 0 bei k
        break

    return new_col, L0
def decodersa(n, e, c):
    
    # using sympy factor int function obtain p,q.
    # takes significant time for long numbers
    primes = factorint(n)
    
    p, _ = dict.popitem(primes)
    q, _ = dict.popitem(primes)

    p1, q1 = p-1, q-1

    # check p-1 and q-1
    if not(gcd(p1 * q1, n) == 1):
        raise Exception('Incorrect p-1 and q-1, their GCD is not 1')
  
    p1q1 = p1 * q1

    # now we solve e*d = 1 (mod (p-1)(q-1))
    # e^-1 (mod (p-1)(q-1))
    e1 = modinv(e, p1q1)

    # check that e1 is e's modular inverse
    if not(pow(e * e1, 1, p1q1) == 1):
        raise Exception('Incorrect e^-1 and e, e*e^-1 not 1')

    # solve for d
    d = e1 % p1q1

    # solve c^d (mod n)
    decoded = pow(long(c), d, n)

    return num2alph(str(decoded))
Example #9
0
def regular(S,X,Y,nterms,degree_bound):
    """
    INPUT:

    -- ``S``: a finite set of pairs `\{(\pi_k,F_k)\}_{1 \leq k \leq B}` 
         where `\pi_k` is a finite `\mathbb{K}`-expansion, `F_k
         \in \bar{\mathbb{K}}[X,Y]` with `F_k(0,0) = 0`, `\partial_Y
         F_k(0,0) \neq 0`, and `F_k(X,0) \neq 0`.

    -- ``H``: a positive integer

    OUTPUT:
    
    -- ``(list)``: a set `\{ \pi_k' \}_{1 \leq k \leq B}` of finite
         `\mathbb{K}` expansions such that `\pi_k'` begins with
         `\pi_k` and contains at least `H` `\mathbb{K}`-terms.

    """
    R = []
    for (pi,F) in S:        
        # grow each expansion to the number of desired terms
        Npi = len(pi)

        # if a degree bound is specified, get the degree of the
        # singular part of the Puiseux series. We also want to compute
        # enough terms to distinguish the puiseux series.
        q,mu,m,beta,eta = pi[-1]
        e = reduce( lambda q1,q2: q1*q1, (tau[0] for tau in pi) )
        ydeg = sum( tau[0]*tau[2] for tau in pi )
        need_more_terms = True

        while ((Npi < nterms) and (ydeg < e*degree_bound)) or need_more_terms:
            # if the set of all (0,j), j!=0 is empty, then we've 
            # encountered a finite puiseux expansion
            a = dict(F.terms())
            ms = [j for (j,i) in a.keys() if i==0 and j!=0]
            if ms == []: break
            else:        m = min(ms)

            # if a degree bound is specified, break pi-series
            # construction once we break the bound.
            ydeg += m
            Npi += 1
                
            beta = sympy.together(-a[(m,0)]/a[(0,1)])
            tau = (1,1,m,beta,1)
            pi.append(tau)
            F = _new_polynomial(F,X,Y,tau,m)

            # if the degree in the y-series isn't divisible by the
            # ramification index then we have enough terms to
            # distinguish the puiseux series.
            if sympy.gcd(ydeg,e) == 1:
                need_more_terms = False

        R.append(tuple(pi))

    return tuple(R)
Example #10
0
def epsp(n):
    #Primer paso, si n es par devuelve (2,false)
    if(n%2==0):
        print str(n)+" es par"
        return (2,False)
    #Elegimos una base b al azar
    base=random.randint(2,n-1)
    #Comprobamos si gcd(b,n)=1
    #Si no es cierto
    if not sp.gcd(base,n)==1:
        print str(sp.gcd(n,base)) + " es divisor de " + str(n) + "."
        return (base,False)
    #Si es cierto
    else:
        if pow(base,(n-1)/2,n) == sp.jacobi_symbol(base,n)%n :
            return (base,True)
        else:
            return (base,False)
Example #11
0
def test_log_exact():
    # check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
    for n in range(-23, 24):
        if gcd(n, 24) != 1:
            assert log(exp(n * I * pi / 24).rewrite(sqrt)) == n * I * pi / 24
        for n in range(-9, 10):
            assert log(exp(n * I * pi / 10).rewrite(sqrt)) == n * I * pi / 10

    assert log(S.Half - I * sqrt(3) / 2) == -I * pi / 3
    assert log(Rational(-1, 2) + I * sqrt(3) / 2) == I * pi * Rational(2, 3)
    assert log(-sqrt(2) / 2 - I * sqrt(2) / 2) == -I * pi * Rational(3, 4)
    assert log(-sqrt(3) / 2 - I * S.Half) == -I * pi * Rational(5, 6)

    assert log(
        Rational(-1, 4) + sqrt(5) / 4 -
        I * sqrt(sqrt(5) / 8 + Rational(5, 8))) == -I * pi * Rational(2, 5)
    assert log(
        sqrt(Rational(5, 8) - sqrt(5) / 8) + I *
        (Rational(1, 4) + sqrt(5) / 4)) == I * pi * Rational(3, 10)
    assert log(-sqrt(sqrt(2) / 4 + S.Half) +
               I * sqrt(S.Half - sqrt(2) / 4)) == I * pi * Rational(7, 8)
    assert log(-sqrt(6) / 4 - sqrt(2) / 4 + I *
               (-sqrt(6) / 4 + sqrt(2) / 4)) == -I * pi * Rational(11, 12)

    assert log(-1 + I * sqrt(3)) == log(2) + I * pi * Rational(2, 3)
    assert log(5 + 5 * I) == log(5 * sqrt(2)) + I * pi / 4
    assert log(sqrt(-12)) == log(2 * sqrt(3)) + I * pi / 2
    assert log(-sqrt(6) + sqrt(2) - I * sqrt(6) -
               I * sqrt(2)) == log(4) - I * pi * Rational(7, 12)
    assert log(-sqrt(6 - 3 * sqrt(2)) - I * sqrt(6 + 3 * sqrt(2))) == log(
        2 * sqrt(3)) - I * pi * Rational(5, 8)
    assert log(1 + I * sqrt(2 - sqrt(2)) / sqrt(2 + sqrt(2))) == log(
        2 / sqrt(sqrt(2) + 2)) + I * pi / 8
    assert log(cos(pi * Rational(7, 12)) +
               I * sin(pi * Rational(7, 12))) == I * pi * Rational(7, 12)
    assert log(cos(pi * Rational(6, 5)) +
               I * sin(pi * Rational(6, 5))) == I * pi * Rational(-4, 5)

    assert log(5 * (1 + I) / sqrt(2)) == log(5) + I * pi / 4
    assert log(
        sqrt(2) *
        (-sqrt(3) + 1 - sqrt(3) * I - I)) == log(4) - I * pi * Rational(7, 12)
    assert log(
        -sqrt(2) *
        (1 - I * sqrt(3))) == log(2 * sqrt(2)) + I * pi * Rational(2, 3)
    assert log(
        sqrt(3) * I * (-sqrt(6 - 3 * sqrt(2)) -
                       I * sqrt(3 * sqrt(2) + 6))) == log(6) - I * pi / 8

    zero = (1 + sqrt(2))**2 - 3 - 2 * sqrt(2)
    assert log(zero - I * sqrt(3)) == log(sqrt(3)) - I * pi / 2
    assert unchanged(log, zero + I * zero) or log(zero + zero * I) is zoo

    # bail quickly if no obvious simplification is possible:
    assert unchanged(log, (sqrt(2) - 1 / sqrt(sqrt(3) + I))**1000)
    # beware of non-real coefficients
    assert unchanged(log, sqrt(2 - sqrt(5)) * (1 + I))
Example #12
0
    def __init__(self, numer, denom):
        if denom == 0:
            raise ValueError("Cannot have a 0 denominator")

        d = gcd(numer, denom)
        if denom < 0:
            d = -d
        self.numer = numer / d
        self.denom = denom / d
Example #13
0
def RSA(num, enc):
    p = sympy.randprime(200, 500)
    q = sympy.randprime(200, 500)
    n = p * q
    phi = (p - 1) * (q - 1)
    e = sympy.randprime(0, n)
    while sympy.gcd(e, phi) != 1:
        e = sympy.randprime(0, n)
    d = sympy.mod_inverse(e, phi)
    x = {
        "cipherString": "",
        "cipherType": "rsa",
        "curlang": "en",
        "editEntry": "1308",
        "offset": None,
        "alphabetSource": "",
        "alphabetDest": "",
        "shift": None,
        "offset2": None,
        "name1": "Allen",
        "rsa": {"p": p, "q": q, "n": n, "phi": phi, "e": e, "d": d},
    }
    if enc == "E":
        x["operation"] = "rsa2"
        x["digitsPrime"] = 4
        x["digitsCombo"] = 4
        x["points"] = 350
        x["combo"] = 1000
        x["question"] = (
            "<p>Given primes (p,q,e)=("
            + str(p)
            + ","
            + str(q)
            + ","
            + str(e)
            + "), compute the private key d.</p>"
        )
    if enc == "D":
        year = random.randint(1950, 2000)
        enc = pow(year, e, n)
        x["operation"] = "rsa4"
        x["digitsPrime"] = 4
        x["digitsCombo"] = 4
        x["points"] = 500
        x["year"] = year
        x["encrypted"] = enc
        x["name2"] = "Jason"
        x["question"] = (
            "<p>Given (n,c,d)=("
            + str(n)
            + ","
            + str(enc)
            + ","
            + str(d)
            + "), compute the original message m.</p>"
        )
    return x
Example #14
0
def phi(n):
    """ Euler's totient function."""
    assert n >= 0, 'Negative integer.'

    out = 0
    for i in range(1, n + 1):
        if gcd(n, i) == 1:
            out += 1

    return out
Example #15
0
def exercice_11():
    # Factorisation simple
    def to_str(n):
        if n < 0:
            return " - " + str(-n)
        else:
            return " + " + str(n)

    def to_x(n, carre=False):
        if n == 1:
            return "x²" if carre else "x"
        else:
            return (str(n) + "x²") if carre else (str(n) + "x")

    numbers = range(-5, -1) + range(1, 5)
    n1 = random.choice(numbers)
    n2 = random.choice(numbers)
    n3 = random.randrange(1, 10)
    x = symbols('x')
    temp = random.choice(['with x', 'without x'])
    if temp == 'with x':
        exp = to_x(n1, True) + " + " + to_x(n2)
        sol = str(simplify(n1 * x**2 + n2 * x)).replace("*", "")
        common_f = str(gcd(n1 * x**2, n2 * x)).replace("*", "")
        statement = "Factoriser l'expression algébrique suivante : " + exp
        solution = "Le facteur commun est " + common_f + ". La solution est : <span style='font-weight: bold'>" + sol + "</span>"
    else:
        exp = to_x(n1 * n3) + to_str(n2 * n3)
        sol = str(simplify(n1 * n3 * x + n2 * n3)).replace("*", "")
        common_f = str(gcd(n1 * n3 * x, n2 * n3)).replace("*", "")
        statement = "Factoriser l'expression algébrique suivante : " + exp
        solution = "Le facteur commun est " + common_f + ". La solution est : <span style='font-weight: bold'>" + sol + "</span>"
    return jsonify({
        'statement':
        statement,
        'solution':
        '''
    <div style='text-align: center'>
    ''' + solution + '''
    </div>
    '''
    }), 201
Example #16
0
 def pp(self):
     assert self
     g = self[0][1]
     for mk in self[1:]:
         g = gcd(g, mk[1])
         if g == S.One:
             return
     for mk in self:
         mk[1] /= g
         sympy.simplify(mk[1])
     assert self.assertValid()
Example #17
0
    def apply(self, args, evaluation):
        'CoprimeQ[args__]'

        py_args = [arg.to_python() for arg in args.get_sequence()]
        if not all(isinstance(i, int) or isinstance(i, complex) for i in py_args):
            return Symbol('False')

        if all(sympy.gcd(n,m) == 1 for (n,m) in combinations(py_args, 2)):
            return Symbol('True')
        else:
            return Symbol('False')
Example #18
0
    def apply(self, ns, evaluation):
        'GCD[ns___Integer]'

        ns = ns.get_sequence()
        result = 0
        for n in ns:
            value = n.get_int_value()
            if value is None:
                return
            result = sympy.gcd(result, value)
        return Integer(result)
Example #19
0
def get_prime(l):
    P = functools.reduce(mul, sympy.primerange(2, 30))
    q = random.randint(2**(l - 1), 2**l)
    while True:
        if sympy.gcd(q, P) == 1:
            break
        q += 1
    while not isprime(q):
        q += P

    return q
Example #20
0
def factor_out_from_matrix(M):
    if has_pw(M):
        return(1)

    try:
        return gcd(list(M))
    except(PolynomialError):
        #print('no factoring out possible')
        #fixme: does not work if a function of X, t is in the expressios,
        # we could make it work...if we really wanted to
        return 1
Example #21
0
def generate_random_primes(k_security, N):
    print("starting generate random_primes")
    lower_bound = 2 ** (k_security - 1)
    upper_bound = 2 ** k_security
    p = sympy.randprime(lower_bound, upper_bound)
    q = sympy.randprime(lower_bound, upper_bound)
    n_h = p * q
    e = (p - 1) * (q - 1)
    gcd_r = sympy.gcd(N, e)
    while (p == q) or (gcd_r != 1) or (not sympy.isprime(2 * p + 1)) or (not sympy.isprime(2 * q + 1)):
        while not sympy.isprime(2 * p + 1):
            p = sympy.randprime(lower_bound, upper_bound)
        while not sympy.isprime(2 * q + 1):
            q = sympy.randprime(lower_bound, upper_bound)
        n_h = p * q
        e = (p - 1) * (q - 1)
        gcd_r = sympy.gcd(N, e)
        if sympy.isprime((p + 1) / 2) and sympy.isprime((q + 1) / 2) and (p != q) and (gcd_r == 1):
            return p, q
    return p, q
Example #22
0
    def apply(self, ns, evaluation):
        "GCD[ns___Integer]"

        ns = ns.get_sequence()
        result = 0
        for n in ns:
            value = n.get_int_value()
            if value is None:
                return
            result = sympy.gcd(result, value)
        return Integer(result)
Example #23
0
    def coefficients_integerize(self):
        """Transform coefficients to integers if it could be done."""

        #  Get the list that contains all items.
        all_items = self.__left_items + self.__right_items

        #  Initialize the LCM of denominators as 1.
        denom_lcm = _math_cst.ONE

        #  Process left items.
        for item in all_items:
            #  Get the coefficient.
            coeff = item.get_coefficient().simplify()

            #  Get the denominator.
            nd = coeff.as_numer_denom()
            nd_denom = nd[1].simplify()

            #  Calculate.
            if nd_denom.is_Integer:
                denom_lcm = _sympy.lcm(denom_lcm, nd_denom)

        #  Let all coefficients multiply with the LCM value.
        for item in all_items:
            item.set_coefficient(item.get_coefficient() * denom_lcm)

        #  Initialize the GCD of numerators.
        numer_gcd = None
        use_numer_gcd = True

        for item in all_items:
            #  Get the coefficient.
            coeff = item.get_coefficient().simplify()

            #  Get the numerator.
            nd = coeff.as_numer_denom()
            nd_numer = nd[0].simplify()

            #  Calculate.
            if nd_numer.is_Integer and not nd_numer.is_zero:
                if numer_gcd is None:
                    numer_gcd = nd_numer
                else:
                    numer_gcd = _sympy.gcd(nd_numer, numer_gcd)
            else:
                use_numer_gcd = False
                break

        #  Let all coefficients divide by the GCD value if the GCD value is available.
        if use_numer_gcd and numer_gcd is not None:
            for item in all_items:
                item.set_coefficient(
                    (item.get_coefficient() / numer_gcd).simplify())
Example #24
0
    def output_flux_type(self, pool_from):
        # return 'linear', 'nonlinear', 'no substrate dependence'

        sv = self.state_vector[pool_from]
        flux = self.output_fluxes[pool_from]
        if gcd(sv, flux) == 1:
            return 'no substrate dependence'

        # now test for dependence on further state variables, which would lead to nonlinearity
        if (gcd(sv, flux) == sv) or gcd(sv, flux) == 1.0 * sv:
            flux /= sv
            free_symbols = flux.free_symbols

            for sv in list(self.state_vector):
                if sv in free_symbols:
                    return 'nonlinear'

            return 'linear'
        else:
            # probably this can never happen
            raise (Exception('Unknown internal flux type'))
def smith_step(A, t, var):
    # erste Spalte (Index: j), die nicht komplett 0 ist
    # j soll größer als Schrittzähler sein
    nr, nc = A.shape

    row_op_list = []

    cols = st.col_split(A)

    # erste nicht verschwindende Spalte finden
    for j, c in enumerate(cols):
        if j < t:
            continue
        if not c == c*0:
            break
    # Eintrag mit Index t soll ungleich 0 sein, ggf. Zeilen tauschen
    if c[t] == 0:
        i, elt = first_nonzero_element(c)
        ro = row_swap(nr, t, i)
        c = ro*c

        row_op_list.append(ro)

    col = c.expand()
    while True:
        new_col, L0 = smith_column_step(col, t, var)
        if L0 == sp.eye(nr):
            # nothing has changed
            break
        row_op_list.append(L0)
        col = new_col

    # jetzt teilt col[t] alle Einträge in col
    # Probe in der nächsten Schleife

    col.simplify()
    col = col.expand()
    for i,a in enumerate(col):
        if i == t:
            continue
        if not sp.simplify(sp.gcd(a, col[t]) - col[t]) == 0:
            IPS()
            raise ValueError, "col[t] should divide all entries in col"
        quotient = sp.simplify(a/col[t])
        if a == 0:
            continue

        # eliminiere a
        ro = row_op(nr, i, t, -1, quotient)
        row_op_list.append(ro)


    return row_op_list
Example #26
0
def simplify_rows_gcd_map(args):
    """
    Note
    ----
    As of sympy 0.7.5, there may be some issues if some x \in Wi are not
    simplified but simplify to an integer. See
    <https://github.com/sympy/sympy/issues/8384>.
    """
    i, Wi, pos_polynoms = args
    gcd_i = sympy.gcd([x for x in Wi if x != 0])
    abs_gcd_i = eval_sign(gcd_i, pos_polynoms) * gcd_i
    return (i, abs_gcd_i)
def keycreation(p, q, e):
    n = p * q

    # check p, q are primes
    if not(isprime(p) and isprime(q)):
        raise Exception('p, q are not primes')

    # check gcd(e, (p-1)(q-1))=1
    if (gcd(e, (p-1) * (q-1)) == 1): 
        return (n, e)
    else:
        raise Exception('Improper e')
Example #28
0
    def _gen_params(self, dimension, fixed_e):
        if fixed_e is not None:
            if (fixed_e % 2) == 0:
                print("Error: e is even number")
                fixed_e = None
            if fixed_e < 3:
                fixed_e = None

        difference = 2**(dimension // 2 - 2)

        while True:
            p = q = 0

            # Based on Pollard's p − 1 algorithm generate strong primes
            # https://en.wikipedia.org/wiki/Pollard%27s_p_%E2%88%92_1_algorithm
            # (p - 1 = prime * 2) => (p = prime * 2 + 1)
            while sympy.isprime(p) is False:
                p_1 = sympy.nextprime(
                    random.getrandbits(dimension // 2 + 1)) * 2
                p = p_1 + 1
            while sympy.isprime(q) is False:
                q_1 = sympy.nextprime(random.getrandbits(dimension // 2)) * 2
                q = q_1 + 1

            # Anti Fermat's factorization method
            # https://en.wikipedia.org/wiki/Fermat%27s_factorization_method
            if abs(p - q) > difference:
                n = p * q
                if lib.bitcount(n) == dimension:
                    phi = (p - 1) * (q - 1)
                    while True:
                        if fixed_e is None:
                            e = random.randint(3, phi - 1)
                        else:
                            e = fixed_e

                        if sympy.gcd(e, phi) == 1:
                            d = sympy.invert(e, phi)

                            # Anti Wiener's attack
                            # https://en.wikipedia.org/wiki/Wiener%27s_attack
                            if d > 1 / 3 * sympy.root(n, 4):
                                break
                    break

        self.p = p
        self.q = q
        self.n = n
        self.e = e
        self.d = int(d)

        return e, d, n
Example #29
0
def check_prim(n, g):

    if sympy.gcd(n, g) != 1:
        return False

    group = n - 1
    factors = sympy.ntheory.primefactors(n - 1)
    exp = [(group // i) for i in factors]

    for e in exp:
        if pow(g, e, n) == 1:
            return False
    return True
Example #30
0
def create_keys(cnt, l):
    result = []
    t = []
    n = sympy.randprime(2 ** (l - 1), 2 ** l)
    for i in range(cnt):
        e = random.randint(2, n - 1)
        while sympy.gcd(e, n - 1) != 1 and e not in t:
            e = random.randint(2, n - 1)
        t.append(e)
        d = utils.inverse(e, n - 1)
        result.append([[e, n], [d, n]])

    return result
Example #31
0
def myltx(obj, V=False):
    # This outer function handles matrices (which is what our 'vectors'
    # are) or anything else that can be changed into a list.
    if V: print('myltx(): obj is %s' % obj)
    try:
        gcd = sy.gcd(list(obj))
        if V: print('gcd=%s, type is: %s' % (gcd, type(gcd)))
        if type(gcd) != type(sqrt(2)): return (sy.latex(obj))
        obj = obj * gcd
        return (myltx(1 / gcd) + myltx_frac(obj))
    except Exception, e:
        if V: print str(e)
        return (myltx_frac(obj))
Example #32
0
def generate_primitives(degree, limit=None):
    """
    Returns a list of primitive polynomials of a given degree.

    This function searches for the first primitive polynomial using
    brute force, and then uses decimations to obtain the rest.

    Parameters
    ----------
    degree : integer
        The degree of polynomials to be returned.

    limit : integer, optional (default=None)
        If None, returns all primitive polynomials of the given degree.
        Otherwise, returns at most `limit` polynomials.

    Returns
    -------
    l : list
        List of primitive polynomials of degree `degree`.
    """
    if degree == 1:
        return [sympy.Poly(x + 1, x, modulus=2)]

    poly = None
    for k in xrange(1, 2**(degree - 1)):
        if hamming_weight(k) % 2 == 1:
            if int(
                    bin(k)[:1:-1] + '0' *
                (degree - int(sympy.log(k, 2)) - 2), 2) < k:
                continue
            proto_poly = 0
            power = 0
            while k:
                if k % 2:
                    proto_poly += x**power
                k >>= 1
                power += 1
            proto_poly *= x
            proto_poly += x**degree + 1
            poly = sympy.Poly(proto_poly, x, modulus=2)
            if is_primitive(poly):
                break

    decimations = get_representatives(degree)[:limit]
    temp_out = [
        poly_decimation(poly, t) for t in decimations
        if sympy.gcd(t, 2**degree - 1) == 1
    ]

    return sorted(temp_out, key=lambda a: a.all_coeffs())
Example #33
0
def test_log_exact():
    # check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
    for n in range(-23, 24):
        if gcd(n, 24) != 1:
            assert log(exp(n * I * pi / 24).rewrite(sqrt)) == n * I * pi / 24
        for n in range(-9, 10):
            assert log(exp(n * I * pi / 10).rewrite(sqrt)) == n * I * pi / 10

    assert log(S.Half - I * sqrt(3) / 2) == -I * pi / 3
    assert log(-S.Half + I * sqrt(3) / 2) == I * 2 * pi / 3
    assert log(-sqrt(2) / 2 - I * sqrt(2) / 2) == -I * 3 * pi / 4
    assert log(-sqrt(3) / 2 - I * S.Half) == -I * 5 * pi / 6

    assert log(-S(1) / 4 + sqrt(5) / 4 -
               I * sqrt(sqrt(5) / 8 + S(5) / 8)) == -I * 2 * pi / 5
    assert log(sqrt(S(5) / 8 - sqrt(5) / 8) + I *
               (S(1) / 4 + sqrt(5) / 4)) == I * 3 * pi / 10
    assert log(-sqrt(sqrt(2) / 4 + S(1) / 2) +
               I * sqrt(S(1) / 2 - sqrt(2) / 4)) == I * 7 * pi / 8
    assert log(-sqrt(6) / 4 - sqrt(2) / 4 + I *
               (-sqrt(6) / 4 + sqrt(2) / 4)) == -I * 11 * pi / 12

    assert log(-1 + I * sqrt(3)) == log(2) + I * 2 * pi / 3
    assert log(5 + 5 * I) == log(5 * sqrt(2)) + I * pi / 4
    assert log(sqrt(-12)) == log(2 * sqrt(3)) + I * pi / 2
    assert log(-sqrt(6) + sqrt(2) - I * sqrt(6) -
               I * sqrt(2)) == log(4) - I * 7 * pi / 12
    assert log(-sqrt(6 - 3 * sqrt(2)) -
               I * sqrt(6 + 3 * sqrt(2))) == log(2 * sqrt(3)) - 5 * I * pi / 8
    assert log(1 + I * sqrt(2 - sqrt(2)) / sqrt(2 + sqrt(2))) == log(
        2 / sqrt(sqrt(2) + 2)) + I * pi / 8
    assert log(cos(7 * pi / 12) + I * sin(7 * pi / 12)) == 7 * I * pi / 12
    assert log(cos(6 * pi / 5) + I * sin(6 * pi / 5)) == -4 * I * pi / 5

    assert log(5 * (1 + I) / sqrt(2)) == log(5) + I * pi / 4
    assert log(sqrt(2) *
               (-sqrt(3) + 1 - sqrt(3) * I - I)) == log(4) - I * 7 * pi / 12
    assert log(-sqrt(2) *
               (1 - I * sqrt(3))) == log(2 * sqrt(2)) + 2 * I * pi / 3
    assert log(
        sqrt(3) * I * (-sqrt(6 - 3 * sqrt(2)) -
                       I * sqrt(3 * sqrt(2) + 6))) == log(6) - I * pi / 8

    zero = (1 + sqrt(2))**2 - 3 - 2 * sqrt(2)
    assert log(zero - I * sqrt(3)) == log(sqrt(3)) - I * pi / 2
    assert unchanged(log, zero + I * zero) or log(zero + zero * I) == zoo

    # bail quickly if no obvious simplification is possible:
    assert unchanged(log, (sqrt(2) - 1 / sqrt(sqrt(3) + I))**1000)
    # beware of non-real coefficients
    assert unchanged(log, sqrt(2 - sqrt(5)) * (1 + I))
    def _internal_flux_type(self, pool_from, pool_to):
        """Return the type of an internal flux.

        Args:
            pool_from (int): The number of the pool from which the flux starts.
            pool_to (int): The number of the pool to which the flux goes.

        Returns:
            str: 'linear', 'nonlinear', 'no state dependence'

        Raises:
            Error: If unknown flux type is encountered.
        """
        sv = self.state_vector[pool_from]
        flux = self.internal_fluxes[(pool_from, pool_to)]

        if has_pw(flux):
            #print("Piecewise")
            #print(latex(flux))
            return "nonlinear"

        if gcd(sv, flux) == 1:
            return 'no state dependence'

        # now test for dependence on further state variables,
        # which would lead to nonlinearity
        if (gcd(sv, flux) == sv) or gcd(sv, flux) == 1.0 * sv:
            flux /= sv
            free_symbols = flux.free_symbols

            for sv in list(self.state_vector):
                if sv in free_symbols:
                    return 'nonlinear'

            return 'linear'
        else:
            # probably this can never happen
            raise (Error('Unknown internal flux type'))
Example #35
0
 def gcd(polys):
     """
     Returns greatest common divisor of given polynomials (computed w/ SymPy)
     """
     R = polys[0].get_sympy_ring()
     sympy_polys = []
     for poly in polys:
         if poly.is_unitary():
             return poly
         sympy_dict = poly.get_sympy_dict()
         if sympy_dict:
             sympy_polys.append(R(sympy_dict).as_expr())
     gcd = R(sympy.gcd(sympy_polys))
     return SparsePolynomial.from_sympy(gcd)
Example #36
0
def test_sincos_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17, 3 * 5 * 17]:
        for t in [1, 8]:
            n = t * p
            for i in xrange(1, (n + 1) // 2 + 1):
                if 1 == gcd(i, n):
                    x = i * pi / n
                    s1 = sin(x).rewrite(sqrt)
                    c1 = cos(x).rewrite(sqrt)
                    assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert 1e-10 > abs(sin(float(x)) - float(s1))
                    assert 1e-10 > abs(cos(float(x)) - float(c1))
    def check(self, f, force_prime=None):
        # try for prime divisors of constant term (might add leading term later too)
        const_coeff = abs(f.TC())
        if const_coeff == 0:
            return REDUCIBLE, None

        if force_prime is not None:
            if const_coeff % force_prime != 0:
                return UNKNOWN, None
            primes = [force_prime]
        else:
            primes = sympy.ntheory.factorint(const_coeff)

        satisfies = []
        for p in primes:
            # calculate points for given prime p for all coeffs
            points = []
            for exp, coeff in poly_non_zero_exps(f):
                if coeff != 0:
                    coeff_factors = sympy.ntheory.factorint(coeff)
                    padic = coeff_factors[p] if p in coeff_factors else 0
                    points.append((exp, padic))

            # if this can be of any use, length of line between end points must not cross any integers
            first = points[0]
            last = points[-1]
            x_diff = abs(first[0] - last[0])
            y_diff = abs(first[1] - last[1])
            if sympy.gcd(x_diff, y_diff) != 1:
                continue

            # now just check if all the other points are above this line
            x1 = first[0]
            y1 = first[1]
            x2 = last[0]
            y2 = last[1]

            above = True
            for i in range(1, len(points) - 1):
                x, y = points[i]
                if (y - y1) * (x2 - x1) <= (x - x1) * (y2 - y1):
                    above = False
                    break
            if not above:
                continue

            satisfies.append(p)
        if satisfies:
            return IRREDUCIBLE, {"p": satisfies}
        return UNKNOWN, None
Example #38
0
def test_sincos_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17, 3*5*17]:
        for t in [1, 8]:
            n = t*p
            for i in xrange(1, (n + 1)//2 + 1):
                if 1 == gcd(i, n):
                    x = i*pi/n
                    s1 = sin(x).rewrite(sqrt)
                    c1 = cos(x).rewrite(sqrt)
                    assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert 1e-10 > abs( sin(float(x)) - float(s1) )
                    assert 1e-10 > abs( cos(float(x)) - float(c1) )
Example #39
0
def encrypt(plain, key_enc, alpha):
    key_enc = sp.Matrix(key_enc)
    # Calculate the Determinant and Check if there is a solution
    D = key_enc.det()
    if sp.gcd(D, 26) != 1:
        print "Not relatively prime. No solution!"
        exit()
    # Convert plain text to Matrix to Encrypt
    mat_plain = stringToMatrix(plain, alpha, key_enc.shape[0])
    # Calculate the Cipher Matrix
    mat_cipher = key_enc * mat_plain
    # Calculate the Cipher
    cipher = matrixToString(mat_cipher, alpha, key_enc.shape[0])
    return cipher
Example #40
0
def test_sincos_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17]:
        for t in [1, 8]:
            n = t*p
            for i in xrange(1, (n + 1)//2 + 1):
                if 1 == gcd(i, n):
                    x = i*pi/n
                    s1 = sin(x).rewrite(sqrt)
                    c1 = cos(x).rewrite(sqrt)
                    assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
                    assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
    assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
Example #41
0
def test_sincos_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17]:
        for t in [1, 8]:
            n = t*p
            for i in xrange(1, (n + 1)//2 + 1):
                if 1 == gcd(i, n):
                    x = i*pi/n
                    s1 = sin(x).rewrite(sqrt)
                    c1 = cos(x).rewrite(sqrt)
                    assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
                    assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
    assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
Example #42
0
 def generate_key(self, key_bits=10):
     # choose p and q, and calculate n and phi
     # key_bits = key_bits / 2             # RSA 密钥的位数指的是 n 的位数
     self.__p = sympy.ntheory.generate.randprime(2**key_bits,
                                                 2**(key_bits + 1))
     self.__q = sympy.ntheory.generate.randprime(2**key_bits,
                                                 2**(key_bits + 1))
     self.__n = self.__p * self.__q
     self.__phi = (self.__p - 1) * (self.__q - 1)
     while True:
         # 暴力一点,直接选了一个素数当 e
         self.__e = sympy.ntheory.generate.randprime(2, self.__phi)
         self.__d = sympy.mod_inverse(self.__e, self.__phi)
         if sympy.gcd(self.__e, self.__phi) == 1:
             break
Example #43
0
def test2():
    x, a, b, c = map(Symbol, ['x', 'a', 'b', 'c'])
    #f = 2*x**2 + 5*x**3 + 4*x**4 + x**5
    f = (x + 2) * x**2 * (x + 1)**2
    f = expand(f)

    #print('ex : ', expand((x + 2) * (x**2 + x)**2))
    print('f : ', f)
    f_ = diff(f)
    print('f_ : ', f_)
    a0 = gcd(f, f_)
    print('a0 : ', a0)
    b1 = quo(f, a0)
    print('b1 : ', b1)
    c1 = quo(f_, a0)
    print('c1 : ', c1)
    d1 = c1 - diff(b1)
    print('d1 : ', d1)

    a1 = gcd(b1, d1)
    print('a1 : ', a1)
    b2 = quo(b1, a1)
    print('b2 : ', b2)
    c2 = quo(d1, a1)
    print('c2 : ', c2)
    d2 = c2 - diff(b2)
    print('d2 : ', d2)

    a2 = gcd(b2, d2)
    print('a2 : ', a2)
    b3 = quo(b2, a2)
    print('b3 : ', b3)

    L = sqf_list(f)
    #sqf(f)
    print(L)
Example #44
0
def test_tancot_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17, 3*5*17]:
        for t in [1, 8]:
            n = t*p
            for i in xrange(1, (n + 1)//2 + 1):
                if 1 == gcd(i, n):
                    x = i*pi/n
                    if  2*i != n and 3*i != 2*n:
                        t1 = tan(x).rewrite(sqrt)
                        assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
                        assert 1e-10 > abs( tan(float(x)) - float(t1) )
                    if  i != 0 and i != n:
                        c1 = cot(x).rewrite(sqrt)
                        assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
                        assert 1e-10 > abs( cot(float(x)) - float(c1) )
Example #45
0
def test_tancot_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17]:
        for t in [1, 8]:
            n = t*p
            for i in xrange(1, (n + 1)//2 + 1):
                if 1 == gcd(i, n):
                    x = i*pi/n
                    if  2*i != n and 3*i != 2*n:
                        t1 = tan(x).rewrite(sqrt)
                        assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
                        assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
                    if  i != 0 and i != n:
                        c1 = cot(x).rewrite(sqrt)
                        assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
                        assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
Example #46
0
def desingularize(f,x,y):
    """
    If f is singular, it is desginularized. Outputs new f and Puiseux 
    series expansion data.
    """

    coeffs = _coefficient(f)
    c = coeffs.pop((0,0))
    
    # for each monomial c x**j y**i find the dominant term: that is
    # the one that cancels out the constant term c. This is done
    # by substituting x = T**q, y = eta T**m giving the monomial 
    # c eta**iT**(qj+mi). To balance the equation (kill the constant term) 
    # we need qj+mi=0. q = i, m = -j satisfies this equation.
    #
    # Finally, we need to check that this choice of q,m doesn't introduce 
    # terms with negative exponent in the curve.
    q,m = (1,1)
    for (i,j),aij in coeffs.iteritems():
        # compute q,m
        g = sympy.gcd(i,j)
        q = sympy.Rational(i,g)
        m = -sympy.Rational(j,g)

        # check if the other terms remain positive.
        if all(q*jj+m*ii>=0 for ii,jj in coeffs.keys()):
            break

    if (q,m) == (1,1):
        raise ValueError("Unable to compute singular term.")            
        
    # now compute the values of eta that cancel the constant term c
    Phi = [aij*_Z**sympy.Rational(i,q) for (i,j) in coeffs.keys() 
           if q*j+m*i == 0]
    Phi = sympy.Poly(sum(Phi) + c, _Z)

    return [(q,m,0,Phi)]
Example #47
0
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
    """
    return the minimal polynomial for ``op(ex1, ex2)``

    Parameters
    ==========

    op : operation ``Add`` or ``Mul``
    ex1, ex2 : expressions for the algebraic elements
    x : indeterminate of the polynomials
    dom: ground domain
    mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None

    Examples
    ========

    >>> from sympy import sqrt, Add, Mul, QQ
    >>> from sympy.polys.numberfields import _minpoly_op_algebraic_element
    >>> from sympy.abc import x, y
    >>> p1 = sqrt(sqrt(2) + 1)
    >>> p2 = sqrt(sqrt(2) - 1)
    >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)
    x - 1
    >>> q1 = sqrt(y)
    >>> q2 = 1 / y
    >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))
    x**2*y**2 - 2*x*y - y**3 + 1

    References
    ==========

    [1] http://en.wikipedia.org/wiki/Resultant
    [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638
    "Degrees of sums in a separable field extension".
    """
    from sympy import gcd
    y = Dummy(str(x))
    if mp1 is None:
        mp1 = _minpoly_compose(ex1, x, dom)
    if mp2 is None:
        mp2 = _minpoly_compose(ex2, y, dom)
    else:
        mp2 = mp2.subs({x: y})

    if op is Add:
        # mp1a = mp1.subs({x: x - y})
        (p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y)
        r = p1.compose(p2)
        mp1a = r.as_expr()
    elif op is Mul:
        mp1a = _muly(mp1, x, y)
    else:
        raise NotImplementedError('option not available')

    r = resultant(mp1a, mp2, gens=[y, x])

    deg1 = degree(mp1, x)
    deg2 = degree(mp2, y)
    if op is Add and gcd(deg1, deg2) == 1:
        # `r` is irreducible, see [2]
        return r
    if op is Mul and deg1 == 1 or deg2 == 1:
        # if deg1 = 1, then mp1 = x - a; mp1a = x - y - a;
        # r = mp2(x - a), so that `r` is irreducible
        return r

    r = Poly(r, x, domain=dom)
    _, factors = r.factor_list()
    res = _choose_factor(factors, x, op(ex1, ex2), dom)
    return res.as_expr()
Example #48
0
def test_H7():
    p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
    p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
    assert gcd(p1, p2, x, y, z) == 1
Example #49
0
def test_H6():
    assert gcd(expand(p1 * q), expand(p2 * q)) == q
Example #50
0
def test_sincos_rewrite_sqrt():
    # equivalent to testing rewrite(pow)
    for p in [1, 3, 5, 17]:
        for t in [1, 8]:
            n = t*p
            for i in range(1, (n + 1)//2 + 1):
                if 1 == gcd(i, n):
                    x = i*pi/n
                    s1 = sin(x).rewrite(sqrt)
                    c1 = cos(x).rewrite(sqrt)
                    assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
                    assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
                    assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
    assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
    assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
    assert cos(-15*pi/2/11, evaluate=False).rewrite(
        sqrt) == -sqrt(-cos(4*pi/11)/2 + S.Half)
    assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite(
        sqrt) == -1
    e = cos(pi/3/17)  # don't use pi/15 since that is caught at instantiation
    a = (
        -3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 -
        3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) +
        17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
        + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17)
        + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - S(1)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
        3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128
        + 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) +
        17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
        + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32
        + sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 +
        sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + S(15)/32)/8 -
        5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
        S(15)/32)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 -
        3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
        sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + S(15)/32)/32
        + sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
        S(15)/32)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
        sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + S(15)/32)/2 +
        S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) +
        17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
        sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
        6*sqrt(17) + 34)/32 + S(15)/32)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
        sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
        6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
        sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
        sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
        17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
        S(15)/32)/32)/2)
    assert e.rewrite(sqrt) == a
    assert e.n() == a.n()
    # coverage of fermatCoords: multiplicity > 1; the following could be
    # different but that portion of the code should be tested in some way
    assert cos(pi/9/17).rewrite(sqrt) == \
        sin(pi/9)*sin(2*pi/17) + cos(pi/9)*cos(2*pi/17)
Example #51
0
def _simplification_technique_1(rels):
    """
    All relators are checked to see if they are of the form `gen^n`. If any
    such relators are found then all other relators are processed for strings
    in the `gen` known order.

    Examples
    ========

    >>> from sympy.combinatorics.free_groups import free_group
    >>> from sympy.combinatorics.fp_groups import _simplification_technique_1
    >>> F, x, y = free_group("x, y")
    >>> w1 = [x**2*y**4, x**3]
    >>> _simplification_technique_1(w1)
    [x**-1*y**4, x**3]

    >>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5]
    >>> _simplification_technique_1(w2)
    [x**-1*y*x**-1, x**3, x**-1*y**-2, y**5]

    >>> w3 = [x**6*y**4, x**4]
    >>> _simplification_technique_1(w3)
    [x**2*y**4, x**4]

    """
    from sympy import gcd

    rels = rels[:]
    # dictionary with "gen: n" where gen^n is one of the relators
    exps = {}
    for i in range(len(rels)):
        rel = rels[i]
        if rel.number_syllables() == 1:
            g = rel[0]
            exp = abs(rel.array_form[0][1])
            if rel.array_form[0][1] < 0:
                rels[i] = rels[i]**-1
                g = g**-1
            if g in exps:
                exp = gcd(exp, exps[g].array_form[0][1])
            exps[g] = g**exp

    one_syllables_words = exps.values()
    # decrease some of the exponents in relators, making use of the single
    # syllable relators
    for i in range(len(rels)):
        rel = rels[i]
        if rel in one_syllables_words:
            continue
        rel = rel.eliminate_words(one_syllables_words, _all = True)
        # if rels[i] contains g**n where abs(n) is greater than half of the power p
        # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0)
        for g in rel.contains_generators():
            if g in exps:
                exp = exps[g].array_form[0][1]
                max_exp = (exp + 1)//2
                rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True)
                rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True)
        rels[i] = rel
    rels = [r.identity_cyclic_reduction() for r in rels]
    return rels
Example #52
0
import socket
import fractions
import sympy

x = sympy.symbols('x')
HOST = "54.64.40.172"
PORT = 5454

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
s.connect((HOST, PORT))
while 1:
    n = int(s.recv(20000))
    all = s.recv(20000)
    all = all.split("\n")
    c1 = int(all[1])
    c2 = int(all[2])
    f = x**3-int(c1)
    g = (x+1)**3-int(c2)
    q, r = sympy.div(f, g, x)
    print q
    print r
    print sympy.gcd(g, r)
    print f
    print g
    print x
    #gcd = x - M (find m from expression above) send m
    s.send(str(int(1)) + "\n")
    print s.recv(10000)

Example #53
0
    def generer_expression(self, expr=None):
        u"""Génère une expression aléatoire en fonction respectant le format
        en cours.

        Si `expr` a une valeur, l'expression reprend la valeur de `expr`.
        """
        # Génération de l'expression:
        x = S('x')
        k = 0
        while True:
            k += 1
            # 10000 essais au maximum
            assert k < 10000
            if expr is None:
                expression = re.sub('n', self.naturel, self.pattern)
                expression = re.sub('z', self.relatif, expression)
                expression = re.sub('d', self.decimal, expression)
                expression = re.sub('q', self.rationnel, expression)
            else:
                expression = expr
            self.raw_expression = expression
            expression = expression.replace('+-', '-').replace('-+', '-')
            if '|' in expression:
                num, den = expression.split('|')
            else:
                num = expression
                den = ''
            num = num.strip()
            den = den.strip()
            if not num or num == '1':
                self.numerateur = []
            else:
                self.numerateur = num.split(',')
            if not den or den == '1':
                self.denominateur = []
            else:
                self.denominateur = den.split(',')
            if not any(gcd(S(P), S(Q)).has(x) for P in self.numerateur for Q in self.denominateur):
                # Il ne faut pas qu'un facteur apparaisse à la fois
                # au numérateur et au dénominateur.
                break

        # Génération de l'expression:
        if len(self.numerateur) > 1:
            num = ''.join(self._formater(facteur) for facteur in self.numerateur)
        else:
            num = self.numerateur[0] if self.numerateur else '1'
        if len(self.denominateur) > 1:
            den = ''.join(self._formater(facteur) for facteur in self.denominateur)
        else:
            den = self.denominateur[0] if self.denominateur else '1'
        if den == '1':
            self.expression = num
        else:
            self.expression = '(%s)/(%s)' %(num, den)

        # On génère tous les dictionnaires utiles à la construction du tableau
        self.expression_latex = convertir_en_latex(self.expression, mode=None)
        num = '*'.join('(' + s + ')' for s in self.numerateur)
        den = '*'.join('(' + s + ')' for s in self.denominateur)
        if den and num:
            self.expression_sympy = S('(%s)/(%s)' %(num, den))
        elif num:
            self.expression_sympy = S('(%s)' %num)
        else:
            assert den
            self.expression_sympy = S('1/(%s)' %den)

        self.facteurs_latex = fact_latex = OrderedDict((expr, convertir_en_latex(expr, mode=None))
                                for expr in self.numerateur + self.denominateur)
        self.facteurs_sympy = fact_sympy = OrderedDict((expr, S(expr)) for expr in fact_latex)
        self.facteurs_sols = OrderedDict((expr, solve(fact_sympy[expr])) for expr in fact_latex)
        self.facteurs_diff = OrderedDict((expr, fact_sympy[expr].diff(S('x'))) for expr in fact_latex)

        # valeurs remarquables de x
        self.sols = []
        for sols in self.facteurs_sols.values():
            self.sols.extend(sols)
        self.sols.sort()
        if param.debug:
            print('(Exercice tableau de signes) Liste des solutions: ' + str(self.sols))
Example #54
0
def test_H8():
    p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
    p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
    q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8
    assert gcd(p1 * q, p2 * q, x, y, z) == q
Example #55
0
def test_H5():
    assert gcd(p1, p2, x) == 1
Example #56
0
def test_H9():
    p1 = 2*x**(n + 4) - x**(n + 2)
    p2 = 4*x**(n + 1) + 3*x**n
    assert gcd(p1, p2) == x**n
Example #57
0
def isReducedFraction(num, det):
    #gcd(num, det, extension=True) factors rational exponents
    return (gcd(num, det) == 1 and sympify(num+'/'+det, evaluateOptions).atoms(Float) == set([]))
Example #58
0
def coPrime(n):
    num = set()
    for i in range(1, n):
        if (gcd(i, n) == 1):
            num.add(i)
    return num