Example #1
0
def least_common_multiple(divisors=range(1, 21)):
    # Returns least common multiple of INTs in <divisors>

    # No matter the divisors, we at least need the max divisor as an LCM
    lcm = max(divisors)
    lcm_factors = sympy.factorint(lcm)

    for n in divisors:
        n_factors = sympy.factorint(n)

        for f in n_factors:

            # If this factor appears in the LCM ...
            if f in lcm_factors:
                factor_excess = lcm_factors[f] - n_factors[f]

                # ... check if there are enough of them
                if factor_excess < 0:

                    # If not, we multiply into LCM to account for this
                    lcm *= - factor_excess * f
                    lcm_factors[f] += - factor_excess

            # If this factor does not appear in the LCM, multiple into LCM
            else:
                lcm *= n_factors[f] * f
                lcm_factors[f] = n_factors[f]

    return lcm
Example #2
0
def mu(n):

    # check if the value is memoized
    check = memo.get(n)
    if check is not None:
        return memo[n]

    # sympy.perfect_power returns (base, exp) or False
    tmp = perfect_power(n)
    if tmp:

        # if n is a prime power not pre-memoized, then exp > base, and we use kempner's algorithm from [1]
        if isprime(tmp[0]):
            return (tmp[0] - 1) * tmp[1] + sumk(tmp[0], tmp[1])

        # sympy.factorint returns a dictionary of { primefactor : power }
        # we recursively check the value of mu(primefactor**power), returning the max
        # this should be very fast most of the time, as small primes have all been pre-memoized
        else:
            f = factorint(n)
            memo[n] = max([mu(p**f[p]) for p in f.keys()])
            return memo[n]
    else:

        # any prime not pre-memoized : mu(p) = p
        if isprime(n):
            memo[n] = n
            return memo[n]

        # else recursively check the prime powers in n's factorization as above
        f = factorint(n)
        memo[n] = max([mu(p**f[p]) for p in f.keys()])
        return memo[n]
def totient_comparisons(max_n):
    #x is our modulus
    false_pos = 0
    false_neg = 0
    for x in range(3, max_n):
        self_squares = []
        #factoring to find invertible numbers
        primes = factorint(x)

        #checking all the numbers where gcd(x,y)=1
        for y in range(1, x):
            #checks that no prime divisors of our modulus (x) divide our number y
            #then checks if y is its own inverse
            if all(y % p != 0 for p in primes.keys()) and (y * y) % x == 1:
                self_squares.append(y)

        #if we have some interesting solutions, verify the relationship between
        #totient(n)%4 and the existence of solutions (it's necessary, not sufficient)
        if (len(self_squares) > 2) != (sp.totient(x) % 4 == 0):
            if len(self_squares) > 2:
                false_neg += 1
            else:
                false_pos += 1
        if len(self_squares) > 2:
            print("Solution totient: {}".format(
                sp.factorint(sp.totient(max(self_squares)))))
            #looking at the factorizations of solutions
            print("N totient: {}".format(sp.factorint(sp.totient(x))))
    print("False positive solns: {} False negative solns: {}".format(
        false_pos, false_neg))
Example #4
0
def main():
        print "euler23.py"
        print sum(proper_factors(28))
        print deficient(28)
        print perfect(28)
        print factorint(28)
        abridged_abundant = lambda(x): x%6 != 0 and x%28 != 0 and x%496 != 0 and abundant(x)
        print ascuii_map([('X', abridged_abundant), (' ', nil)], ['list', 0, 8000, 60])
Example #5
0
def factor_fraction(fraction):
    N, D = to_numerator_denominator_pair(fraction)

    ps = factorint(N)
    qs = factorint(D)
    L = len(ps) + len(qs)

    ps.update((q, -exp) for q, exp in qs.items())
    assert len(ps) == L
    return ps
