示例#1
0
def test_visual_factorint():
    assert type(factorint(42, visual=True)) == Mul
    assert str(factorint(42, visual=True)) == '2**1*3**1*7**1'
    assert factorint(1, visual=True) is S.One
    assert factorint(42**2, visual=True) == Mul(Pow(2, 2, evaluate=False),
    Pow(3, 2, evaluate=False), Pow(7, 2, evaluate=False), evaluate=False)
    assert Pow(-1, 1, evaluate=False) in factorint(-42, visual=True).args
示例#2
0
def test_visual_factorint():
    assert factorint(1, visual=1) == 1
    forty2 = factorint(42, visual=True)
    assert type(forty2) == Mul
    assert str(forty2) == "2**1*3**1*7**1"
    assert factorint(1, visual=True) is S.One
    no = dict(evaluate=False)
    assert factorint(42 ** 2, visual=True) == Mul(Pow(2, 2, **no), Pow(3, 2, **no), Pow(7, 2, **no), **no)
    assert Pow(-1, 1, **no) in factorint(-42, visual=True).args
示例#3
0
    def factors(self, limit=None, verbose=False):
        """A wrapper to factorint which return factors of self that are
        smaller than limit (or cheap to compute)."""
        from sympy.ntheory import factorint

        f = factorint(self.p, limit=limit, verbose=verbose).copy()
        for p, e in factorint(self.q, limit=limit, verbose=verbose).items():
            try: f[p] += -e
            except KeyError: f[p] = -e

        if len(f)>1 and 1 in f: del f[1]
        return f
