예제 #1
0
    def _info(bases):
        """
        Analyze the list of bases, reporting the number of 'j-loops' that
        will be required if this list is passed to _test (stot) and the primes
        that must be cleared by a previous test.

        This info tag should then be appended to any new mr_safe line
        that is added so someone can easily see whether that line satisfies
        the requirements of mr_safe (see docstring there for details).
        """
        from sympy.ntheory.factor_ import factorint, trailing

        factors = []
        tot = 0
        for b in bases:
            tot += trailing(b - 1)
            f = factorint(b)
            factors.extend(f)
        factors = sorted(set(factors))
        bases = sorted(set(bases))
        if bases == factors:
            factors = '== bases'
        else:
            factors = str(factors)
        return ' # %s stot = %s clear %s' % tuple(
            [str(x).replace('L', '') for x in (list(bases), tot, factors)])
예제 #2
0
    def _info(bases):
        """
        Analyze the list of bases, reporting the number of 'j-loops' that
        will be required if this list is passed to _test (stot) and the primes
        that must be cleared by a previous test.

        This info tag should then be appended to any new mr_safe line
        that is added so someone can easily see whether that line satisfies
        the requirements of mr_safe (see docstring there for details).
        """
        from sympy.ntheory.factor_ import factorint, trailing

        factors = []
        tot = 0
        for b in bases:
            tot += trailing(b - 1)
            f = factorint(b)
            factors.extend(f)
        factors = sorted(set(factors))
        bases = sorted(set(bases))
        if bases == factors:
            factors = '== bases'
        else:
            factors = str(factors)
        return ' # %s stot = %s clear %s' % tuple(
                [str(x).replace('L', '') for x in (list(bases), tot, factors)])
예제 #3
0
def prime_factorization(n: int) -> List[Tuple[int, int]]:
    try:
        from sympy.ntheory.factor_ import factorint
    except ModuleNotFoundError:
        raise Exception("Install sympy to use number-theoretic functions!")
    factor_dict = factorint(n)
    return sorted(factor_dict.items())
def pohlig_helman(Y, g, p):
	print("Solving 0x%s = 0x%s^x (mod 0x%s)" % (hex(Y), hex(g), hex(p)))
	#print(factorint(p))

	t1 = time.clock()
	n = totient(p)
	t2 = time.clock()
	q = factorint(n)
	t3 = time.clock()

	print("totient(%i) = %i" % (p, n))
	print("factor(%i) = %s" % (n, str(q)))

	print("totient time: " + str(t2-t1))
	print("factor time: " + str(t3-t2))

	t4 = time.clock()
	x_is = list()
	mods = list()
	for p_i in q:
		e = q[p_i]
		
		x_i = solve_xi(Y, g, p, p_i, e, n)
		print("x = %i mod %i" % (x_i, pow(p_i, e)))
		x_is.append(x_i)
		mods.append(pow(p_i, e))
	x = chinese_remainder(mods, x_is)

	t5 = time.clock()

	print("x = %i" % x)
	print("ph time: " + str(t5-t4))

	return x
