Beispiel #1
0
 def test_factors(self):
     self.assertEqual(tuple(factors(2)), (1, 2))
     self.assertEqual(tuple(factors(6)), (1, 2, 3, 6))
     self.assertEqual(tuple(factors(25)), (1, 5, 25))
     self.assertEqual(tuple(factors(2017)), (1, 2017))
     self.assertEqual(tuple(factors(100)),
                      (1, 2, 4, 5, 10, 20, 25, 50, 100))
def test_candidate(a, c):
    # Find the factors of m^2 = c / a    
    a_factors = primes.factors(a, prime_table)
    c_factors = primes.factors(c, prime_table)

    # Eliminate common factors 
    a_index = c_index = 0
    while (a_index < len(a_factors)) and (c_index < len(c_factors)):
        if a_factors[a_index] == c_factors[c_index]:
            a_factors[a_index] = 1
            c_factors[c_index] = 1
            a_index += 1
            c_index += 1
        elif a_factors[a_index] < c_factors[c_index]:
            a_index += 1
        else:
            c_index += 1
    a_factors = [x for x in a_factors if x != 1]
    c_factors = [x for x in c_factors if x != 1]

    # Get the square root m
    a_factors = a_factors[::2]
    c_factors = c_factors[::2]

    # Calculate b
    b = a
    for f in c_factors:
        b *= f
    for f in a_factors:
        b //= f

    if b in factor_list:
        return True, b
    else:
        return False, b
def testSpecialFactors2():
    d = {
        3: 1,
        102: 36,
        130: 25,
        312: 8,
        759: 81,
        2496: 512,
        2706: 1936,
        3465: 1225,
        6072: 5184,
        6111: 3969,
        8424: 5832,
        14004: 432,
        16005: 1089,
        36897: 21609,
        37156: 12544,
        92385: 50625,
        98640: 50625,
        112032: 27648,
        117708: 41616,
        128040: 69696
    }  ## ,351260,740050}
    for k, v in sorted(d.iteritems()):
        f = primes.factors(k)
        sp = specialFactors(f, k)
        if v not in sp:
            print k, v, sp
            print
Beispiel #4
0
def divisors(n):
  factors = {}
  for f in primes.factors(n, p):
    if not f in factors:
      factors[f] = 1
    factors[f] = factors[f] + 1
  return util.product(factors.values())