Example #6
0
def main():
    print('----------------Lluís----------------')
    print(sympy.factorint(nLluis))
    #115281056474331054700251942688513962925044855473544908166056180479356817897219  4 veces
    #3347812451 32 veces
    print("phi(p): ")
    p = 115281056474331054700251942688513962925044855473544908166056180479356817897219**4
    p_1 = (p - 1) * (p**3)
    print(p_1)
    print("phi(q): ")
    q = 3347812451**32
    q_1 = (q - 1) * (q**31)
    print(q_1)
    print("phi(n): ")
    phi_n = p_1 * q_1
    print(phi_n)
    dLluis = sympy.gcdex(e, phi_n)[0]
    privateLluis = RSA.construct((nLluis, e, int(dLluis)))

    outputLluis = open('keyLluis2.pem', 'wb')
    outputLluis.write(privateLluis.exportKey('PEM'))
    outputLluis.close()

    #openssl rsautl -decrypt -inkey keyLluis2.pem -in lluis.marques_RSA_pseudo.enc -out decLluis2

    print('----------------Toni----------------')
    print(sympy.factorint(nToni))
    #3916392617 32 veces
    #238276963031717718724382324364818146621 8 veces
    p2 = 3916392617**32
    p2_1 = (p2 - 1) * (p2**31)
    print("phi(p2): ")
    print(p2_1)
    print("phi(q2): ")
    q2 = 238276963031717718724382324364818146621**8
    q2_1 = (q2 - 1) * (q2**7)
    print(q2_1)
    print("phi(n2): ")
    phi_n2 = p2_1 * q2_1
    print(phi_n2)
    dToni = sympy.gcdex(e, phi_n2)[0]
    dToni = dToni % phi_n2  # dona negatiu, cal fer modul
    privateToni = RSA.construct((nToni, e, int(dToni)))

    outputToni = open('keyToni2.pem', 'wb')
    outputToni.write(privateToni.exportKey('PEM'))
    outputToni.close()

    #openssl rsautl -decrypt -inkey keyToni2.pem -in antonio.guilera_RSA_pseudo.enc -out decToni2

    print(
        '-------------------------------------DONETTE-------------------------------------'
    )
Example #7
0
def main():
    count = 0
    min = 2 * 3 * 5 * 7
    while True:
        if len(sympy.factorint(min)) == 4:
            count = count + 1
        else:
            count = 0
        if count == 4:
            print ("%d" % (min - 3))
            print(sympy.factorint(min - 3))
            break
        min = min + 1
Example #8
0
File: poly.py Project: bzhan/holpy
def reduce_power(n, e):
    """Reduce n^e to normal form."""
    if isinstance(n, expr.Expr):
        return ((n, e),)
    elif isinstance(n, int):
        if n >= 0:
            return tuple((ni, e * ei) for ni, ei in sympy.factorint(n).items())
        else:
            assert Fraction(e).denominator % 2 == 1, 'reduce_power'
            return ((-1, 1),) + tuple((ni, e * ei) for ni, ei in sympy.factorint(-n).items())
    elif n in (Decimal("inf"), Decimal("-inf")):
        return ((n, e),)
    else:
        raise NotImplementedError
def get_times(bits):
    fact_times = []
    mul_times = []
    for bit in bits:
        fact_param = randbits(bit)
        mul_param = [k**v for k, v in factorint(fact_param).items()]
        fact_time = timeit.timeit(lambda: factorint(fact_param),
                                  "from sympy import factorint",
                                  number=1000)
        mul_time = timeit.timeit(lambda: Mul(*mul_param),
                                 "from sympy import Mul",
                                 number=1000)
        fact_times.append(fact_time)
        mul_times.append(mul_time)
    return fact_times, mul_times
def is_semiprime(n):
    factors = sym.factorint(n)
    if len(factors) == 2:
        return n
    if len(factors.values()) == 1 and list(factors.values())[0] == 2:
        return n
    return 0
Example #11
0
def totient(n):
    if isprime(n):
        return n - 1
    result = n
    for p in factorint(n).keys():
        result *= (1 - 1 / p)
    return result
