def is_prime(i):
    import sympy

    if len(sympy.primefactors(i)) == 1 and sympy.primefactors(i)[0] == i:
        return True
    else:
        return False
 def is_prime(i):
     if i in prime_list:
         return True
     if len(sympy.primefactors(i)) == 1 and sympy.primefactors(i)[0] == i:
         prime_list.append(i)
         return True
     else:
         return False
def main():
    import sympy as sp
    i = 2
    while True:
        i = i + 1
        if len(sp.primefactors(i)) == 4:
            i = i + 1
            if len(sp.primefactors(i)) == 4:
                i = i + 1
                if len(sp.primefactors(i)) == 4:
                    i = i + 1
                    if len(sp.primefactors(i)) == 4:
                        print(i - 3)
                        return
Ejemplo n.º 4
0
def ans():
    wanted: int = 4
    i: int = 1
    while True:
        # get skip size
        if len(primefactors(i + 3)) != wanted:
            i += 4
        elif len(primefactors(i + 2)) != wanted:
            i += 3
        elif len(primefactors(i + 1)) != wanted:
            i += 2
        elif len(primefactors(i)) != wanted:
            i += 1
        else:
            return i
Ejemplo n.º 5
0
 def is_founder_tuple(x, y):
     if x == 0 and y == 0:
         return False
     x = effective_for_coprimality(x)
     y = effective_for_coprimality(y)
     if x == y:
         assert x != base
         return is_founder_tuple(x, base)
         # will inherit e.g. (3, 3)%12, from n=4, but not (11, 11)
         # and even though 10 is not prime, n=21 will not inherit (10, 10) from anywhere because 10 and 21 are coprime
     x_factors = set(sympy.primefactors(x))
     y_factors = set(sympy.primefactors(y))
     base_factors = set(sympy.primefactors(base))
     return x_factors & y_factors & base_factors == set(
     )  # they share no prime factors
def entropy_of_a_single_number(n):

    pfactors = primefactors(n)
    smallest_pfactor = pfactors[0]
    h_n = ln(smallest_pfactor)

    return h_n
Ejemplo n.º 7
0
def test(N):
    """Brute-force test function."""

    def is_admissable(L):
        """Checks if the given prime factors make an admissable number."""
        a = L[0]
        for i, p in enumerate(L):
            if i == 0:
                if a != 2:
                    return False
            else:
                if p == nextprime(a):
                    a = p
                else:
                    return False
        return True


    # Throw error if input value is too large.
    if N > 100000:
        raise ValueError("N is too large. Try N < 100000.")

    # Check for admissable numbers
    admissable = set()
    for a in range(2, N):
        if is_admissable(primefactors(a)):
            admissable.add(a)

    # Compute the sum of all distinct pseudo-Fortunate numbers
    distinct_pf = set()
    for a in admissable:
        distinct_pf.add(pseudoFortunate(a))

    return sum(distinct_pf)
Ejemplo n.º 8
0
def prime_factors_cached(num: int):
    """
    wrap sympy's primefactors function with a cache
    :param num: input number
    :return: distinct prime factors list of the num
    """
    return primefactors(num)
