Esempio n. 1
0
def length4(n):
    if n in table:
        return table[n]
    else:
        res = len(primefactors(n)) == 4
        table[n] = res
        return res
Esempio n. 2
0
def generatorp(p):
    """Return a generator for the cyclic group multiplication modulo p.
    Also called a primitive root of p.

    Args:
        p (int): a prime number

    Raises:
        RuntimeError: when p is not a prime

    Returns:
        int: the generator
    """
    if not isprime(p):
        raise RuntimeError(str(p) + " is not prime")

    primef = np.array(primefactors(p - 1), dtype="int")
    g = 2
    i = 1
    while i <= np.size(primef):
        if 1 == pow(int(g), int((p - 1) / primef[i - 1]), int(p)):
            g = g + 1
            i = 0
        i = i + 1
    return g
Esempio n. 3
0
def OrderTitik(Periode, P):
    Inf = P - P
    faktor = primefactors(Periode)
    for i in faktor:
        if (Periode // i) * P == Inf:
            return OrderTitik(Periode // i, P)
    return Periode
Esempio n. 4
0
 def convert_to_vts(self, outdir='.', Radius=1., name='basin'):
     from tvtk.api import tvtk, write_data
     from sympy.ntheory import primefactors
     lonArr = np.array([])
     latArr = np.array([])
     for geopolygon in self.geopolygons:
         lonArr = np.append(lonArr, geopolygon.lonArr)
         latArr = np.append(latArr, geopolygon.latArr)
     theta = (90. - latArr) / 180. * np.pi
     phi = lonArr / 180. * np.pi
     x = Radius * np.sin(theta) * np.cos(phi)
     y = Radius * np.sin(theta) * np.sin(phi)
     z = Radius * np.cos(theta)
     pts = np.empty(z.shape + (3, ), dtype=float)
     pts[..., 0] = x
     pts[..., 1] = y
     pts[..., 2] = z
     least_prime = primefactors(x.size)[0]
     dims = (x.size / least_prime, least_prime, 1)
     sgrid = tvtk.StructuredGrid(dimensions=dims, points=pts)
     sgrid.point_data.scalars = (np.ones(x.size)).ravel(order='F')
     sgrid.point_data.scalars.name = name
     outfname = outdir + '/' + name + '.vts'
     write_data(sgrid, outfname)
     return
Esempio n. 5
0
def verify_condition_2(m, a):
    prime_factors = primefactors(int(m / 2))
    for prime_factor in prime_factors:
        if (a - 1) % prime_factor != 0:
            print('Falla cond. 2:\n{} es primo\
            y divide a m={} pero no a (a-1)={}'.format(prime_factor, m, a - 1))
            return False
    return True
Esempio n. 6
0
def A001221(n: int) -> int:
    """omage(n).

    Number of distinct primes dividing n.
    """
    from sympy.ntheory import primefactors

    return len(primefactors(n))
Esempio n. 7
0
File: oeis.py Progetto: theo199/oeis
def A001221() -> Iterator[int]:
    """omage(n).

    Number of distinct primes dividing n.
    """
    from sympy.ntheory import primefactors

    for n in count(1):
        yield len(primefactors(n))
Esempio n. 8
0
def factorsOfNumbers(num1):
    print("\nHere are the factors of your number: ", divisors(num1))
    print("Your number has", divisor_count(num1), "factors within it")
    if divisor_count(num1) == 2:
        print("Your number is a prime number.")
    else:
        print("Your number is a composite number.")
    print()
    print("The prime factors of your number are", primefactors(num1))
    print("A number’s prime factors are the set of prime numbers (including repeats) that equal that number when multiplied together.")
Esempio n. 9
0
def A007947(i: int) -> int:
    """Largest squarefree number dividing n.

    The squarefree kernel of n, rad(n), radical of n.
    """
    from sympy.ntheory import primefactors

    if i < 2:
        return 1
    return reduce(lambda x, y: x * y, primefactors(i))
Esempio n. 10
0
def main():
    lastfew = []
    for i in range(2, 2**32):
        factors = primefactors(i)
        if len(factors) == 4:
            lastfew.append(i)
        else:
            lastfew = []
        if len(lastfew) == 4:
            print(lastfew[0])
            return
Esempio n. 11
0
def calc_phi(n):
    factors = ntheory.primefactors(n)
    phi = n
    for product_size in xrange(1, len(factors) + 1):
        for comb in itertools.combinations(factors, product_size):
            composite = reduce(lambda a, b: a * b, comb)
            if product_size % 2 == 1:
                phi -= n / composite
            else:
                phi += n / composite
    return phi
Esempio n. 12
0
def calc_phi(n):
    factors = ntheory.primefactors(n)
    phi = (n / 2 if n % 2 != 0 else n / 2 - 1) - (n / 3)
    for product_size in xrange(1, len(factors) + 1):
        for comb in itertools.combinations(factors, product_size):
            composite = reduce(lambda a, b: a * b, comb)
            multiples = (n / 2 if n % 2 != 0 else n / 2 - 1) / composite - (n / 3) / composite
            if product_size % 2 == 1:
                phi -= multiples
            else:
                phi += multiples
    return phi
Esempio n. 13
0
def A007947(start: int = 0) -> Iterator[int]:
    """Largest squarefree number dividing n:
    the squarefree kernel of n, rad(n), radical of n.
    """
    from sympy.ntheory import primefactors

    start += 1
    for i in count(start):
        if i < 2:
            yield 1
        else:
            yield reduce(lambda x, y: x * y, primefactors(i))
Esempio n. 14
0
 def is_semi_prime_number(self, number: int) -> bool:
     """
     Checks if a number is semi prime. A semi prime number is the product of two prime numbers.
     :param number: The number to check.
     :return: Whether it is or not.
     """
     if number >= 1:
         prime_factors = list(primefactors(number))
         if len(prime_factors) == 2:
             if prime_factors[0] * prime_factors[1] == number:
                 return True
     return False
Esempio n. 15
0
def brute_force():
    total = 0
    for n in range(1, LIMIT):
        for prime in primes:
            if n % prime**2 == 0:
                break
        else:
            factors[len(primefactors(n))] += 1
            #sys.stderr.write(str(n) + ' | ' + str(factorint(n)) + '\n')
            #sys.stderr.write(str(n) + '\n')
            total += 1
    return total
Esempio n. 16
0
 def is_sphenic_number(self, number: int) -> bool:
     """
     Checks if a number is sphenic. A sphenic number is a number that is a positive number that is the product of three (different) prime numbers.
     :param number: The number to check.
     :return: Whether it is or not.
     """
     if number >= 1:
         prime_factors = list(primefactors(number))
         if len(prime_factors) == 3:
             if prime_factors[0] * prime_factors[1] * prime_factors[
                     2] == number:
                 return True
     return False
Esempio n. 17
0
 def convert_to_vts(self, outdir, component, iter0=None, iterf=None, diter=None, Radius=0.98, verbose=True):
     """
     Plot depth slices of field component at given depth ranging between "valmin" and "valmax"
     ================================================================================================
     Input parameters:
     outdir          - output directory
     component       - component for plotting
                         The currently available "components" are:
                             Material parameters: A, B, C, mu, lambda, rhoinv, vp, vsh, vsv, rho
                             Velocity field snapshots: vx, vy, vz
                             Sensitivity kernels: Q_mu, Q_kappa, alpha_mu, alpha_kappa
     depth           - depth for plot (km)
     iter0, iterf    - start/end iteration index
     diter           - iteration interval
     Radius          - radius for output sphere
     =================================================================================================
     """
     if not os.path.isdir(outdir): os.makedirs(outdir)
     group=self[component]
     from tvtk.api import tvtk, write_data
     try: iterArr=np.arange(iter0 ,iterf+diter, diter, dtype=int)
     except: iterArr = group.keys()
     least_prime=None
     for iteration in iterArr:
         subgroup=group[str(iteration)]
         if len(subgroup.keys())==0: continue
         if verbose: print 'Output vts file for iteration =',iteration
         theta=np.array([]); phi=np.array([]); r=np.array([]); field = np.array([])
         for key in subgroup.keys():
             subdset = subgroup[key]
             field   = np.append(field, (subdset[...]))
             theta1  = subdset.attrs['theta']
             phi1    = subdset.attrs['phi']
             theta1, phi1 = np.meshgrid(theta1, phi1, indexing='ij')
             theta   = np.append(theta, theta1)
             phi     = np.append(phi, phi1)
         x = Radius * np.sin(theta) * np.cos(phi)
         y = Radius * np.sin(theta) * np.sin(phi)
         z = Radius * np.cos(theta)
         if least_prime==None: least_prime=primefactors(field.size)[0]
         dims = (field.size/least_prime, least_prime, 1)
         pts = np.empty(z.shape + (3,), dtype=float)
         pts[..., 0] = x; pts[..., 1] = y; pts[..., 2] = z
         sgrid = tvtk.StructuredGrid(dimensions=dims, points=pts)
         sgrid.point_data.scalars = (field).ravel(order='F')
         sgrid.point_data.scalars.name = component
         outfname=outdir+'/'+component+'_'+str(iteration)+'.vts'
         write_data(sgrid, outfname)
     return
Esempio n. 18
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
Esempio n. 19
0
 def convert_to_vts(self, outdir='.', Radius=1., name='basin'):
     from tvtk.api import tvtk, write_data
     from sympy.ntheory import primefactors
     lonArr=np.array([]); latArr=np.array([])
     for geopolygon in  self.geopolygons:
         lonArr=np.append(lonArr, geopolygon.lonArr)
         latArr=np.append(latArr, geopolygon.latArr)
     theta=(90.-latArr)/180.*np.pi; phi=lonArr/180.*np.pi
     x = Radius * np.sin(theta) * np.cos(phi)
     y = Radius * np.sin(theta) * np.sin(phi)
     z = Radius * np.cos(theta)
     pts = np.empty(z.shape + (3,), dtype=float)
     pts[..., 0] = x; pts[..., 1] = y; pts[..., 2] = z
     least_prime=primefactors(x.size)[0]
     dims = (x.size/least_prime, least_prime, 1)
     sgrid = tvtk.StructuredGrid(dimensions=dims, points=pts)
     sgrid.point_data.scalars = (np.ones(x.size)).ravel(order='F')
     sgrid.point_data.scalars.name = name
     outfname=outdir+'/'+name+'.vts'
     write_data(sgrid, outfname)
     return
Esempio n. 20
0
 def isCyclic(self):
     import importlib
     sympyLib = importlib.find_loader('sympy')
     if sympyLib is not None:
         from sympy.ntheory import primefactors
         primesList = primefactors(self._den)
     else:
         from factordb.factordb import FactorDB
         f = FactorDB(self._den)
         connection = f.connect()
         primesList = f.get_factor_list()
     isDenPrime = len(primesList) == 1
     self._isCyclic = False
     if isDenPrime and self._num < self._den and self._period != 0:
         self._isCyclic = True
         cycleList = []
         spectrumsSet = set()
         for n in range(1, self._den):
             number = Rational()
             number.calc(n, self._den, self._scaleOfNotation)
             cycleList.append(number)
             spectrumsSet.add(number.spectrumString())
         if len(spectrumsSet) == (self._den - 1) / self._period:
             self._amountOfCycles = len(spectrumsSet)
         self._vertTables = []
         for i in range(self._period):
             singleVerTab = []
             for j in range(1, self._den):
                 singleVerTab.append(int(cycleList[j - 1].digits()[i + 1]))
             self._vertTables.append(singleVerTab)
         self._multiplyShiftList = [0]
         protoPeriod = cycleList[0].digits(part='period')
         for i in range(2, self._den):
             firstPeriodDigit = cycleList[i - 1].digits(part='period')[0]
             for index, digit in enumerate(protoPeriod):
                 if digit == firstPeriodDigit:
                     self._multiplyShiftList.append(index)
         cyclicNumber = int(
             (self._scaleOfNotation**self._period) * (1.0 / self._den))
     return self._isCyclic
Esempio n. 21
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 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, limit=3) == {
        4115: 1,
        3: 1
    }  # the 5 is greater than the limit
Esempio n. 22
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
Esempio n. 23
0
 def cyclicPairNumber(self):
     if self._isCyclic:
         repunitString = '9' * self._period
         periodBorder = gmpy2.mpz(repunitString)
         import importlib
         sympyLib = importlib.find_loader('sympy')
         if sympyLib is not None:
             from sympy.ntheory import primefactors
             primes = primefactors(periodBorder)
         else:
             from factordb.factordb import FactorDB
             f = FactorDB(periodBorder)
             connection = f.connect()
             primes = f.get_factor_list()
         primesSet = set(primes)
         equalPeriods = []
         for primeNumber in primesSet:
             pass
             rational = Rational()  #slow.. TODO
             rational.calc(1, primeNumber, self._scaleOfNotation)
             if rational.getPeriod() == self._period:
                 equalPeriods.append(primeNumber)
         return equalPeriods
Esempio n. 24
0
def makePrimeStringList(number): 
    strList = []
    import importlib
    sympyLib = importlib.find_loader('sympy')
    if sympyLib is not None: 
        if len(str(number)) > 30:           
            f = FactorDB(number)
            connection = f.connect()
            l = f.get_factor_list()
            for el in l:
                strList.append(str(el))
        else:
            from sympy.ntheory import primefactors                              
            primes = primefactors(number)
            for el in primes:
                strList.append(str(el))
    else:
        f = FactorDB(number)
        connection = f.connect()
        l = f.get_factor_list()
        for el in l:
            strList.append(str(el))
    return strList
def prim_root(N):
	"""Find a primitive root for N, a large safe prime. Hint: it isn't
       always 2.

    PARAMETERS
    ==========
    N: The prime in question. May be an integer or bytes object.

    RETURNS
    =======
    An integer representing the primitive root. Must be a positive
       number greater than 1.
    """

	primeFact = ntheory.primefactors(N - 1)
	for j in range(2, N):
		found = True
		for factor in primeFact:
			if pow(j,(N - 1) // factor, N) == 1:
				found = False
				break
		if found == True:
				return j
	return 0
Esempio n. 26
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}
    #issue 19683
    assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
    #issue 17676
    assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
    assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
    assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}

    assert factorint(0, multiple=True) == [0]
    assert factorint(1, multiple=True) == []
    assert factorint(-1, multiple=True) == [-1]
    assert factorint(-2, multiple=True) == [-1, 2]
    assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
    assert factorint(2, multiple=True) == [2]
    assert factorint(24, multiple=True) == [2, 2, 2, 3]
    assert factorint(126, multiple=True) == [2, 3, 3, 7]
    assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
    assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
    assert factorint(64015937, multiple=True) == [7993, 8009]
    assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]

    assert factorint(fac(1, evaluate=False)) == {}
    assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
    assert factorint(fac(15, evaluate=False)) == \
        {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
    assert factorint(fac(20, evaluate=False)) == \
        {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
    assert factorint(fac(23, evaluate=False)) == \
        {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}

    assert multiproduct(factorint(fac(200))) == fac(200)
    assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
    for b, e in factorint(fac(150)).items():
        assert e == fac_multiplicity(150, b)
    for b, e in factorint(fac(150, evaluate=False)).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 len(factorint(fac(10000, evaluate=False))) == 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) == \
        {int(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))
    # test dict/Dict input
    sans = '2**10*3**3'
    n = {4: 2, 12: 3}
    assert str(factorint(n)) == sans
    assert str(factorint(Dict(n))) == sans
Esempio n. 27
0
def lengthOfPrimeFacs(n):
	return len(primefactors(n))
Esempio n. 28
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))
Esempio n. 29
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(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) == \
           {19026377261L: 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, 'pollard_rho(4)')
    raises(ValueError, 'pollard_pm1(3)')
    raises(ValueError, '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}
Esempio n. 30
0
        for i in range(len(lst)):
            result.extend([ lst[i] ] + x for x in permutation(lst[:i] + lst[i+1:], num -1 ) )
        return result
    if num == 1:
        return result

def make_odd_lst(input_lst):
    result = []
    for test_lst in input_lst:
        if test_lst[len(test_lst) - 1] % 2 == 1:
            result.append(test_lst)
    return result

def lst_to_num(input_lst):
    ret = 0    
    for i in range(len(input_lst)):
        ret += input_lst[i] * 10 ** (len(input_lst) - 1 - i)
    return ret

input_num_lst = range(7, 0, -1)
test_lst = make_odd_lst(permutation(input_num_lst, 7))
"""
print test_lst[0]
print lst_to_num(test_lst[0])
"""
for i in test_lst:
    test_num = lst_to_num(i)
    if len(primefactors(test_num)) == 1:
        print test_num
        break
Esempio n. 31
0
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 30 09:50:39 2014

@author: Yusuke
"""

from sympy.ntheory import primefactors

input_number = 89899

print primefactors(input_number)
    
    
 
Esempio n. 32
0
    for i in range(2, 11):
        base = int(enclosed_num, i)
        bases.append(base)
        if isprime(base):
            check = False
            break

    #print(len(bases))
    if check == True:
        print(enclosed_num, end="")
        output.write(enclosed_num)
        for base in bases:
            if divisor_count(base) == 2:
                print("dafuq")
            print(' ', end="")
            print(primefactors(base)[0], end="")
            output.write(" ")
            output.write(str(primefactors(base)[0]))
        print()

        for base in bases:
            print('{} -> {}'.format(base, primefactors(base)))
        output.write("\n")
        counter += 1

    #if cur_num % 10 == 0:
    #    print(cur_num)
    cur_num += 1
    if cur_num > 2**(length - 2):
        break
Esempio n. 33
0
    if num == 1:
        return result


def make_odd_lst(input_lst):
    result = []
    for test_lst in input_lst:
        if test_lst[len(test_lst) - 1] % 2 == 1:
            result.append(test_lst)
    return result


def lst_to_num(input_lst):
    ret = 0
    for i in range(len(input_lst)):
        ret += input_lst[i] * 10**(len(input_lst) - 1 - i)
    return ret


input_num_lst = range(7, 0, -1)
test_lst = make_odd_lst(permutation(input_num_lst, 7))
"""
print test_lst[0]
print lst_to_num(test_lst[0])
"""
for i in test_lst:
    test_num = lst_to_num(i)
    if len(primefactors(test_num)) == 1:
        print test_num
        break
Esempio n. 34
0
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 01 00:28:16 2014

@author: Yusuke
"""

from sympy.ntheory import primefactors


for i in range(9,0,-1):
    for j in range(9,-1,-1):
        input_number = i * 1e3 + j * 1e2 + j * 1e1 + i
        prime_lst = primefactors(input_number)            
        max_prime = max(prime_lst)            
        if max_prime < 100:
            print input_number, prime_lst
                
"""
for i in range(9,0,-1):
    for j in range(9,-1,-1):
        for k in range(9,-1,-1):
            input_number = i * 1e5 + j * 1e4 + k * 1e3 + k * 1e2 + j * 1e1 + i
            prime_lst = primefactors(input_number)            
            max_prime = max(prime_lst)            
            if max_prime < 100:
                print input_number, prime_lst
"""                
            
            
        
Esempio n. 35
0
from sympy.ntheory import primefactors

a = 2
while True:
    if len(primefactors(a)) != 4:
        a = a + 1
        continue
    if len(primefactors(a + 1)) != 4:
        a = a + 2
        continue
    if len(primefactors(a + 2)) != 4:
        a = a + 3
        continue
    if len(primefactors(a + 3)) != 4:
        a = a + 4
        continue
    print(a)
    break
def euler_totient(n):
    return int(product((1-(1/i)) for i in primefactors(n)) * n)
Esempio n. 37
0
def A001221() -> Iterator[int]:
    "Number of distinct primes dividing n (also called omega(n))."
    from sympy.ntheory import primefactors

    for n in count(1):
        yield len(primefactors(n))
Esempio n. 38
0
    sys.exit(1)

# Read the public key
print("Reading the public key")
with open(sys.argv[1], 'r') as f:
    pubkey = RSA.import_key(f.read())

# Is the read key really a public key?
if pubkey.has_private():
    print("The passed key is a private key")
    sys.exit(1)

# Factorize the modulus (the most ridiculous part!)
modulus = pubkey.n
print("Factorizing (It takes years :( ) ")
l = primefactors(modulus)
print("Done :)")

# Generate private key from the factors
print("Generating the private key")
prime1 = l[1]  # prime1 > prime2
prime2 = l[0]
public_exp = pubkey.e
private_exp = mod_inverse(public_exp, (prime1-1)*(prime2-1))
# coef = Integer(prime2).invert(prime1)
# print(f"modulus: {prime1 * prime2}")
# print(f"publicExponent: {public_exp}");
# print(f"privateExponent: {private_exp}");
# print(f"prime1: {prime1}");
# print(f"prime2: {prime2}");
# print(f"coefficient: {coef}");