Example #12
0
 def _GeneratesMaxPeriodSecondCondition(self, a, M):
     # Calculate M prime factors
     MPrimeFactors = list(factorint(M).keys())
     # Calculate a congruent 1 mod p for each prime im M factorization
     congruences = all(
         (a % prime) == (1 % prime) for prime in MPrimeFactors)
     return congruences
Example #13
0
def euler47():
    i = 646
    while True:
        i += 1
        if all(len(factorint(i + j).keys()) == 4 for j in range(4)):
            print(i)
            return
Example #14
0
def euler47():
    i = 646
    while True:
        i += 1
        if all(len(factorint(i+j).keys()) == 4 for j in range(4)):
            print(i)
            return
Example #15
0
def n_order(a, n, f):
    from collections import defaultdict
    a, n = as_int(a), as_int(n)
    if igcd(a, n) != 1:
        raise ValueError("The two numbers should be relatively prime")
    factors = defaultdict(int)
    for px, kx in f.items():
        if kx > 1:
            factors[px] += kx - 1
        fpx = factorint(px - 1)
        for py, ky in fpx.items():
            factors[py] += ky
    group_order = 1
    for px, kx in factors.items():
        group_order *= px**kx
    order = 1
    if a > n:
        a = a % n
    for p, e in factors.items():
        exponent = group_order
        for f in range(e + 1):
            if pow(a, exponent, n) != 1:
                order *= p**(e - f + 1)
                break
            exponent = exponent // p
    return order
Example #16
0
 def factor(self, n):
     """Simple example of specific protocol functionality
     """
     log.msg('Factor ', n)
     f = factorint(long(n))
     log.msg('Factors: ', str(f))
     return 
Example #17
0
def is_cyclic_number(n):
    """
    Check whether `n` is a cyclic number. A number `n` is said to be cyclic
    if and only if every finite group of order `n` is cyclic. For more
    information see [1]_.

    Examples
    ========

    >>> from sympy.combinatorics.group_numbers import is_cyclic_number
    >>> from sympy import randprime
    >>> is_cyclic_number(15)
    True
    >>> is_cyclic_number(randprime(1, 2000)**2)
    False
    >>> is_cyclic_number(4)
    False

    References
    ==========

    .. [1] Pakianathan, J., Shankar, K., *Nilpotent Numbers*,
            The American Mathematical Monthly, 107(7), 631-634.

    """
    if n <= 0 or int(n) != n:
        raise ValueError("n must be a positive integer, not %i" % n)

    n = Integer(n)
    if not is_nilpotent_number(n):
        return False

    prime_factors = list(factorint(n).items())
    is_cyclic = all(a_i < 2 for p_i, a_i in prime_factors)
    return is_cyclic
Example #18
0
def sort_N(DF,forms,all_N_factors):
    Nf = 1.0*1000*1000
    DiscF_factors = sympy.factorint(DF*4)
    a0 = twos[DF]
    b0 = threes[DF]
    N1 = noTwoThree(DF, a0, b0)
    DF_info = {}
    DF_obstructions = {}
    for k in range(1, int(Nf / N1) + 1):
        N = N1 * k
        a = twos[N]
        b = threes[N]
        if a_okay(a, a0) and b_okay(b, b0):
            N_factors = all_N_factors[N]
            prime_bounds,prime_list = exponents(N,DF*4,N_factors,DiscF_factors)
            all_local_obstructions = []
            new_forms = []
            for F in forms:
                local_obstruction = local_test(F,DF*4,N_factors)
            print(N)



                if local_obstruction == []:
                    new_forms.append(F)
                else:
                    all_local_obstructions.append([N,F,local_obstruction[0]])
            if new_forms != []:
                DF_info[N] = [N,new_forms,prime_bounds,prime_list]
            if all_local_obstructions != []:
                DF_obstructions[N] = all_local_obstructions
Example #19
0
def CheckPrime(x, y):
    n = x * 10 + y
    d = sympy.factorint(n)
    if n in d:
        return 1
    else:
        return 0
Example #20
0
    def _eval_expand_log(self, deep=True, **hints):
        from sympy import unpolarify, expand_log, factorint
        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)