Ejemplo n.º 9
0
    def eliminate(rxns, wrt):
        """ Linear combination coefficients for elimination of a substance

        Parameters
        ----------
        rxns : iterable of Equilibrium instances
        wrt : str (substance key)

        Examples
        --------
        >>> e1 = Equilibrium({'Cd+2': 4, 'H2O': 4}, {'Cd4(OH)4+4': 1, 'H+': 4}, 10**-32.5)
        >>> e2 = Equilibrium({'Cd(OH)2(s)': 1}, {'Cd+2': 1, 'OH-': 2}, 10**-14.4)
        >>> Equilibrium.eliminate([e1, e2], 'Cd+2')
        [1, 4]
        >>> print(1*e1 + 4*e2)
        4 Cd(OH)2(s) + 4 H2O = Cd4(OH)4+4 + 4 H+ + 8 OH-; 7.94e-91

        """
        import sympy
        viol = [r.net_stoich([wrt])[0] for r in rxns]
        factors = defaultdict(int)
        for v in viol:
            for f in sympy.primefactors(v):
                factors[f] = max(factors[f], sympy.Abs(v//f))
        rcd = reduce(mul, (k**v for k, v in factors.items()))
        viol[0] *= -1
        return [rcd//v for v in viol]
Ejemplo n.º 10
0
    def eliminate(rxns, wrt):
        """ Linear combination coefficients for elimination of a substance

        Parameters
        ----------
        rxns : iterable of Equilibrium instances
        wrt : str (substance key)

        Examples
        --------
        >>> e1 = Equilibrium({'Cd+2': 4, 'H2O': 4}, {'Cd4(OH)4+4': 1, 'H+': 4}, 10**-32.5)
        >>> e2 = Equilibrium({'Cd(OH)2(s)': 1}, {'Cd+2': 1, 'OH-': 2}, 10**-14.4)
        >>> Equilibrium.eliminate([e1, e2], 'Cd+2')
        [1, 4]
        >>> print(1*e1 + 4*e2)
        4 Cd(OH)2(s) + 4 H2O = Cd4(OH)4+4 + 4 H+ + 8 OH-; 7.94e-91

        """
        import sympy
        viol = [r.net_stoich([wrt])[0] for r in rxns]
        factors = defaultdict(int)
        for v in viol:
            for f in sympy.primefactors(v):
                factors[f] = max(factors[f], sympy.Abs(v//f))
        rcd = reduce(mul, (k**v for k, v in factors.items()))
        viol[0] *= -1
        return [rcd//v for v in viol]
Ejemplo n.º 11
0
def euler47():
    n = 2 * 3 * 5 * 7
    while True:
        if len(primefactors(n)) != 4:
            n += 1
            continue
        elif len(primefactors(n + 1)) != 4:
            n += 2
            continue
        elif len(primefactors(n + 2)) != 4:
            n += 3
            continue
        elif len(primefactors(n + 3)) != 4:
            n += 4
            continue
        return n
Ejemplo n.º 12
0
def first_int(arr):
    f = lambda x: len(primefactors(x))
    for i in range(len(arr) - 3):
        if f(arr[i]) == 4 and f(arr[i + 1]) == 4 and f(arr[i + 2]) == 4 and f(
                arr[i + 3]) == 4:
            return arr[i]
    return False
Ejemplo n.º 13
0
def phi(n):
    f = primefactors(n)
    count = n
    for p in f:
        count *= (1-1/p)
    if isprime(n):
        return round(count - 1)
    return round(count)
Ejemplo n.º 14
0
def consecutiveNumbers(c: int):
    if not 0 < c < 5:
        raise ValueError("Input should be an integer between 0 and 5")
    counter = 0
    while True:
        counter += 1
        if all(len(primefactors(counter + x)) == c for x in range(c)):
            return counter
Ejemplo n.º 15
0
def cum_gcd_count(x):
    primefacts = {n: set(primefactors(n)) for n in trange(1, x + 1)}
    total = 0
    for i in trange(2, x + 1):
        for j in range(1, i):
            # total += gcd(i, j) == 1
            total += len(primefacts[i].intersection(primefacts[j])) == 0
    return total
def prime_producer(a, b):
    import sympy
    n = 0
    while True:
        f = n**2 + a * n + b
        if f <= 0 or len(sympy.primefactors(f)) > 1:
            break
        n = n + 1
    return n
def main(N):
    count = 0
    for i in range(2, N + 1):
        print(i)
        s = i
        for t in sp.primefactors(i):
            s *= (t - 1) / t
        count += int(s)
    print(count)
Ejemplo n.º 18
0
def set_primes(s):
    for composite in sorted(s, reverse=True):
        for prime in reversed(primefactors(composite)):
            if prime not in s.values():
                s[composite] = prime
                break
        if s[composite] == 0:
            raise Exception('no unique prime found for %d' % composite)
    return s
Ejemplo n.º 19
0
 def find_generator(self):  # find random generator for group
     # see free handbook of applied cryptography p163 for a description
     factors = sympy.primefactors(self.primeM1)
     while True:  # there are numerous generators
         candidate = self.rand_int()  # so we'll find in a few tries
         log(f'  candidate {candidate}', verbose=3)
         for factor in factors:
             if 1 == self.pow(candidate, self.primeM1 // factor): break
             else:
                 return candidate
Ejemplo n.º 20
0
 def is_generator(self):
     if self.val == 0:
         return False
     # init phi(n) factorization
     if not Field.__phi_n_prime_factors:
         Field.__phi_n_prime_factors = set(primefactors(Field.__phi_n))
     for factor in Field.__phi_n_prime_factors:
         if factor != Field.__phi_n and self**(n // factor) == Field(1):
             return False
     return True
def p_factor_table(n):
    pfs = sympy.primefactors(n)
    pf_tbl = {}
    for i in pfs:
        pf_tbl[i] = 0
        m = n
        while m % i == 0:
            m = m // i
            pf_tbl[i] = pf_tbl[i] + 1
    return pf_tbl
Ejemplo n.º 22
0
 def find_generator(self):
     # find random generator for group
     factors = sympy.primefactors(self.primeM1)
     while True:  # there are numerous generators
         candidate = self.rand_int()
         # so we'll find in a few tries
         for factor in factors:
             if 1 == self.pow(candidate, self.primeM1 // factor): break
         else:
             return candidate
Ejemplo n.º 23
0
def getStaticEvaluation(aGamePrime, isMaxTurn):
    aGame = copy.deepcopy(aGamePrime)
    score = 0
    lastToken = aGame.lastToken
    unvisitedTokens = aGame.unvisited
    possibleMoves = aGame.possibleMoves

    if len(possibleMoves) == 0:
        score = -1
        if isMaxTurn is False:
            score = 1
        return score

    if lastToken is None:
        return None

    if 1 in unvisitedTokens:
        score = 0

    if lastToken == 1:
        if len(possibleMoves) % 2 == 0:
            score = -0.5
        else:
            score = 0.5

    if sympy.isprime(lastToken) is True:
        primeMultiples = []
        for child in possibleMoves:
            # finding all multiples of the prime number
            if child % lastToken == 0:
                primeMultiples.append(child)

        if len(primeMultiples) % 2 == 0:
            score = -0.7
        else:
            score = 0.7

    if sympy.isprime(lastToken) is False:
        # primefactors() returns prime factors of number in a list, and [-1] returns the last element of that list
        # which is usually the biggest prime from the list
        largestPrime = sympy.primefactors(lastToken)[-1]
        primeMultiples = []
        for child in possibleMoves:
            if child % largestPrime == 0:
                primeMultiples.append(child)

        if len(primeMultiples) % 2 == 0:
            score = -0.6
        else:
            score = 0.6

    if isMaxTurn is False:
        score = -score

    return score
Ejemplo n.º 24
0
def coprimes(n):
    coprime_list = list()
    prime_fact = primefactors(n)
    arr = [(1 - 1 / el) for el in prime_fact]
    num_coprimes = int(np.prod(arr) * n)

    for el in range(1, n):
        if m.gcd(el, n) == 1:
            coprime_list.append(el)

    return num_coprimes, coprime_list
Ejemplo n.º 25
0
    def find_generator(self):  # find random generator for group
        """Find a random generator for the group."""
        factors = sympy.primefactors(self.prime_m1)

        while True:
            candidate = self.rand_int()
            for factor in factors:
                if 1 == self.pow(candidate, self.prime_m1 // factor):
                    break
            else:
                return candidate
Ejemplo n.º 26
0
def numberOfFractions(n):
    pf = primefactors(n)
    length = len(pf)
    suma = n-1
    for i in range(length):
        for j in combinations(pf,i+1):
            product = 1
            for k in j:
                product *= k
            suma += (-1)**(i+1) * (n/product-1)
    return int(suma)
Ejemplo n.º 27
0
def A007947(start: int = 1, limit: int = 20) -> Collection[int]:
    """Largest squarefree number dividing n:
    the squarefree kernel of n, rad(n), radical of n.
    """
    sequence = []
    for i in range(start, start + limit):
        if i < 2:
            sequence.append(1)
        else:
            n = reduce(lambda x, y: x * y, primefactors(i))
            sequence.append(n)

    return sequence
Ejemplo n.º 28
0
def factorization_of_n(n):
    #returns a dictionary of proper prime factorization of n

    da = dict()
    prime_list = sp.primefactors(n)
    prime_list = [int(i) for i in prime_list]
    for i in prime_list:
        counter = 0
        while n % (i**counter) == 0:
            counter += 1
        da[i] = counter - 1

    return da
Ejemplo n.º 29
0
def get_factors():
    l = {}
    for i in range(2, N):
        a = sympy.primefactors(i)
        b = set(a)
        for factor in a:
            b.add(int(i / factor))
        b.add(1)
        # debug_print(f"{i}: {b}")
        l[i] = sum(b)
        # print(a)
    # debug_print(l)
    return l
Ejemplo n.º 30
0
def findIntsWithFactors(numInts, numFactors):
    num = 1
    while True:
        ints = list([num + i for i in range(numInts)])

        count = 0
        for val in ints:
            valFactors = primefactors(val)
            if len(valFactors) == numFactors:
                count += 1
        if count == numInts:
            return ints

        num += 1
Ejemplo n.º 31
0
def primitive_root(p):
    assert syp.isprime(p), "%s is not a prime" % p
    if p == 2:
        return 1
    a = 2
    prime_divisors = syp.primefactors(p - 1)

    def test(a):
        for p_i in prime_divisors:
            if pow(a, (p - 1) // p_i, p) == 1:
                return False
        return True

    while not test(a):
        a += 1

    return a
Ejemplo n.º 32
0
def Rn(n):
    if n in cache.keys():
        return cache[n]
    else:
        r = sym.Symbol("r")
        poly = sym.poly(fn(n, 0.5, r) - 0.5)
        primefactors = sym.primefactors(n)
        for p in primefactors:
            if p != n:
                poly = sym.pexquo(poly, fn(p, 0.5, r) - 0.5)

        print("Expression:", poly)
        print()
        allsols = poly.nroots()
        sols = sym.ConditionSet(r, r > 0, allsols)
        cache[n] = sols
        return sols
Ejemplo n.º 33
0
def main(N):
    m = 0
    b = 0
    bad_set = {20}
    for i in range(2, N + 1):
        if i in bad_set:
            print(i, "is bad.")
            continue
        l = sp.primefactors(i)
        s = 1
        for j in l:
            s *= j / (j - 1)
            h = i
            while h <= N:
                h *= j
                bad_set.add(h)
        print(i, s)
        if m < s:
            m, b = s, i
    print("Max of n/phi(n) is: n =", b, ", n/phi = ", m)
Ejemplo n.º 34
0
def euler_phi_function(n: int, verbose: bool=False):
    prime_factors = sympy.primefactors(n)
    factors_count = dict(Counter(prime_factors))
    step1 = []
    step2 = []
    step3 = []
    phi = 1

    for i in factors_count:
        temp = math.pow(i, factors_count[i]) - math.pow(i,factors_count[i]-1)
        step1.append (f"({i}^{factors_count[i]} - {i}^({factors_count[i]} - 1))")
        step2.append (f"({i}^{factors_count[i]} - {i}^{factors_count[i] - 1})")
        step3.append (f"({temp})")
        phi *= temp
    if verbose: 
        print(f" φ({n}) =",end= " ")
        print(*step1,sep = " X ")
        print(f" φ({n}) =",end= " ")
        print(*step2,sep = " X ")
        print(f" φ({n}) =",end= " ")
        print(*step3,sep = " X ")
    return int(phi)
Ejemplo n.º 35
0
def czt(x, f1, f2, binWidth, fs):
    '''
    n = (f2-f1)/binWidth + 1
    w = - i 2 pi (f2-f1+binWidth)/(n fs)
    a = i 2 pi (f1/fs)
    
    cztoptprep(len(x), n, w, a, nfft) # nfft custom to >len(x)+n-1
    '''
    
    k = int((f2-f1)/binWidth + 1)
    m = len(x)
    nfft = m + k
    foundGoodPrimes = False
    while not foundGoodPrimes:
        nfft = nfft + 1
        if np.max(sympy.primefactors(nfft)) <= 7: # change depending on highest tolerable radix
            foundGoodPrimes = True
    
    kk = np.arange(-m+1,np.max([k-1,m-1])+1)
    kk2 = kk**2.0 / 2.0
    ww = np.exp(-1j * 2 * np.pi * (f2-f1+binWidth)/(k*fs) * kk2)
    chirpfilter = 1 / ww[:k-1+m]
    fv = np.fft.fft( chirpfilter, nfft )
    
    nn = np.arange(m)
    # print(ww[m+nn-1].shape)
    aa = np.exp(1j * 2 * np.pi * f1/fs * -nn) * ww[m+nn-1]
    
    y = x * aa
    fy = np.fft.fft(y, nfft)
    fy = fy * fv
    g = np.fft.ifft(fy)
    
    g = g[m-1:m+k-1] * ww[m-1:m+k-1]
    
    return g
Ejemplo n.º 36
0
def findPrimitive(n):
    s = set()

    # Check if n is prime or not
    if (isPrime(n) == False):
        return -1

    # Find value of Euler Totient function
    # of n. Since n is a prime number, the
    # value of Euler Totient function is n-1
    # as there are n-1 relatively prime numbers.
    phi = n - 1

    # Find prime factors of phi and store in a set
    s = primefactors(phi)

    # Check for every number from 2 to phi
    for r in range(2, phi + 1):

        # Iterate through all prime factors of phi.
        # and check if we found a power with value 1
        flag = False
        for it in s:

            # Check if r^((phi)/primefactors)
            # mod n is 1 or not
            if (power(r, phi // it, n) == 1):
                flag = True
                break

        # If there was no power with value 1.
        if flag == False:
            return r

            # If no primitive root found
    return -1
Ejemplo n.º 37
0
def phi(n):
    phi = n
    for i in primefactors(n):
        phi *= (1-1/i)
    return int(phi)
Ejemplo n.º 38
0
Archivo: 0.py Proyecto: ubuntuh/github
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
import sympy as sy
class MyRange:
    def __init__(self, length):
        self.length = length
        del length
        self.short_length = self.length - 2
        range_ = range(0, 2 ** self.short_length)
        self.iter_ = iter(range_)
    def __iter__(self):
        return self
    def __next__(self):
        i = next(self.iter_)
        str0 = '1{0:0' + str(self.short_length) + 'b}1'
        str1 = str0.format(i)
        int_ = int(str1)
        return int_

for i, n in zip(itertools.count(), MyRange(10)):
    is_prime = sy.isprime(n)
    prime_factors = sy.primefactors(n)
    print('i = {0}, n = {1}, is_prime = {2}, prime_factors = {3}'.format(i, n, is_prime, prime_factors))
Ejemplo n.º 39
0
Author: Spencer Lyon

Project Euler Problem 47
"""
from time import time
start_time = time()

from sympy import primefactors

found = 0
n1 = 1
n2 = 2
n3 = 3
n4 = 4
while found == 0:
    if len(primefactors(n1)) == 4:
        if len(primefactors(n2)) == 4:
            if len(primefactors(n3)) == 4:
                if len(primefactors(n4)) == 4:
                    ans = n1
                    found = 1

    n1 += 1
    n2 += 1
    n3 += 1
    n4 += 1

print("The answer is: %i") % (ans)

running_time = time()
elapsed_time = running_time - start_time
Ejemplo n.º 40
0
from sympy import primefactors

factors = primefactors(600851475143)
print(max(factors))
Ejemplo n.º 41
0
 def consec(nums):
     for n in nums:
         if len(sp.primefactors(n)) != ndistinct:
             return False
     return True
Ejemplo n.º 42
0
'''
Project Euler Problem #3:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?
'''

#Note: Primes are sympy's bitch.

import sympy as sy
print(max(sy.primefactors(600851475143)))
Ejemplo n.º 43
0
from sympy import primefactors

print(primefactors(600851475143)[-1])

# import math
# import time

# def checkprime(a):
#     for i in range(2,math.ceil(math.sqrt(a+0.001))):
#         if a%i == 0:
#             return False
#     return True

# def lprimfactor(a):
#     d = 2
#     lista = []
#     while a > 1:
#         if a%d == 0:
#             lista.append(d)
#             a //= d
#         else:
#             d+=1

#     return lista

#     # for i in range(2,math.ceil(a/2+0.1)):
#     #     if a%i == 0:
#     #        if checkprime(i):
#     #            print(i)
#     # return
Ejemplo n.º 44
0
"""
The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?
"""

from sympy import primefactors
from time import time

n = 600851475143
factors = primefactors(n)
print(factors[-1])
Ejemplo n.º 45
0
import sympy

print(sympy.primefactors(600851475143)[-1])
Ejemplo n.º 46
0
def p_fact(n):
    return (n,len(primefactors(n)))
Ejemplo n.º 47
0
import sympy
print max(sympy.primefactors(600851475143))

Ejemplo n.º 48
0
def Totient(n):
    l = sp.primefactors(n)
    s = 1
    for i in l:
        s *= (i - 1)/i
    return s