예제 #5
0
    def _eval_expand_log(self, deep=True, **hints):
        from sympy.concrete import Sum, Product
        force = hints.get('force', False)
        factor = hints.get('factor', False)
        if (len(self.args) == 2):
            return expand_log(self.func(*self.args), deep=deep, force=force)
        arg = self.args[0]
        if arg.is_Integer:
            # remove perfect powers
            p = perfect_power(arg)
            logarg = None
            coeff = 1
            if p is not False:
                arg, coeff = p
                logarg = self.func(arg)
            # expand as product of its prime factors if factor=True
            if factor:
                p = factorint(arg)
                if arg not in p.keys():
                    logarg = sum(n * log(val) for val, n in p.items())
            if logarg is not None:
                return coeff * logarg
        elif arg.is_Rational:
            return log(arg.p) - log(arg.q)
        elif arg.is_Mul:
            expr = []
            nonpos = []
            for x in arg.args:
                if force or x.is_positive or x.is_polar:
                    a = self.func(x)
                    if isinstance(a, log):
                        expr.append(self.func(x)._eval_expand_log(**hints))
                    else:
                        expr.append(a)
                elif x.is_negative:
                    a = self.func(-x)
                    expr.append(a)
                    nonpos.append(S.NegativeOne)
                else:
                    nonpos.append(x)
            return Add(*expr) + log(Mul(*nonpos))
        elif arg.is_Pow or isinstance(arg, exp):
            if force or (
                    arg.exp.is_extended_real and
                (arg.base.is_positive or
                 ((arg.exp + 1).is_positive and
                  (arg.exp - 1).is_nonpositive))) or arg.base.is_polar:
                b = arg.base
                e = arg.exp
                a = self.func(b)
                if isinstance(a, log):
                    return unpolarify(e) * a._eval_expand_log(**hints)
                else:
                    return unpolarify(e) * a
        elif isinstance(arg, Product):
            if force or arg.function.is_positive:
                return Sum(log(arg.function), *arg.limits)

        return self.func(arg)
예제 #6
0
def test_square_factor():
    assert square_factor(1) == square_factor(-1) == 1
    assert square_factor(0) == 1
    assert square_factor(5) == square_factor(-5) == 1
    assert square_factor(4) == square_factor(-4) == 2
    assert square_factor(12) == square_factor(-12) == 2
    assert square_factor(6) == 1
    assert square_factor(18) == 3
    assert square_factor(52) == 2
    assert square_factor(49) == 7
    assert square_factor(392) == 14
    assert square_factor(factorint(-12)) == 2
예제 #7
0
파일: real.py 프로젝트: bzhan/holpy
    def get_proof_term(self, t):
        a, p = t.args

        # Exponent is an integer: apply rpow_pow
        if p.is_number() and p.is_comb('of_nat', 1) and p.arg.is_binary():
            return refl(t).on_rhs(
                arg_conv(rewr_conv('real_of_nat_id', sym=True)),
                rewr_conv('rpow_pow'))

        if not (a.is_number() and p.is_number()):
            raise ConvException

        a, p = a.dest_number(), p.dest_number()
        if a <= 0:
            raise ConvException

        # Case 1: base is a composite number
        factors = factorint(a)
        keys = list(factors.keys())
        if len(keys) > 1 or (len(keys) == 1 and keys[0] != a):
            b1 = list(factors.keys())[0]
            b2 = a // b1
            eq_th = refl(Real(b1) * b2).on_rhs(real_eval_conv())
            pt = refl(t).on_rhs(arg1_conv(rewr_conv(eq_th, sym=True)))
            pt = pt.on_rhs(rewr_conv('rpow_mul'))
            return pt

        # Case 2: exponent is not between 0 and 1
        if isinstance(p, Fraction) and p.numerator // p.denominator != 0:
            div, mod = divmod(p.numerator, p.denominator)
            eq_th = refl(Real(div) + Real(mod) / p.denominator).on_rhs(
                real_eval_conv())
            pt = refl(t).on_rhs(arg_conv(rewr_conv(eq_th, sym=True)))
            a_gt_0 = auto.auto_solve(Real(a) > 0)
            pt = pt.on_rhs(rewr_conv('rpow_add', conds=[a_gt_0]))
            return pt

        return refl(t)
예제 #8
0
import sympy as sp

# The Odd-Limit

odd_limit = lambda i: max([x for x in [i.q, i.p] if x % 2 != 0])
odd_limit.__doc__ = '''
Find the odd-limit of an interval.

:param i: The interval (a ``sympy.Rational``)
:returns: The odd-limit for the interval.
'''

# Prime-limit

prime_limit = lambda i: max(
    [list(factorint(x).keys()) for x in [i.p, i.q] if x % 2 != 0])[0]