Example #21
0
def factor(expression, variable = None, ensemble = None, decomposer_entiers = True):
    if isinstance(expression, (int, long, Integer)):
        if decomposer_entiers:
            return ProduitEntiers(*factorint(expression).iteritems())
        else:
            return expression


    elif isinstance(expression, Basic) and expression.is_polynomial():
        if variable is None:
            variable = extract_var(expression)
        if variable is None:
            # polynôme à plusieurs variables
            return factor_(expression)
        else:
            try:
                return poly_factor(expression, variable, ensemble)
            except NotImplementedError:
                if param.debug:
                    print_error()
                return expression
    resultat = together_(expression)
    if resultat.is_rational_function():
        num, den = resultat.as_numer_denom()
        if den != 1:
            return factor(num, variable, ensemble, decomposer_entiers)/factor(den, variable, ensemble, decomposer_entiers)
    else:
        resultat = auto_collect(resultat)
        if resultat.is_Mul:
            produit = 1
            for facteur in resultat.args:
                if facteur != 1:
                    produit *= factor(facteur, variable, ensemble, decomposer_entiers)
            return produit
        return resultat
Example #22
0
def primes_pop(a):
    if isinstance(a, int):
        if a < 2:
            return []
        try:
            import sympy
            factor_dict = sympy.factorint(a)
            factors_with_mult = [[fact for _ in range(factor_dict[fact])] for fact in factor_dict]
            return sorted(sum(factors_with_mult, []))
        except:
            working = a
            output = []
            num = 2
            while num * num <= working:
                while working % num == 0:
                    output.append(num)
                    working //= num
                num += 1
            if working != 1:
                output.append(working)
            return output
    if is_num(a):
        return cmath.phase(a)
    if is_seq(a):
        return a[:-1]
    raise BadTypeCombinationError("P", a)
def fac_list(n):
    f_list = [1]
    prime_fac_dict = sympy.factorint(n)
    for i, j in prime_fac_dict.items():
        f_list.extend([a * i ** k for a in f_list[:] for k in range(1, j+1)])
    f_list.remove(n)
    return f_list
Example #24
0
def best_square(n):
    from sympy import factorint
    import itertools

    if n == 1:
        return 1, 1

    # find nearly square factors to cover depth
    pfd = factorint(
        n)  # the prime factors of ndepth, which is the number of feature maps
    f = []
    for key, val in pfd.items(
    ):  # pfd is a dictionary of factors and number of times they
        f.append([key] *
                 val)  # occur, e.g. 24 -> {{2,3},{3,1}} . So expand it....
    f = list(itertools.chain.from_iterable(f))  #...and then flatten it.
    f.sort()

    prod = 1
    pmax = int(n**0.5)
    print(f)
    for pf in f:
        if prod * pf <= pmax:
            prod *= pf
        else:
            nrows = prod
            ncols = n // nrows
            break

    return nrows, ncols
Example #25
0
    def compute_MDRS(n):
        """Computes the MDRS from a number n using greedy local search."""
        candidates = []  # Candidates with local optimal DRS

        def improve(factors):
            """Recursively multiply two factors as long as it
            does not decrease the digital root sum of the factors."""
            factors = defaultdict(int, factors)
            improvement = 0
            for a, b in find_pairs(factors):
                c = a*b
                # If local improvement is possible, create remove the two
                # old factors once and introduce a new one
                if DR[c] >= DR[a] + DR[b]:
                    new_factors = factors.copy()
                    new_factors[a] -= 1
                    new_factors[b] -= 1
                    new_factors[c] += 1
                    improvement += 1
                    improve(new_factors)

            # If no more local improvements are possible then add
            # to the pool of local optima as candidates for MDRS
            if not improvement:
                candidates.append(factors)

        # Compute the potential candidates
        improve(factorint(n))
        return max([DRS(f) for f in candidates])