Beispiel #5
0
def groups_of_order(n):
    start_time = time()
    k = upper_bound_generating_set(n)
    # Don't check [] cycle type
    good_cts = good_cycle_types(n, list(factors(n))[1:])[1:]
    # Don't check cycle types which give order n
    good_cts = [
        ct for ct in good_cts
        if reduce(lambda m, n: m * n // gcd(m, n), ct) < n
    ]
    print(good_cts)
    N = len(good_cts) * comb(sum(size_of_conj_class(n, ct)
                                 for ct in good_cts), k - 1)
    print(N)
    total_groups = 0
    # Total hack to optimise prime case lol
    cts = good_cts if k != 1 else []
    i = 1
    for ct in good_cts:
        print("New cycle type:", ct)
        x = canonical_of_cycle_type(n, ct)
        for perms in combinations(
                chain(*(conjugacy_class(n, ct) for ct in cts)), k - 1):
            G = Group.generate(n, (x, ) + perms, limit=n)
            if G is not None and len(G.perms) == n:
                yield G
                total_groups += 1
            if i % UPDATE_INTERVAL == 0 or i == N or i == 1:
                elapsed = time() - start_time
                print(f"{i:{len(str(N))}}/{N} ({i / N:7.2%}) "
                      f"{i / elapsed if elapsed != 0.0 else inf:.0f}/s"
                      f" ETA{(N - i) * elapsed / i / 60:.0f}m"
                      f" ({(N - i) * elapsed / i / 60 ** 2:.1f}h)"
                      f" {total_groups}G")
            i += 1
Beispiel #6
0
def euler66(s, start, limit) :
	solutions = []
	tricky = []
	print >> sys.stderr, "Limit = %d" % limit
	for a in range(2, limit) :
		x1 =
	for D in sorted(s) :
		p = primes.factors(D)
		incr = p[-1]
		for i in range(1, limit) :
			x1 = i * incr - 1
			x2 = x1 + 2
			x3 =
			print >> sys.stderr, D, x, "\r",
			if testDiophantine(x1, x2, D, y) :
				print >> sys.stderr
				print >> sys.stderr, ("%d*%d - %d*%d*%d = 1") % (x,x,D,y,y)
				solutions.append( (x, D) )
				break
			if x > limit:
				print >> sys.stderr
				print >> sys.stderr, "skipping %d" % D
				tricky.append(D)
				break

	#max_x = max(a[0] for a in solutions)
	#max_D = [ a[1] for a in solutions if a[0] == max_x ]
	#print
	#print max_D, max_x
	return tricky
def testSpecialFactors2() :
	d = {3:1,102:36,130:25,312:8,759:81,2496:512,2706:1936,3465:1225,6072:5184,6111:3969,8424:5832,14004:432,16005:1089,36897:21609,37156:12544,92385:50625,98640:50625,112032:27648,117708:41616,128040:69696} ## ,351260,740050}
	for k,v in sorted(d.iteritems()) :
		f = primes.factors(k)
		sp = specialFactors(f, k)
		if v not in sp :
			print k, v, sp
			print
Beispiel #8
0
def factor_dict(number):
    d = dict()
    for f in primes.factors(number):
        if f in d:
            d[f] += 1
        else:
            d[f] = 1
    return d
def phi(n):
    factors = primes.factors(n, prime_table)

    amount = 0
    for k in range(1, n + 1):
        if fractions.gcd(n, k) == 1:
            amount += 1

    return amount
Beispiel #10
0
def phy(x):
        d={}
        for factor in primes.factors(x):
                d[factor]=0
        
        
        num = reduce(lambda x,y:x*y , [z-1 for z in d])
        den = reduce(lambda x,y:x*y , [z for z in d])
        
        return (x*num)/den
Beispiel #11
0
 def get_result(n):
     try:
         n = int(n)
     except ValueError:
         return {
             "number": n,
             "error": 'not a number',
         }
     if n > 1e6:
         return {
             "number": n,
             "error": "too big number (>1e6)",
         }
     else:
         return {"number": n, "decomposition": factors(n)}
Beispiel #12
0
def factors_count(number):
    """
    >>> factors_count(1)
    1
    >>> factors_count(3)
    2
    >>> factors_count(6)
    4
    >>> factors_count(28)
    6
    """
    if number == 1:
        return 1

    return reduce(mul, (exponent + 1 for prime, exponent in primes.factors(number)))
Beispiel #13
0
def solve(N, J):
    jamcoins = []
    for n in range(0, 2**(N-2)):
        raw_bits = '1' + '{:0{width}b}'.format(n, width=N-2) + '1'
        is_jamcoin = True
        proof = []
        for base in range(2, 11):
            number = int(raw_bits, base)
            factors = primes.factors(number)
            if len(factors) == 2:
                is_jamcoin = False
                break
            proof.append(str(factors[1]))
        if is_jamcoin:
            jamcoins.append([raw_bits] + proof)
        if len(jamcoins) == J:
            break
Beispiel #14
0
 def get_result(n):
     try:
         n = int(n)
     except ValueError:
         return {
             "number": n,
             "error" : 'not a number',
             }
     if n > 1e6:
         return {
             "number": n,
             "error" : "too big number (>1e6)",
             }
     else:
         return {
             "number": n,
             "decomposition" : factors(n)
             }
Beispiel #15
0
Datei: 047.py Projekt: 3kwa/euler
def consecutive_distinct(count):
    """
    >>> consecutive_distinct(2)
    14
    >>> consecutive_distinct(3)
    644
    """
    result = None
    acc = set()
    consecutive = 1
    i = 1
    while result is None:
        i += 1
        new = set(factors(i))

        # does i have the correct number of factors
        if len(new) != count:
            consecutive = 1
            acc = set()
            continue

        # acc is empty and new is acceptable we are resetting
        if len(acc) == 0:
            consecutive = 1
            acc = new
            continue

        # are all of i's factor distinct from the previous 'count' i
        if len(acc.intersection(new)) != 0:
            consecutive = 1
            acc = new
            continue

        # increase the count of consecutive and add the factors to acc
        consecutive += 1
        acc = acc.union(new)

        if consecutive == count:
            result = i - count + 1

    return result
Beispiel #16
0
def euler141() :
	## [3,102,130,312,759,2496,2706,3465,6072,6111,8424,14004,16005,36897,37156,92385,98640,112032,117708,128040,351260,740050]) :
	s = set()
	for sqr in xrange(2, 1000*1000) :
		if primes.isPrime(sqr) : continue
		i = sqr*sqr
		print sqr, i, "\r",
		f = primes.factors(sqr)
		sp = specialFactors.specialFactors(f, sqr)
		for r in sp :
			x = r * (i - r)
			cub = CubeRoot(x)
			if cub :
				q, r2 = divmod(i, cub)
				if r == r2 :
					a = [r, q, cub]
					print sqr, i, a
					s.add(i)
					break
	print sorted(s)
	print sum(s)
Beispiel #17
0
def test_zero():
    assert (factors(0) == [])
Beispiel #18
0
import primes, powerset, factorial

max_elem = 10000
lowest = 2
d = {}
for i in range(max_elem-1, lowest-1, -1) :
	pf = primes.factors(i)
	d[i] = sum(pf[0: -1])

s = []
for i in range(lowest, max_elem) :
	p = d[i]
	if lowest < p < max_elem :
		if i == d[p] and p < d[p] :
			s.append ( (p, d[p]) )

a = 0
for x in s :
	a += x[0] + x[1]
	print x
print a

Beispiel #19
0
def test_big():
    assert (factors(967) == [967])
    assert (factors(870) == [2, 3, 5, 29])
    assert (factors(900) == [2, 2, 3, 3, 5, 5])
    assert (factors(998) == [2, 499])
    assert (factors(782) == [2, 17, 23])
def test_non_repeated_prime_number():
    assert (primes.factors(21) == [3, 7])
Beispiel #21
0
def test_two():
    '''
    testing for 2^10
    '''
    assert factors(1024) == [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
	def F(n):
		f = primes.factors(n)
		s = 0
		for i in range(len(f)):
			s += fn(f[i])
		return s 
	def F(n):
		f = primes.factors(n)
		s = 0 
		for i in range(len(f)):
			s+= (mu(f[i])*fn(n/f[i]))
		return s 
def testSpecialFactors() :
	for i in range(4, 100) :
		if not primes.isPrime(i) :
			f = primes.factors(i)
			sp = specialFactors(f, i)
			print i, sp
def test_prime_number_zero():
    assert (primes.factors(0) == [])
Beispiel #26
0
def isprime(x):
  return x & 1 and len(primes.factors(x)) == 0
Beispiel #27
0
# The first three consecutive numbers to have three distinct prime factors are:
#
# 644 = 2² × 7 × 23
# 645 = 3 × 5 × 43
# 646 = 2 × 17 × 19.
#
# Find the first four consecutive integers to have four distinct prime factors.
# What is the first of these numbers?


import primes
import sys

primes.sieve(140000)
target = 4

counter = 0
for x in range(2, 200000):
    # print(x, primes.factors(x))
    if (len(primes.factors(x)) >= target+1):
        counter += 1
    else:
        if (counter > 1):
            sys.stdout.write(str(counter))
            sys.stdout.flush()
        counter = 0
    if (counter == target):
        print('\n')
        print(x-target+1)
        break
Beispiel #28
0


def numOfUniq(mylist):
        d = {}
        for x in mylist:
            d[x] = 1
        mylist = list(d.keys())
        return len(mylist)

factors=[]
contin=1
n=2


while contin:
        count =0
        for i in range(0,NUM):
                factors=primes.factors(n+i)
                if numOfUniq(factors)<NUM:
                        break
                else:
                        count+=1
        if count==NUM:
                print n
                break
        n+=1
        

endTime=time.clock()
print endTime-startTime
Beispiel #29
0
def test_zero():
    assert primes.factors(0) == []
def test_repeated_prime_number():
    assert (primes.factors(16) == [2, 2, 2, 2])
Beispiel #31
0
def test_small():
    assert (factors(2) == [2])
    assert (factors(8) == [2, 2, 2])
    assert (factors(29) == [29])
    assert (factors(36) == [2, 2, 3, 3])
    assert (factors(69) == [3, 23])
def test_single_prime_number():
    assert (primes.factors(2) == [2])
############################################################

print("Calculating M(n) for n in 1..{:,}".format(SIZE))
m = [1] * (SIZE+1)
m[1] = 0
answer = 0

prev_factors = [2]
prev_time = time.clock()
for a in range(3, SIZE):
    if (a % 25000) == 0:
        print("Calculating M(?) = {:,} with {:.2f} seconds elapsed, {:.3f} seconds delta".format(a, time.clock() - start_time, time.clock() - prev_time))
        prev_time = time.clock()
    
    aam1 = a * (a - 1)
    curr_factors = primes.factors(a, prime_table)
    #print("    a={a}, a*(a-1)={aam1}, prev_factors={p}, curr_factors={c}".format(a=a, aam1=aam1, p=prev_factors, c=curr_factors))
    for d in divisors(prev_factors, curr_factors):
        n = aam1 // d
        if a >= n:
            continue
        if n <=SIZE:
            #print("        M({n}) = {a}".format(n=n, a=a))
            #print("M({n}) = {a}".format(n=n, a=a), end='')
            #print("    a={a}, a*(a-1)={aam1} = {n}*{d}".format(a=a, aam1=aam1, d=d, n=n))
            m[n] = a
    prev_factors = curr_factors

for n in range(1, SIZE+1):
    answer += m[n]
    #print("M({:2}) = {:2}".format(n, m[n]))
def has_square(n):
    """
    Returns True iff n contains a perfect square as a factor.
    """
    facts = factors(n)
    return len(nub(facts)) < facts
Beispiel #35
0
#!/usr/bin/python3
import primes

def last(gen):
    x = None
    for y in gen: x = y
    return x

print(last(primes.factors(600851475143)))
Beispiel #36
0
def test_three():
    '''
    testing for the product of a series of primes
    '''
    assert factors(15015) == [3, 5, 7, 11, 13]
Beispiel #37
0
def test_one():
    '''
    testing for 1
    '''
    assert factors(1) == [1]
Beispiel #38
0
def problem3(n):
  return max(primes.factors(n))
Beispiel #39
0
def test_prime():
    assert primes.factors(17) == [17]
Beispiel #40
0
import primes, powerset, factorial

max_elem = 10000
lowest = 2
d = {}
for i in range(max_elem - 1, lowest - 1, -1):
    pf = primes.factors(i)
    d[i] = sum(pf[0:-1])

s = []
for i in range(lowest, max_elem):
    p = d[i]
    if lowest < p < max_elem:
        if i == d[p] and p < d[p]:
            s.append((p, d[p]))

a = 0
for x in s:
    a += x[0] + x[1]
    print x
print a
#SIZE = 10**7  # Answer = 1316768308545 in 19.59 seconds
SIZE = 10**8  # Answer in 192.13 seconds

# With SIZE = 10**8, it takes
# 40.44 seconds to calculate primes
# 67.74 seconds to calculate factors

############################################################
import primes
prime_table, prime_list = primes.calculate_primes(SIZE)


############################################################
factor_list = dict()
for prime in prime_list:
    factor_list[prime+1] = primes.factors(prime+1, prime_table)
    #print("factor_list[{}] = {}".format(prime+1, factor_list[prime+1]))
print("Finished calculating factor_list after {:.2f} seconds".format(time.clock() - start_time))
#print()


############################################################
reverse_factors = dict()
for factor in factor_list:
    this = sorted(factor_list[factor])
    that = list()
    i = 0
    while (i+1) < len(this):
        if this[i] == this[i+1]:
            i += 2  # skip pair of prime factors
        else:
Beispiel #42
0
def test_two_factors():
    assert primes.factors(39) == [3, 13]
Beispiel #43
0
def test_more_factors():
    assert primes.factors(68) == [2, 2, 17]
Beispiel #44
0
def testSpecialFactors():
    for i in range(4, 100):
        if not primes.isPrime(i):
            f = primes.factors(i)
            sp = specialFactors(f, i)
            print i, sp
Beispiel #45
0
import specialFactors
import primes


j = 4
max_so_far = -1
k = -1
while 1 :
	if not primes.isPrime(j) :
		f = primes.factors(j)
		sp = specialFactors.specialFactors(f, j)	
		L = len(sp)
		if L > max_so_far :
			pf = primes.primeFactors(j)
			max_so_far, k = L, j
			print k, max_so_far, pf
		if L > 1000 : break
		print j, L, "\r", 
	j += 1
print
print k, max_so_far
Beispiel #46
0
def testSpecialFactors() :
	#f = primes.factors(37156)
	#f = primes.factors(576081)
	f = primes.factors(759)
	print f
	print specialFactors.specialFactors(f)