示例#4
0
文件: galoistools.py 项目: Aang/sympy
def gf_irred_p_rabin(f, p, K):
    """Rabin's polynomial irreducibility test over finite fields. """
    n = gf_degree(f)

    if n <= 1:
        return True

    _, f = gf_monic(f, p, K)

    x = [K.one, K.zero]

    H = h = gf_pow_mod(x, p, f, p, K)

    indices = set([ n//d for d in factorint(n) ])

    for i in xrange(1, n):
        if i in indices:
            g = gf_sub(h, x, p, K)

            if gf_gcd(f, g, p, K) != [K.one]:
                return False

        h = gf_compose_mod(h, H, f, p, K)

    return h == x
示例#5
0
def gf_csolve(f, n):
    """
    To solve f(x) congruent 0 mod(n).

    n is divided into canonical factors and f(x) cong 0 mod(p**e) will be
    solved for each factor. Applying the Chinese Remainder Theorem to the
    results returns the final answers.

    Examples
    ========

    Solve [1, 1, 7] congruent 0 mod(189):

    >>> from sympy.polys.galoistools import gf_csolve
    >>> gf_csolve([1, 1, 7], 189)
    [13, 49, 76, 112, 139, 175]

    References
    ==========

    [1] 'An introduction to the Theory of Numbers' 5th Edition by Ivan Niven,
        Zuckerman and Montgomery.

    """
    from sympy.polys.domains import ZZ

    P = factorint(n)
    X = [csolve_prime(f, p, e) for p, e in P.iteritems()]
    pools = map(tuple, X)
    perms = [[]]
    for pool in pools:
        perms = [x + [y] for x in perms for y in pool]
    dist_factors = [pow(p, e) for p, e in P.iteritems()]
    return sorted([gf_crt(per, dist_factors, ZZ) for per in perms])
示例#6
0
def getFactorListSympy( n ):
    # We shouldn't have to check for lists here, but something isn't right...
    if isinstance( n, list ):
        return [ getFactorListSympy( i ) for i in n ]

    from sympy.ntheory import factorint

    return getExpandedFactorListSympy( factorint( n ) )
示例#7
0
def dup_zz_cyclotomic_poly(n, K):
    """Efficiently generate n-th cyclotomic polnomial. """
    h = [K.one,-K.one]

    for p, k in factorint(n).iteritems():
        h = dup_quo(dup_inflate(h, p, K), h, K)
        h = dup_inflate(h, p**(k-1), K)

    return h
def main():
    i = 1
    while True:
        # nth triangular number is n*(n+1) / 2
        tri = (i*(i+1))/2
        if count_factors(factorint(tri)) >= 1500:
            print tri
            break
        i += 1
def mobius(n):
    dict = factorint(n)
    factor_count = list(dict.values())
    for i in factor_count:
        if i != 1:
            return 0
    if n == 1:
        return 1
    else:
        return (-1) ** (len(factor_count))
示例#10
0
def _dup_cyclotomic_decompose(n, K):
    H = [[K.one,-K.one]]

    for p, k in factorint(n).iteritems():
        Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ]
        H.extend(Q)

        for i in xrange(1, k):
            Q = [ dup_inflate(q, p, K) for q in Q ]
            H.extend(Q)

    return H
示例#11
0
def solution(q):
    c = 0
    for p in count(start=1, step=1):
        if len(factorint(p)) == q:
            c += 1
            if c == 1:
                last = p
        else:
            c = 0

        if c == q:
            return last
示例#12
0
def get_sq_free_int(limit: int):
    """Get the none-sqare factors number"""
    result = []

    for i in range(1, limit + 1):
        factors = factorint(i)

        if any(value > 1 for value in factors.values()):
            continue

        result.append(str(i))

    return ", ".join(result)
示例#13
0
def dup_zz_irreducible_p(f, K):
    """Test irreducibility using Eisenstein's criterion. """
    lc = dup_LC(f, K)
    tc = dup_TC(f, K)

    e_fc = dup_content(f[1:], K)

    if e_fc:
        e_ff = factorint(int(e_fc))

        for p in e_ff.iterkeys():
            if (lc % p) and (tc % p**2):
                return True
def generator_Zp(p):
  factorizare = factorint(p - 1)
  N = p - 1
  gasit = False
  while not gasit:
    a = random.randint(1, N)
    for factor in factorizare.keys():
      b = pow(a,  N // factor, p)
      if b == 1:
        break
    else:
      gasit = True
  return a
示例#15
0
文件: sym.py 项目: ickc/dautil-py
def fft_nice(n):
    '''Given integer ``n``, check if it is at the best handling
    size fot FFTW according to
    http://www.fftw.org/fftw2_doc/fftw_3.html
    '''
    factors = factorint(n)
    max_prime = max(factors)
    if max_prime <= 7:
        return True
    elif max_prime <= 13:
        if factors.get(11, 0) + factors.get(13, 0) <= 1:
            return True
    return False
示例#16
0
def divisible_triangle_number(divisors):
    n = 1
    while True:
        triangle = (n * (n + 1)) // 2  # calculate the next triangle number
        prime_factors_tri = factorint(
            triangle)  # find prime factors of the triangle number
        total_divs = 1
        for i in prime_factors_tri:  # let's say 6 = 2 * 3 = 2^1 + 3^1 so the number of divisors of 6 is (1+1)*(1+1)
            total_divs *= prime_factors_tri[
                i] + 1  # add one to the prime factors exponents and then multiply them
        if total_divs > divisors:  # compare the total_divs of the current tirangle and see it's greater than the given divisors
            return triangle
        n += 1
def get_prime(numOfBits: int, safe=False):
    if safe == False:
        return get_primes(numOfBits, 1)[0]
    else:
        iter = 0
        while 1 or iter < 10**10:
            p = get_primes(numOfBits, 1)[0]
            t = factorint(p - 1)
            if len(t) == 2:
                if 2 in t.keys() and t[2] == 1:
                    return p
            iter += 1
        print("No safe prime found in max iterations!")
示例#18
0
    def gen_relatively_prime(f, name):
        factors = set(factorint(f).keys())
        possible_factors = [
            factor for factor in GenBBS.big + GenBBS.small
            if factor not in factors
        ]

        x = 1
        for idx in range(2):
            x *= random.choice(possible_factors)

        Gen.print_genned_param(name, x)
        return x
示例#19
0
def dup_zz_irreducible_p(f, K):
    """Test irreducibility using Eisenstein's criterion. """
    lc = dup_LC(f, K)
    tc = dup_TC(f, K)

    e_fc = dup_content(f[1:], K)

    if e_fc:
        e_ff = factorint(int(e_fc))

        for p in e_ff.keys():
            if (lc % p) and (tc % p**2):
                return True
示例#20
0
def test_factor():
    assert trial(1) == []
    assert trial(2) == [(2,1)]
    assert trial(3) == [(3,1)]
    assert trial(4) == [(2,2)]
    assert trial(5) == [(5,1)]
    assert trial(128) == [(2,7)]
    assert trial(720) == [(2,4), (3,2), (5,1)]
    assert factorint(123456) == [(2, 6), (3, 1), (643, 1)]
    assert primefactors(123456) == [2, 3, 643]
    assert factorint(-16) == [(-1, 1), (2, 4)]
    assert factorint(2**(2**6) + 1) == [(274177, 1), (67280421310721, 1)]
    assert factorint(5951757) == [(3, 1), (7, 1), (29, 2), (337, 1)]
    assert factorint(64015937) == [(7993, 1), (8009, 1)]
    assert divisors(1) == [1]
    assert divisors(2) == [1, 2]
    assert divisors(3) == [1, 3]
    assert divisors(10) == [1, 2, 5, 10]
    assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
    assert divisors(101) == [1, 101]
    assert pollard_rho(2**64+1, max_iters=1, seed=1) == 274177
    assert pollard_rho(19) is None
示例#21
0
def find_larger_prime(value, decomp):
    if value == 1:
        assert not decomp
        return

    missing_decomp = []
    for w, n in decomp:
        w_val = get_known_word(w)
        if w_val is not None:
            print("\033[37mRemoving %d**%d from %d\033[m" % (w_val, n, value))
            assert value % (w_val**n) == 0
            value = value // (w_val**n)
        else:
            missing_decomp.append((w, n))

    if value == 1:
        assert not missing_decomp
        return

    value_d = factorint(value)
    assert len(value_d) == len(missing_decomp)

    if len(missing_decomp) == 1:
        # Single decomp
        the_prime = list(value_d.keys())[0]
        assert value_d[the_prime] == missing_decomp[0][
            1], "Mismatching single-decomp for %r vs %r" % (value_d,
                                                            missing_decomp)
        add_known(missing_decomp[0][0], the_prime)
        return

    if sorted(set(value_d.values())) == [1]:
        print("Finding larger prime from decomp %d=%r from %r" %
              (value, value_d, missing_decomp))
        larger_prime = max(value_d.keys())
        puiss = int(math.log(P) / math.log(larger_prime)) + 1
        if not all(
            (x**puiss) < P for x in value_d.keys() if x != larger_prime):
            print("... skipping because not real puiss")
        else:
            assert (larger_prime**puiss) > P
            for w, n in missing_decomp:
                decomp_w = send_words(((w, puiss), ))
                if len(decomp_w) != 1:
                    print("... found %r^%d = %r" % (w, puiss, decomp_w))
                    add_known(w, larger_prime)
                    assert value % (larger_prime**n) == 0
                    find_larger_prime(value, missing_decomp)
                    #global_queue.append((pow(larger_prime, puiss, P), decomp_w))
                    return
            print("NO DECOMP FOUND")
示例#22
0
def mobius(n):
    primeNos = 0
    if n < 1:
        return "Invalid"
    if n == 1:
        return 1
    for prime, exp in factorint(n).items():
        if exp >= 2:
            return 0
        primeNos = primeNos + 1
    if primeNos % 2 == 0:
        return 1
    else:
        return -1
示例#23
0
def partB(inputText):
    _, busList = inputText.split()
    busList = enumerate(busList.split(","))
    busList = [(busPos%int(busN), int(busN)) for busPos, busN in busList if busN != "x"]

    #unzip
    busN = [i[1] for i in busList]
    busPos = [i[0] for i in busList]

    #confirm busN are coprime
    from sympy.ntheory import factorint
    factorized = [factorint(i) for i in busN]
    print(busN, busPos, factorized)
    return None
def generate_samples(max_n):
    #x is our modulus
    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)
        print("n: {} self squares: {}".format(x, self_squares))
示例#25
0
def _dup_cyclotomic_decompose(n, K):
    from sympy.ntheory import factorint

    H = [[K.one, -K.one]]

    for p, k in factorint(n).items():
        Q = [ dup_quo(dup_inflate(h, p, K), h, K) for h in H ]
        H.extend(Q)

        for i in range(1, k):
            Q = [ dup_inflate(q, p, K) for q in Q ]
            H.extend(Q)

    return H
示例#26
0
def factors():
    answer = []
    for num in range(134000, 135000):
        lst =[]
        test = factorint(num)
        for i in test.keys():
            lst.append(i)
        if len(lst) == 4:
            answer.append(num)
    print(answer)
    for j in answer:
        if (j+1) in answer:
            if (j+2) in answer:
                if (j+3) in answer:
                    print(j)
示例#27
0
def naive_search(M, N, J):
    p = np.array([0] * N)
    p[0], p[-1] = 1, 1
    jamcoins = []
    proofs = []
    for i in range(0, 2**(N - 2)):
        p_ = [int(a) for a in str(bin(i))[2:]]
        p[-(len(p_) + 1):-1] = p_
        c = [sum([a * b for a, b in zip(p, D)]) for D in M]
        if all([not isprime(a) for a in c]):
            jamcoins.append("".join([str(a) for a in p]))
            proofs.append([min(list(factorint(a).keys())) for a in c])
            if len(jamcoins) == J:
                break
    return jamcoins, proofs
示例#28
0
def calcGeneratorInefficient(p):
    primeFactors = factorint(p - 1)
    generators = []

    for g in range(2, p - 1):
        results = []
        for x in primeFactors:
            result = g**((p - 1) / x) % p
            if result == 1:
                break
            results.append(result)
        # print g, results
        generators.append(g)

    return generators
示例#29
0
def compute():
    user, session = get_user(request)
    if user is None:
        return redirect(url_for('login'))

    try:
        number = int(request.form['number'])
    except:
        return render_template("index.html",
                               user=user,
                               number_result='Incorrect Input')

    return render_template("index.html",
                           user=user,
                           number_result=factorint(number))
示例#30
0
def d(n):
    global d_memo

    if n in d_memo:
        return d_memo.get(n)

    factors = factorint(n)

    d_sum = 1
    for p, m in factors.items():
        d_sum *= ((p**(m + 1) - 1) // (p - 1))

    d_sum -= n
    d_memo[n] = d_sum
    return d_sum
示例#31
0
def return_parents(n):
    factor_dict = factorint(n)
    factors = []
    for i in factor_dict:
        factors.append(str(i))
    parents_iter = []
    for parent in itertools.permutations(factors):
        parents_iter.append(parent)
    parents = []
    for parent in parents_iter:
        result = ""
        for element in parent:
            result += element
        parents.append(int(result))
    return parents
示例#32
0
def generate_with_factorization(n):
    rnd = randint(int(math.e**n), int(2 * math.e**n))
    log_rnd = math.log(rnd)

    xs = []
    factorization = factorint(rnd)

    for fact in factorization:
        for i in range(factorization[fact]):
            xs.append(math.log(fact) / log_rnd)

    print("rnd =", rnd, "\nlen_fact =", len(xs), "\nfactorization =",
          factorization)

    return list(reversed(xs))
示例#33
0
def findAVulnerablePrime(bitSize):
    generator = 65537
    m = nt.primorial(prime_default(bitSize), False)

    max_order = nt.totient(m)
    max_order_factors = nt.factorint(max_order)

    order = element_order_general(generator, m, max_order, max_order_factors)
    order_factors = nt.factorint(order)

    power_range = [0, order - 1]
    min_prime = g.bit_set(
        g.bit_set(g.mpz(0), bitSize // 2 - 1), bitSize // 2 - 2
    )  # g.add(pow(g.mpz(2), (length / 2 - 1)), pow(g.mpz(2), (length / 2 - 2)))
    max_prime = g.bit_set(
        min_prime, bitSize // 2 - 4
    )  # g.sub(g.add(min_prime, pow(g.mpz(2), (length / 2 - 4))), g.mpz(1))
    multiple_range = [g.f_div(min_prime, m), g.c_div(max_prime, m)]

    random_state = g.random_state(random.SystemRandom().randint(0, 2**256))

    return random_prime(random_state,
                        nt.primorial(prime_default(bitSize), False), generator,
                        power_range, multiple_range)
示例#34
0
def isItJamCoin(number):
    binnumber = bin(number)[2:]
    divisors = []
    for i in range(2, 11):
        current = int(binnumber, i)
        if isprime(current):
            return None

        divisor = min(factorint(current).keys())
        if divisor == current:
            return None

        divisors.append(divisor)

    return divisors
示例#35
0
def generate_key():
    p = random.choice(big_primes)
    q = list(sorted(factorint(p - 1)))[-1]

    a = q - 1
    while pow(a, q, p) != 1:
        a -= 1

    x = random.randint(1, (p - 1) // 2)
    y = pow(a, x, p)

    with open('key.txt', 'w') as f:
        f.write('{}\n{}\n{}\n{}\n{}'.format(p, q, a, x, y))

    return p, q, a, x, y
def generate_solns(max_n, interval=1, offset=0, target_dict=None):

    #added fillers so solns[n] gives soln mod n
    D = dict()

    #handling cases less than interval (tricky since we are avoiding 0,1,2)
    start_val = 0
    while (start_val * interval + offset < 3):
        start_val += 1

    #x is our modulus
    #only looking at offset values
    x = start_val * interval + offset
    while x < max_n + 1:

        #factoring to find invertible numbers
        primes = factorint(x)
        prime_len = len(primes)
        if prime_len == 1 and 2 not in primes:
            D[x] = 1
            x += interval
            continue
        elif prime_len == 2 and (2 in primes and primes[2] == 1):
            D[x] = 1
            x += interval
            continue

        #checking all the numbers where gcd(x,y)=1
        #does not check n-1 aka y=1 (trivial case)
        solved = False
        sub_bound = int(sqrt(x) + 1)
        for y in range(sub_bound, int(x / 2) + 1):
            #start at the largest value less than x-1 since we're looking for max
            X = x - y
            #checks that no prime divisors of our modulus (x) divide our number y
            #then checks if y is its own inverse
            if all(X % p != 0 for p in primes.keys()) and (X * X) % x == 1:
                D[x] = X
                solved = True
                break
        if not solved:
            D[x] = 1
        x += interval

    if target_dict == None:
        return D
    else:
        target_dict.update(D)
示例#37
0
def test_decomp_8():
    # This time we consider various cubics, and try factoring all primes
    # dividing the index.
    cases = (
        x**3 + 3 * x**2 - 4 * x + 4,
        x**3 + 3 * x**2 + 3 * x - 3,
        x**3 + 5 * x**2 - x + 3,
        x**3 + 5 * x**2 - 5 * x - 5,
        x**3 + 3 * x**2 + 5,
        x**3 + 6 * x**2 + 3 * x - 1,
        x**3 + 6 * x**2 + 4,
        x**3 + 7 * x**2 + 7 * x - 7,
        x**3 + 7 * x**2 - x + 5,
        x**3 + 7 * x**2 - 5 * x + 5,
        x**3 + 4 * x**2 - 3 * x + 7,
        x**3 + 8 * x**2 + 5 * x - 1,
        x**3 + 8 * x**2 - 2 * x + 6,
        x**3 + 6 * x**2 - 3 * x + 8,
        x**3 + 9 * x**2 + 6 * x - 8,
        x**3 + 15 * x**2 - 9 * x + 13,
    )

    def display(T, p, radical, P, I, J):
        """Useful for inspection, when running test manually."""
        print('=' * 20)
        print(T, p, radical)
        for Pi in P:
            print(f'  ({Pi!r})')
        print("I: ", I)
        print("J: ", J)
        print(f'Equal: {I == J}')

    inspect = False
    for g in cases:
        T = Poly(g)
        rad = {}
        ZK, dK = round_two(T, radicals=rad)
        dT = T.discriminant()
        f_squared = dT // dK
        F = factorint(f_squared)
        for p in F:
            radical = rad.get(p)
            P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=radical)
            I = prod(Pi**Pi.e for Pi in P)
            J = p * ZK
            if inspect:
                display(T, p, radical, P, I, J)
            assert I == J
示例#38
0
    def _gen_relatively_prime(f):
        factors = set(factorint(f).keys())
        possible_factors = [
            factor for factor in GenRSA.big + GenRSA.small
            if factor < f and factor not in factors
        ]
        if not possible_factors:
            return f - 1

        e = 1
        while e < f:
            next_prime = random.choice(possible_factors)
            if next_prime * e > f:
                break
            e *= next_prime
        return e
def multipliers(n):
    """Разложение на множители.

    Параметры:
    n : int
        Целое число для факторизации.

    Выходные данные:
    str: string
        Строка разложения на множители.
    """
    mult = factorint(n)  # Получение словаря простых множителей числа n.
    l = []
    for key in mult:
        l.append(str(key) + "*" + str(mult[key]))
    return (str(n) + " = " + " + ".join(l))
示例#40
0
def residue_system(n, reduced=False, mod=True):
    """
    @type n: integer > 1
    @type reduced: bool
    @param reduced: return a reduced residue system modulo n or
                    a complete residue system modulo n
    @type mod: bool
    @param mod: use mod when generate final list or not
    @rtype: list

    @return: a residue system modulo n
    """
    assert isinstance(n, int) and n > 1

    if n == 2:
        return [1] if reduced else [0, 1]

    n_fact = factorint(n)

    # if len(n_fact) == 1:
    #     if reduced:
    #         return rrs_of_prime_power(
    #             *list(n_fact.items())[0])
    #     else:
    #         return list(range(n))

    m_list = [pow(*e) for e in n_fact.items()]
    M_list = [n//x for x in m_list]

    if reduced:
        vec = [rrs_of_prime_power(*e)
               for e in n_fact.items()]
    else:
        vec = [list(range(x)) for x in m_list]

    vec = [[x*s for x in l] for l, s in zip(vec, M_list)]

    if mod:
        res = reduce(lambda l1, l2: [(x+y) % n for x in l1 for y in l2],
                     vec)
    else:
        res = reduce(lambda l1, l2: [x+y for x in l1 for y in l2],
                     vec)

    res.sort()

    return res
def euler05(n):
    # Evenly divisible by all numbers from 1-20
    d = {}
    i = Sieve(n+1)
    p = i.prime_list()
    for i in p:
        d[i] = 1

    for j in range(4, n+1):
        f = factorint(j)
        for i in f.keys():
            if f[i] > d[i]:
                d[i] = f[i]
    counter = 1
    for i in d.keys():
        counter = counter * i**d[i]
    print(counter)
示例#42
0
def __cols_rows(figures):
    if figures == 1:
        return 1, 1
    factors = nt.factorint(figures)
    expand = [[v] * count for v, count in factors.items()]
    expand = [i for sub in expand for i in sub]
    cols = 1
    rows = 1
    for f in reversed(expand):
        if rows < cols:
            rows *= f
        else:
            cols *= f
    if cols / rows > 2:
        cols = math.ceil(math.sqrt(figures))
        rows = math.ceil(figures / cols)
    return cols, rows
示例#43
0
def crackRsaPrivateKey(e, n):
    """Given an RSA public key, return the private exponent."""
    factorsOfN = factorint(n)

    # since n is the product of two primes, we know its only factors are those two primes
    # if this is not the case, n is invalid (i.e., not the product of two primes)
    factorsAreValid = len(factorsOfN) == 2 and all(multiplicity == 1 for multiplicity in factorsOfN.values())
    if (not factorsAreValid):
        raise Exception(f"{n} is not a valid n value.")

    factorsList = list(factorsOfN)
    p = factorsList[0]
    q = factorsList[1]

    phi = (p - 1) * (q - 1)
    d = inverse_mod(e, phi)
    return d
示例#44
0
def smallest_number_divisible(start, stop):

    # Extract all common factors
    factors = dict()
    for i in range(start, stop + 1):
        if i == 0:
            continue
        for prime, amount in factorint(i).items():
            prime = abs(prime)
            factors[prime] = max(amount, factors.get(prime, 0))

    # Multiply them together
    answer = 1
    for factor, amount in factors.items():
        answer *= (factor**amount)

    return answer
示例#45
0
def gf_irred_p_rabin(f, p, K):
    """
    Rabin's polynomial irreducibility test over finite fields.

    Examples
    ========

    >>> from sympy.polys.domains import ZZ
    >>> from sympy.polys.galoistools import gf_irred_p_rabin

    >>> gf_irred_p_rabin(ZZ.map([1, 4, 2, 2, 3, 2, 4, 1, 4, 0, 4]), 5, ZZ)
    True
    >>> gf_irred_p_rabin(ZZ.map([3, 2, 4]), 5, ZZ)
    False

    """
    n = gf_degree(f)

    if n <= 1:
        return True

    _, f = gf_monic(f, p, K)

    x = [K.one, K.zero]

    H = h = gf_pow_mod(x, p, f, p, K)

    indices = set([n // d for d in factorint(n)])

    for i in xrange(1, n):
        if i in indices:
            g = gf_sub(h, x, p, K)

            if gf_gcd(f, g, p, K) != [K.one]:
                return False

        h = gf_compose_mod(h, H, f, p, K)

    return h == x
示例#46
0
def divisor_sum(n):
	r = 1
	for k,v in factorint(n).iteritems():
		r *= powsum(k, v)

	return r
示例#47
0
def bestFFTlength(n):
    while max(factorint(n)) >= FACTOR_LIMIT:
        n -= 1
    return n
@author VegasAce
last modified 11/9/15
'''
import sympy, re, time
from sympy.ntheory import factorint

startTime = time.time()
primeFactors = []
stringFactors = ''
factors = {}
total = 1

 # get the prime factors for each number 1-20
for num in xrange(1,21,1):
     primeFactors.append(factorint(num))

# concatenate those to a string
for num in xrange(0,len(primeFactors),1):
    stringFactors += (str(primeFactors[num]))

# remove all characters but the numbers
stringFactors = re.findall("\d+",stringFactors)

# add the number of factors to a corresponding dictionary
# by key of the factor
for num in xrange(0,len(stringFactors)-1,2):
    if int(stringFactors[num]) in factors.keys():
        if factors.get(int(stringFactors[num])) > int(stringFactors[num+1]):
            continue
        else:
def prime_factors(n):
    dict = factorint(n)
    return dict
示例#50
0
def prime_factors(num):
    primes = factorint(num)
    return sorted(list(ii for k in primes for ii in repeat(k, primes[k])))
示例#51
0
def factors_count(number):
    return sum(factorint(number).values())
    return 0
示例#52
0
def test_factorint():
    assert primefactors(123456) == [2, 3, 643]
    assert factorint(0) == {0: 1}
    assert factorint(1) == {}
    assert factorint(-1) == {-1: 1}
    assert factorint(-2) == {-1: 1, 2: 1}
    assert factorint(-16) == {-1: 1, 2: 4}
    assert factorint(2) == {2: 1}
    assert factorint(126) == {2: 1, 3: 2, 7: 1}
    assert factorint(123456) == {2: 6, 3: 1, 643: 1}
    assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
    assert factorint(64015937) == {7993: 1, 8009: 1}
    assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
    assert multiproduct(factorint(fac(200))) == fac(200)
    for b, e in factorint(fac(150)).items():
        assert e == fac_multiplicity(150, b)
    assert factorint(103005006059**7) == {103005006059: 7}
    assert factorint(31337**191) == {31337: 191}
    assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
        {2: 1000, 3: 500, 257: 127, 383: 60}
    assert len(factorint(fac(10000))) == 1229
    assert factorint(12932983746293756928584532764589230) == \
        {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
    assert factorint(727719592270351) == {727719592270351: 1}
    assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
    for n in range(60000):
        assert multiproduct(factorint(n)) == n
    assert pollard_rho(2**64 + 1, seed=1) == 274177
    assert pollard_rho(19, seed=1) is None
    assert factorint(3, limit=2) == {3: 1}
    assert factorint(12345) == {3: 1, 5: 1, 823: 1}
    assert factorint(
        12345, limit=3) == {4115: 1, 3: 1}  # the 5 is greater than the limit
    assert factorint(1, limit=1) == {}
    assert factorint(0, 3) == {0: 1}
    assert factorint(12, limit=1) == {12: 1}
    assert factorint(30, limit=2) == {2: 1, 15: 1}
    assert factorint(16, limit=2) == {2: 4}
    assert factorint(124, limit=3) == {2: 2, 31: 1}
    assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
    p1 = nextprime(2**32)
    p2 = nextprime(2**16)
    p3 = nextprime(p2)
    assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
    assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
    assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
    assert factorint(primorial(17) + 1, use_pm1=0) == \
        {long(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
    # when prime b is closer than approx sqrt(8*p) to prime p then they are
    # "close" and have a trivial factorization
    a = nextprime(2**2**8)  # 78 digits
    b = nextprime(a + 2**2**4)
    assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))

    raises(ValueError, lambda: pollard_rho(4))
    raises(ValueError, lambda: pollard_pm1(3))
    raises(ValueError, lambda: pollard_pm1(10, B=2))
    # verbose coverage
    n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
    assert 'with primes' in capture(lambda: factorint(n, verbose=1))
    capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))

    n = nextprime(2**17)
    capture(lambda: factorint(n**3, verbose=1))  # perfect power termination
    capture(lambda: factorint(2*n, verbose=1))  # factoring complete msg

    # exceed 1st
    n = nextprime(2**17)
    n *= nextprime(n)
    assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
    n *= nextprime(n)
    assert len(factorint(n)) == 3
    assert len(factorint(n, limit=p1)) == 3
    n *= nextprime(2*n)
    # exceed 2nd
    assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
    assert capture(
        lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
    # non-prime pm1 result
    n = nextprime(8069)
    n *= nextprime(2*n)*nextprime(2*n, 2)
    capture(lambda: factorint(n, verbose=1))  # non-prime pm1 result
    # factor fermat composite
    p1 = nextprime(2**17)
    p2 = nextprime(2*p1)
    assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
    # Test for non integer input
    raises(ValueError, lambda: factorint(4.5))
示例#53
0
def phi2(n):
    value = n
    for prime, exp in factorint(n).items():
        value = value * (1 - prime ** -1)
    return int(value)
示例#54
0
def test_factorint():
    assert sorted(factorint(123456).items()) == [(2, 6), (3, 1), (643, 1)]
    assert primefactors(123456) == [2, 3, 643]
    assert factorint(-16) == {-1:1, 2:4}
    assert factorint(2**(2**6) + 1) == {274177:1, 67280421310721:1}
    assert factorint(5951757) == {3:1, 7:1, 29:2, 337:1}
    assert factorint(64015937) == {7993:1, 8009:1}
    assert divisors(1) == [1]
    assert divisors(2) == [1, 2]
    assert divisors(3) == [1, 3]
    assert divisors(10) == [1, 2, 5, 10]
    assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
    assert divisors(101) == [1, 101]
    assert factorint(0) == {0:1}
    assert factorint(1) == {}
    assert factorint(-1) == {-1:1}
    assert factorint(-2) == {-1:1, 2:1}
    assert factorint(-16) == {-1:1, 2:4}
    assert factorint(2) == {2:1}
    assert factorint(126) == {2:1, 3:2, 7:1}
    assert factorint(123456) == {2:6, 3:1, 643:1}
    assert factorint(5951757) == {3:1, 7:1, 29:2, 337:1}
    assert factorint(64015937) == {7993:1, 8009:1}
    assert factorint(2**(2**6) + 1) == {274177:1, 67280421310721:1}
    assert multiproduct(factorint(fac(200))) == fac(200)
    for b, e in factorint(fac(150)).items():
        assert e == fac_multiplicity(150, b)
    assert factorint(103005006059**7) == {103005006059:7}
    assert factorint(31337**191) == {31337:191}
    assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
        {2:1000, 3:500, 257:127, 383:60}
    assert len(factorint(fac(10000))) == 1229
    assert factorint(12932983746293756928584532764589230) == \
        {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
    assert factorint(727719592270351) == {727719592270351:1}
    assert factorint(2**64+1, use_trial=False) == factorint(2**64+1)
    for n in range(60000):
        assert multiproduct(factorint(n)) == n
    assert pollard_rho(2**64+1, seed=1) == 274177
    assert pollard_rho(19, seed=1) is None
    assert factorint(3,2) == {3: 1}
    assert factorint(12345) == {3: 1, 5: 1, 823: 1}
    assert factorint(12345, 3) == {12345: 1} # there are no factors less than 3
示例#55
0
def test_issue_4356():
    assert factorint(1030903) == {53: 2, 367: 1}
示例#56
0
def factors(n):    
    return factorint(n)
示例#57
0
def test_issue1257():
    assert factorint(1030903) == {53: 2, 367: 1}
def count_factors(m):
    prime_fact = factorint(m)
    num = 1
    for k in prime_fact:
        num *= prime_fact[k]+1
    return num