Example #26
0
	def operate(self, a):
		if isinstance(a, int):
			if a < 0:
				# Primality testing
				return len(self.operate(-a)) == 1
			if a < 2:
				return []
			try:
				from sympy import factorint
				factor_dict = factorint(a)
				factors_with_mult = [[fact for _ in range(
					factor_dict[fact])] for fact in factor_dict]
				return sorted(sum(factors_with_mult, []))
			except:
				working = a
				output = []
				num = 2
				while num * num <= working:
					while working % num == 0:
						output.append(num)
						working //= num
					num += 1
				if working != 1:
					output.append(working)
				return output
		if is_num(a):
			return cmath.phase(a)
		if is_seq(a):
			return a[:-1]
		raise BadTypeCombinationError("P", a)
def is_semiprime(n):
    factors = sym.factorint(n)
    if len(factors) == 2:
        return n
    if len(factors.values()) == 1 and list(factors.values())[0] == 2:
        return n
    return 0
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 #29
0
def totient(n):
    from sympy import factorint
    fact_dict = factorint(n)
    phi_ = 1
    for key, val in fact_dict.items():
        phi_ *= key**val - key**(val - 1)
    return phi_
Example #30
0
def factorize(*args, **kwargs):
    temp = sympy.factorint(*args, **kwargs)
    output = []
    for k in temp:
        for i in range(temp[k]):
            output.append(k)
    return output
Example #31
0
def report_for_base(base):
    seqs = get_sequences_for_base(base)
    seq_lens = [
        len(seq) - 2 for seq in seqs
    ]  # len of sequence is actually number of pairs in it, = len(seq) - 2
    print("base {} has {} sequences".format(base, len(seqs)))
    print("lengths in order of sequence number: {}".format(seq_lens))
    print("lengths in sorted order:             {}".format(sorted(seq_lens)))
    print()
    tuple_to_seq_number = {}
    for i, seq in enumerate(seqs):
        print("seq #{}, len {} with factorization {}".format(
            i, seq_lens[i], sympy.factorint(seq_lens[i])))
        print(seq)
        pairs = get_conditions_in_sequence(seq)
        for pair in pairs:
            tuple_to_seq_number[tuple(pair)] = i
        print()

    print("\n" + ("-" * 40) + "\n")

    if base <= 50:
        show_table(base, tuple_to_seq_number)
    else:
        print("too big to show table")
Example #32
0
def a(n):  # Orson R. L. Peters, Jan 31 2017
    r = 1
    factors = factorint(n)
    for p, e in factors.items():
        if p % 4 == 1: r *= 2 * e + 1
        if r * 4 > 420: return 0
    return 4 * r if n > 0 else 0
def GenerateSquareRoots(base, gen):
    # Establecemos las variables globales al nuevo valor
    global BASE, GEN, P_FACTS, ROOTS
    BASE = base
    GEN = gen

    # El orden del generador es el cardinal de todos los elementos menos el 0
    order = base - 1

    # Calculamos los factores primos con su exponente
    P_FACTS = factorint(order)

    # Tabla con las raíces de la unidad
    ROOTS = {}

    # Rellenamos la tabla de raíces
    for i in P_FACTS:
        # Raíces p_i-ésimas
        i_roots = {}

        # Variables para rellenar ROOTS
        aux = 1
        step = FastExp(gen, order / i, base)

        # Llenamos la lista
        for j in range(i):
            i_roots[aux] = j

            # Nos ahorramos calcular potencias a cambio de un producto
            aux = aux * step % base

        # Las introducimos al resto de raíces
        ROOTS[i] = i_roots