prime_limit.__doc__ = '''
Find the prime-limit of an interval.

:param i: The interval (a ``sympy.Rational``)
:returns: The prime-limit for the interval.
'''

# Note that we assume the scale to be book-ended by 1 and 2, so we drop them.

find_prime_limit_for_scale = lambda s: max([prime_limit(x) for x in s[1:-1]])
find_prime_limit_for_scale.__doc__ = '''
Find the prime-limit of an interval.

:param s: The scale (a list of ``sympy.Rational`` values)
:returns: The prime-limit for the scale.
예제 #9
0
'''
Created on 2016. 12. 10.

@author: shmoc
'''

from sympy.solvers import solve
from sympy import Symbol, factor, expand, simplify
from sympy.ntheory.factor_ import factorint
# from sympy.ntheory.factor_ import factorint
x = Symbol('x')
y = Symbol('y')


print(factor(x ** 3 + 3 * x ** 2 * y + 3 * x * y ** 2 + y ** 3))


# prime factorization
print(factorint(64))


print(factor(x**2+x-6))
예제 #10
0
def extract_fundamental_discriminant(a):
    r"""
    Extract a fundamental discriminant from an integer *a*.

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

    Given any rational integer *a* that is 0 or 1 mod 4, write $a = d f^2$,
    where $d$ is either 1 or a fundamental discriminant, and return a pair
    of dictionaries ``(D, F)`` giving the prime factorizations of $d$ and $f$
    respectively, in the same format returned by :py:func:`~.factorint`.

    A fundamental discriminant $d$ is different from unity, and is either
    1 mod 4 and squarefree, or is 0 mod 4 and such that $d/4$ is squarefree
    and 2 or 3 mod 4. This is the same as being the discriminant of some
    quadratic field.

    Examples
    ========

    >>> from sympy.polys.numberfields.utilities import extract_fundamental_discriminant
    >>> print(extract_fundamental_discriminant(-432))
    ({3: 1, -1: 1}, {2: 2, 3: 1})

    For comparison:

    >>> from sympy import factorint
    >>> print(factorint(-432))
    {2: 4, 3: 3, -1: 1}

    Parameters
    ==========

    a: int, must be 0 or 1 mod 4

    Returns
    =======

    Pair ``(D, F)``  of dictionaries.

    Raises
    ======

    ValueError
        If *a* is not 0 or 1 mod 4.

    References
    ==========

    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
       (See Prop. 5.1.3)

    """
    if a % 4 not in [0, 1]:
        raise ValueError(
            'To extract fundamental discriminant, number must be 0 or 1 mod 4.'
        )
    if a == 0:
        return {}, {0: 1}
    if a == 1:
        return {}, {}
    a_factors = factorint(a)
    D = {}
    F = {}
    # First pass: just make d squarefree, and a/d a perfect square.
    # We'll count primes (and units! i.e. -1) that are 3 mod 4 and present in d.
    num_3_mod_4 = 0
    for p, e in a_factors.items():
        if e % 2 == 1:
            D[p] = 1
            if p % 4 == 3:
                num_3_mod_4 += 1
            if e >= 3:
                F[p] = (e - 1) // 2
        else:
            F[p] = e // 2
    # Second pass: if d is cong. to 2 or 3 mod 4, then we must steal away
    # another factor of 4 from f**2 and give it to d.
    even = 2 in D
    if even or num_3_mod_4 % 2 == 1:
        e2 = F[2]
        assert e2 > 0
        if e2 == 1:
            del F[2]
        else:
            F[2] = e2 - 1
        D[2] = 3 if even else 2
    return D, F
예제 #11
0
파일: pb611_3.py 프로젝트: desaxce/euler
def delta(m):
	if m==1:
		return 1
	return min(factorint(m), key=int)
예제 #12
0
파일: pb611_3.py 프로젝트: desaxce/euler
def gamma(m):
	if m==1:
		return 1
	return max(factorint(m), key=int)