Example #34
0
def drawnumber(xo,yo,num):
    if num == 1:
        factors = [1]
    else:
        factors = sympy.factorint(num)
        factors = list(sympy.utilities.iterables.multiset_combinations(factors, sum(factors.values())))[0]

    factors=factors[0::2] + factors[1::2]

    for ix,f in enumerate(factors):
        theta1 = 90+360*(ix-.5)/len(factors)
        theta2 = 90+360*(ix+.5)/len(factors)
        color = primecolors.get(f)
        if not color: 
            color = primecolors.get("fallback")
        p = patches.Wedge(center=(xo,yo), r=0.5, theta1=0, theta2=360, 
                          edgecolor="none", facecolor=primecolors.get('background'), linewidth=0);
        plt.gca().add_patch(p)
        p = patches.Wedge(center=(xo,yo), r=1.0, theta1=theta1, theta2=theta2, width=0.5, 
                          edgecolor=primecolors.get('background'), facecolor=color, linewidth=1)
        plt.gca().add_patch(p)
        
        plt.text(xo-0.01,yo-0.03, "{}".format(num),horizontalalignment='center',verticalalignment='center', 
                 color=primecolors.get('text'), weight='bold', size=12.0)
        if (f>primecolors['maxprimecolor']) & (len(factors)>1):
            theta = (theta1+theta2)*.5
            plt.text(xo+numpy.cos(theta*numpy.pi/180)*.75,yo+numpy.sin(theta*numpy.pi/180)*.75, 
                     f, horizontalalignment='center',verticalalignment='center', fontsize=6, weight='bold',
                     color=primecolors.get('text'))
Example #35
0
def factor_special(n):
    dic1 = sympy.factorint(n)
    dic2 = {}
    for i in dic1:
        if dic1[i] != 1:
            dic2[i] = dic1[i] // 2
    return dic2
def show(value):
    '''
    use sympy.factorint() and display in formatted form
    '''
    assert value >= 0

    # factorint() will return dict with factor and its
    myd = factorint(value)
    # output the result...
    msg = f'{value} = '
    #print(value, "= ", end='')
    arr = list(myd.keys())
    arr.sort()
    isFirst = True
    for key in arr:
        if not isFirst:
            #print(" * ", end='')
            msg = msg + ' * '
        else:
            isFirst = False
        val = myd[key]
        if val == 1:
            msg = msg + str(key)
            #print(key, end='')
        else:
            #print("{}**{}".format(key, myd[key]), end='')
            msg = msg + f"{key}**{myd[key]}"
    if HAS_CONSOLE_MODULE:
        console.alert(msg)
    else:
        print(msg)
Example #37
0
def gen_prime(a, b, smooth):
    while (True):
        p = randprime(a, b)

        factors = factorint(p - 1, limit=smooth)
        if (isprime(max(factors)) and max(factors) < smooth):
            return p
Example #38
0
def exec_time_of_fft():
    '''
    @Description: 
        观察不同平滑度输入数组的FFT计算时间,理解Cooley-Tukey算法的时间复杂度
        最优情况下n(long(n)),退化到最坏情况下n^2
    '''
    K = 1000
    lengths = range(250, 260)
    # 计算所有输入长度的平滑度
    smoothness = [max(factorint(i).keys()) for i in lengths]
    exec_time_of_fft_array = []
    for i in lengths:
        '''traverse all possible input lengths, and record the minimum time in multiple times calculation'''
        z = np.random.random(i)
        times = []
        for k in range(K):
            tic = time.monotonic()
            fftpack.fft(z)
            toc = time.monotonic()
            times.append(toc - tic)
        exec_time_of_fft_array.append(min(times))
    _, (ax0, ax1) = plt.subplots(2, 1, sharex=True)
    ax0.stem(lengths, np.array(exec_time_of_fft_array) * 1e6)
    ax0.set_xlabel('Length of input array')
    ax0.set_ylabel('Execution time [us]')
    ax1.stem(lengths, np.array(smoothness))
    ax1.set_ylabel('Smoothness of input length\n(lower is better)')
    plt.savefig('./4_6_execution_time_of_fft.png')
Example #39
0
def calFactors(x):
    if x % 2 == 0: x //= 2
    divs = factorint(x)
    num = 1
    for p in divs:
        num *= divs[p] + 1
    return num
Example #40
0
def _coprime_density(value):
    """Returns float > 0; asymptotic density of integers coprime to `value`."""
    factors = sympy.factorint(value)
    density = 1.0
    for prime in six.iterkeys(factors):
        density *= 1 - 1 / prime
    return density
Example #41
0
 def apply(self, n, evaluation):
     'FactorInteger[n_]'
     
     if isinstance(n, Integer):
         factors = sympy.factorint(n.value)
         factors = sorted(factors.iteritems())
         return Expression('List', *[Expression('List', factor, exp) for factor, exp in factors])
     elif isinstance(n, Rational):
         factors = sympy.factorint(n.value.numer())
         factors_denom = sympy.factorint(n.value.denom())
         for factor, exp in factors_denom.iteritems():
             factors[factor] = factors.get(factor, 0) - exp
         factors = sorted(factors.iteritems())
         return Expression('List', *[Expression('List', factor, exp) for factor, exp in factors])
     else:
         return evaluation.message('FactorInteger', 'exact', n)
Example #42
0
def factor_special(n):
    dic1 = sympy.factorint(n)
    dic2 = {}
    for i in dic1:
        if dic1[i] != 1:
            dic2[i] = dic1[i]//2
    return dic2
Example #43
0
    def __set_letters(self, message: str) -> None:
        letters = []

        for letter in message:
            letters.append(sp.factorint(ord(letter), multiple=True))

        self.letters = np.array(letters, dtype=object)
Example #44
0
def phi(n):
    factor = list(factorint(n))
    
    phi = n
    for i in range(1, len(factor) +1):
        for j in combinations(factor, i):
            phi += (-1) ** i * (n // product(j))
    return phi
Example #45
0
def phi(n):
    if isPrime(n):
        return n-1
    else:
        factors = factorint(n)
        res = n
        for f in list(factors.keys()):
            res = res*(1 - 1/f)
    return res
Example #46
0
def radical(n):
    """A radical is the product of distinct prime factors

    For example, 504 = 2^3 x 3^2 x 7, so radical(504) = 2 x 3 x 7 = 42

    >>> radical(504)
    42
    """
    return product(sympy.factorint(n).keys())
Example #47
0
 def eval(cls, expr):
     if expr.is_Integer:
         from sympy import factorint
         factors = factorint(Abs(expr), limit=10000)
         factorlist=list(factors.keys())
         factorlist.sort()
         return factorlist[0]
     else:
         raise ValueError("Argument to smallest_factor must be an integer")
Example #48
0
def omega(nval):
    if nval == 1:
        return 0
    if nval in prime_exponent_dicts:
        pd = prime_exponent_dicts[nval]
    else:
        pd = sympy.factorint(nval)
        prime_exponent_dicts[nval] = pd
    return len(pd)
Example #49
0
def main():
    ''' main function '''
    while True:    # input value <= zero to exit
        val = input("input an postive integer (0 to quit): ")
        val = int(val)
        if val <= 0:
            break
        fdict = factorint(val)
        print(fdict)
Example #50
0
def distinct_powers(max_a, max_b):
    power_set = set()
    for a in range(2, max_a + 1):
        prime_factors = sorted(factorint(a).items())
        power_primes = list(prime_factors)
        for b in range(2, max_b + 1):
            power_primes = [(z[0][0], z[0][1] + z[1][1]) for z in zip(power_primes, prime_factors)]
            power_representation = ",".join("{}:{}".format(p[0], p[1]) for p in power_primes)
            power_set.add(power_representation)
    return len(power_set)
def fun(n):
    if n == 1:
        return 1
    factor_list = [1]
    for i, j in sp.factorint(n).items():
        for s in factor_list[:]:
            for t in range(1, j + 1):
                factor_list.append(s * i ** t)
    factor_list.remove(n)
    return sum(factor_list)
Example #52
0
def check(n):
    test = float(n)
    if (test/2).is_integer() and not (test/4).is_integer():
        return False
    T1 = time.time()
    primes = sympy.factorint(n)
    global tijd
    tijd += time.time()-T1
    count1 = 0
    count2 = 0
    count3 = 0
    count7 = 0
    for p in primes:
        power = primes[p] % 2
        if p % 4 == 3:
            if power == 1:
                return False
            count1 += 1
        else:
            if p != 2:
                count1 -= 10000
            count1 += 1

        if p % 8 in {5, 7}:
            if power == 1:
                return False
            count2 += 1
        else:
            if p != 2:
                count2 -= 10000
            count2 += 1

        if p % 3 == 2:
            if power == 1:
                return False
            if p == 2:
                count3 -= 10000
            count3 += 1
        else:
            if p != 3:
                count3 -= 10000

        if p % 7 in {3, 5, 6}:
            if power == 1:
                return False
            count7 += 1
        else:
            if p != 7 and p != 2:
                count7 -= 10000
            if p == 2:
                if primes[p] > 2:
                    count7 -= 10000
    if count1 > 0 or count2 > 0 or count3 > 0 or count7 > 0:
        return False
    return True
Example #53
0
    def apply(self, n, evaluation):
        'PrimePowerQ[n_]'
        n = n.get_int_value()
        if n is None:
            return Symbol('False')

        n = abs(n)
        if len(sympy.factorint(n)) == 1:
            return Symbol('True')
        else:
            return Symbol('False')
Example #54
0
def smallest_number_whose_square_is_divisible_by_n(nval):
    if nval == 1:
        return 1
    if nval in prime_exponent_dicts:
        pd = prime_exponent_dicts[nval]
    else:
        pd = sympy.factorint(nval)
        prime_exponent_dicts[nval] = pd
    snwsidbn = 1
    for pval, expval in pd.items():
        snwsidbn *= math.pow(pval, math.ceil(expval / 2))
    return int(snwsidbn)
Example #55
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
Example #56
0
def sigma_1(nval):
    if nval == 1:
        return 1
    if nval in prime_exponent_dicts:
        pd = prime_exponent_dicts[nval]
    else:
        pd = sympy.factorint(nval)
        prime_exponent_dicts[nval] = nval
    psigmult = 1
    for pval, expval in pd.items():
        psigmult *= ((math.pow(pval, expval + 1) - 1) / (pval - 1))
    return int(psigmult)
Example #57
0
def sigma_0_pow(nval, powval=1):
    if nval == 1:
        return 1
    if pow == 0:
        return 1
    if nval in prime_exponent_dicts:
        pd = prime_exponent_dicts[nval]
    else:
        pd = sympy.factorint(nval)
        prime_exponent_dicts[nval] = pd
    s0mult = 1
    for pval, expval in pd.items():
        s0mult *= (expval * powval + 1)
    return int(s0mult)
Example #58
0
def smallest_product_sum(k):
    n = 2
    while 1:
        total = 0
        total_cnt = 0
        for factor, cnt in factorint(n).iteritems():
            total += factor * cnt
            total_cnt += cnt
        print n, total_cnt, total, total + (k - total_cnt)
        if total + (k - total_cnt) == n:
            return n
        if n == 8:
            break
        n += 1
Example #59
0
 def is_acceptable_ring_length(n):
     """
     Determine whether `n` is on the form ``2^a * 3^b * 5^c * k``;
     any other prime factors would non-productively be a part of every ring
     length.
     """
     if n % k != 0:
         return False
     else:
         n //= k
         for factor in sympy.factorint(n).keys():
             if factor not in [2, 3, 5, k]:
                 return False
         else:
             return True
Example #60
0
    def apply(self, n, evaluation):
        'FactorInteger[n_]'

        if isinstance(n, Integer):
            factors = sympy.factorint(n.value)
            factors = sorted(six.iteritems(factors))
            return Expression('List', *(Expression('List', factor, exp)
                                        for factor, exp in factors))

        elif isinstance(n, Rational):
            factors, factors_denom = list(map(
                sympy.factorint, n.value.as_numer_denom()))
            for factor, exp in six.iteritems(factors_denom):
                factors[factor] = factors.get(factor, 0) - exp
            factors = sorted(six.iteritems(factors))
            return Expression('List', *(Expression('List', factor, exp)
                                        for factor, exp in factors))
        else:
            return evaluation.message('FactorInteger', 'exact', n)