Ejemplo n.º 1
0
def divisors_arithmetic_sequence_bf(limit_n, solutions):
    total = 0
    primes_index = prime_factors(3 * limit_n, False)
    print('Primes calculated!')
    primes = prime_factors(10**4)
    t0 = time()
    p = 1
    for n in range(1, limit_n + 1):
        if n > p * 10**6:
            print('Now in: ', p)
            p += 1
        subtotal = 0
        k = 3 * n
        if primes_index[k] == 0:
            if n % 4 in (0, 3):
                sqrt_k = math.sqrt(k)
                factors = list(decompose_primes(n, primes))
                print(k, n % 4, 'Candidate', factors)
                factors = decompose_primes(n, primes)
                for d in range(1, math.ceil(sqrt_k)):
                    if k % d == 0:
                        if (d % 2) + ((k // d) % 2) != 1:
                            if check_compatibility(d, k // d, k):
                                subtotal += 1
                                if subtotal > solutions:
                                    break
        if subtotal == solutions:
            print(k, list(factors))
            total += 1
    t1 = time()
    print('Total time to get solution: ', t1 - t0)
    return total
Ejemplo n.º 2
0
def solve():
    n = 647
    while(n):
        if(len(prime_factors(n)) == 4 and
           len(prime_factors(n+1)) == 4 and
           len(prime_factors(n+2)) == 4 and
           len(prime_factors(n+3)) == 4):
            return n
        n += 4
Ejemplo n.º 3
0
def combinations_over_value(limit_value):
    primes = prime_factors(100)
    primes_index = prime_factors(100, False)
    value = 3
    index = 0
    solution = find_combs(primes, value, index)
    while solution <= limit_value:
        if primes_index[value] == 1:
            index += 1
        value += 1
        solution = find_combs(primes, value, index)
    return value
Ejemplo n.º 4
0
def num_lattice_points_fast(n):
    # count with inclusion-exclusion
    if n == 1:
        return 1

    if (n + 3) % 2 == 1:
        return 0

    a = (n + 3) / 2
    half_a = (a - 1) / 2
    first_lattice_point_x = 3 - (a % 3)

    prime_factors_a = [p for p, m in utils.prime_factors(a)]

    # A is every 3rd point on the line in the lattice, B1 is all points w/ x
    # coord divisible by prime factor i
    # #(A and not B) = #A - #(A and (B1 or B2 or ...))
    # = #A - #((A and B1) or (A and B2) or ..)
    # = #A - (#(A and B1) + #(A and B2) + ... - #(A and B1 and B2) - ...)
    num_lattice_points_half = 0
    factor_sets = utils.power_set(prime_factors_a)
    for factors in factor_sets:
        sign = 1 if (len(factors) % 2 == 0) else -1
        pr = [(3, first_lattice_point_x)] + [(f, 0) for f in factors]
        num_lattice_points_half += sign * count_elts_in_range_with_remainders(first_lattice_point_x, half_a + 1, pr)

    return num_lattice_points_half * 2
Ejemplo n.º 5
0
def number_of_consec_primes(a, b):
    n = 0
    while True:
        formula = n * n + a * n + b
        if sum(prime_factors(formula)) != formula:
            return n
        n += 1
Ejemplo n.º 6
0
def prime_consecutive_sum(limit_value):
    primes  = prime_factors(limit_value, True)

    consecutives = -float('inf')
    max_prime = 0

    for index in range(len(primes)-1, -1,-1):
        num = primes[index]
        if num < 990000:
            return max_prime
        starting_index = 0
        while True:
            current_index = starting_index
            if index-starting_index+1<consecutives or starting_index==index:
                break
            total = 0
            while True:
                total += primes[current_index]
                if total>num or current_index==index:
                    break
                if total==num:
                    if consecutives < current_index-starting_index+1:
                        consecutives = current_index-starting_index+1
                        max_prime = num
                        print(num,consecutives)
                    break
                current_index += 1
            starting_index += 1
Ejemplo n.º 7
0
def pb3():
    """
    Problem 3 : Largest prime factor
    See utils.prime_factors for having the list of prime numbers.
    Generates the list of prime factors and takes the last element.
    """
    return utils.prime_factors(600851475143)[-1]
Ejemplo n.º 8
0
def product_pairs(n):
    '''
    2. This function solves the problem finding every possible pair of factors given its prime decomposition
    '''
    primes = prime_factors(1000)
    prime_factors = decompose_primes(n, primes, as_dict=False)
    prime_factors = [1] + prime_factors
    pairs = {}
    for r1 in range(1, len(prime_factors) // 2 + 1):
        for comb1 in combinations([i for i in range(len(prime_factors))], r1):
            a = 1
            for idx in comb1:
                a *= prime_factors[idx]
            set_a = set(decompose_primes(a, primes))
            complement = [
                i for i in range(len(prime_factors)) if i not in comb1
            ]
            for r2 in range(r1, len(complement) + 1):
                for comb2 in combinations(complement, r2):
                    b = 1
                    for idx in comb2:
                        b *= prime_factors[idx]
                    if set_a.isdisjoint(set(decompose_primes(b, primes))):
                        if (a, b) not in pairs and (b, a) not in pairs:
                            pairs[(a, b)] = 1
    return len(pairs) + 1
Ejemplo n.º 9
0
def get_n_with_maximum_ratio(limit_value):
    primes = prime_factors(100)
    div = 1
    for prime in primes:
        div *= prime
        if div > limit_value:
            return div // prime
Ejemplo n.º 10
0
def arithmetic_sequence():
    primes = prime_factors(10**6, False)
    perm_used = [0] * 10000
    for value in range(1001, 9987):
        perm4 = elements_perm_k(str(value), 4)
        if perm_used[int(perm4[0])] == 0:
            for a in range(0, len(perm4) - 2):
                if primes[int(perm4[a])] and int(perm4[a]) > 1000:
                    for b in range(a + 1, len(perm4) - 1):
                        if primes[int(perm4[b])] and int(perm4[b]) > 1000:
                            d2 = int(perm4[b]) - int(perm4[a])
                            for c in range(b + 1, len(perm4)):
                                if primes[int(
                                        perm4[c])] and int(perm4[c]) > 1000:
                                    d1 = int(perm4[c]) - int(perm4[b])
                                    if d1 == d2:
                                        if (perm4[a], perm4[b], perm4[c]) != (
                                                '1487', '4817', '8147'):
                                            return perm4[a] + perm4[b] + perm4[
                                                c]
                                else:
                                    continue
                        else:
                            continue
                else:
                    continue
        else:
            continue
        for value in perm4:
            perm_used[int(value)] = 1
Ejemplo n.º 11
0
def num_lattice_points_slow(n):
    if n == 1:
        return 1

    if (n + 3) % 2 == 1:
        return 0

    a = (n + 3) / 2
    half_a = (a - 1) / 2
    first_lattice_point_x = 3 - (a % 3)

    prime_factors_a = [p for p, m in utils.prime_factors(a)]
    print prime_factors_a

    # count by looping
    num_lattice_points_half = 0
    for x in xrange(first_lattice_point_x, half_a + 1, 3):
        x_y_relatively_prime = True
        for p in prime_factors_a:
            if (x % p == 0):
                x_y_relatively_prime = False
                break

        if x_y_relatively_prime:
            num_lattice_points_half += 1

    result = 2 * num_lattice_points_half
    return result
Ejemplo n.º 12
0
def pythagorean_triplets(limit_n):
    primes = prime_factors(1000)
    total = 0
    t0 = time()
    for m in range(2, limit_n + 1):
        if 2 * m**2 + 2 * m >= limit_n:
            break
        factors = decompose_primes(m, primes, True)
        inc = 1
        if m % 2 == 0:
            inc = 2
        complete = False
        for n in range(1, m, inc):
            if inc == 1 and n % 2 == 1:
                continue
            are_coprime = True
            for p in factors:
                if n % p == 0:
                    are_coprime = False
                    break
            if are_coprime:
                a = m**2 - n**2
                b = 2 * m * n
                c = m**2 + n**2
                if (a + b + c) >= limit_n:
                    break
                if c % (b - a) == 0:
                    print(a, b, c)
                    total += limit_n // (a + b + c)
        if complete:
            break
    t1 = time()
    print('Time to reach solution: {0} sec'.format(t1 - t0))
    return total
Ejemplo n.º 13
0
def problem_five():
    c = Counter()
    sum = 1
    for i in xrange(21):
        i_c = Counter(prime_factors(i))
        c = c | i_c
    for k, v in dict(c).iteritems():
        sum *= int(pow(k, v))
    return sum
Ejemplo n.º 14
0
def repunit_divisibility_improved(limit_n):
    primes = prime_factors(10**6)
    factors = []
    for i in primes[3:]:
        factor = gcd(i - 1, primes)
        if (10**factor) % i == 1:
            factors.append(i)
            continue
        if len(factors) == 40:
            return sum(factors)
Ejemplo n.º 15
0
def prime_remainders(limit_res):
    '''
    returns the least value of n for which the first remainder first exceeds 10**10
    '''
    primes = prime_factors(10**6)
    n = 1
    for p in primes:
        if 2 * n * p > limit_res and n % 2 != 0:
            return n
        n += 1
Ejemplo n.º 16
0
def ratio_tracker():
    primes_index = prime_factors(10**6, False)
    primes = prime_factors(10**6, True)
    print('Prime factors stored!')

    l = 7
    terms = 13
    prime_counter = 8
    corner_values = [31, 37, 43]
    while ((prime_counter / terms) > 0.1):
        l += 2
        terms += 4
        for index in range(len(corner_values)):
            corner_values[index] += (index + 1) * 2 + 4 * (l - 3)
            if corner_values[index] < 10**6:
                if primes_index[corner_values[index]]:
                    prime_counter += 1
            else:
                prime_counter += is_prime(corner_values[index], primes)
    return l
Ejemplo n.º 17
0
def get_total_set(limit_value):
    primes = prime_factors(limit_value)
    primes_index = prime_factors(limit_value, False)
    counter = 0
    for d in range(2,limit_value+1):
        if primes_index[d]==1:
            counter += d-1
        else:
            tmp = d-1
            factors = find_prime_factors(d,primes)
            for e in range(0,len(factors)):
                variations = combinations(factors, r=e+1)
                for var in variations:
                    num = 1
                    for elem in var:
                        num *= elem
                    if (e+1)%2==0:
                        tmp += (d-1)//num
                    else: 
                        tmp -= (d-1)//num
            counter += tmp
    return counter
Ejemplo n.º 18
0
def sum_product_set_length(limit_value):
    sol = {}
    k = [i for i in range(2, limit_value + 1)]
    k_index = {}
    for i in k:
        k_index[i] = 1
    primes = prime_factors(10000)
    primes_index = prime_factors(100000, False)
    decomposition = {}
    i = 4
    while k:
        if primes_index[i] == 0:
            tmp = decompose_and_group(i, primes)
            for g in tmp:
                tmp_k = (i - g[1]) + len(g[0])
                if tmp_k not in sol:
                    if tmp_k in k_index:
                        sol[tmp_k] = i
                        k.remove(tmp_k)
        i += 1
        print(i)
    return sum(set(sol.values()))
Ejemplo n.º 19
0
def find_counter_between(limit_value):
    primes = prime_factors(limit_value)
    primes_index = prime_factors(limit_value, False)
    lower = 1 / 3
    upper = 1 / 2
    counter = 0
    for i in range(2, limit_value + 1):
        if primes_index[i] == 1:
            counter += math.ceil(i / 2) - math.floor(i / 3) - 1
        else:
            sequence = 0
            factors = find_prime_factors(i, primes)
            for s in range(math.ceil(i / 3), math.floor(i / 2) + 1):
                ins = True
                for p in factors:
                    if s % p == 0:
                        ins = False
                        break
                if ins:
                    sequence += 1
            counter += sequence
    return counter
Ejemplo n.º 20
0
def radicals(limit_n):
    '''
    finds radicals for every prime number below limit_n
    '''
    radicals = {}
    primes = prime_factors(limit_n)
    for i in range(1, limit_n):
        radicals[i] = list(decompose_primes(i, primes, True).keys())
    square_free = [0] * (limit_n + 1)
    for p in primes:
        for i in range(p * p, limit_n, p * p):
            square_free[i] = 1
    return radicals, square_free
Ejemplo n.º 21
0
def primes_square_cube(limit_n):
    primes_index = prime_factors(limit_n + 1, False)
    i = 0
    n = 2
    counter = 0
    while True:
        i = i + n
        tmp = i * 3 + 1
        if tmp > limit_n:
            break
        if primes_index[tmp] == 1:
            counter += 1
        n += 2
    return counter
Ejemplo n.º 22
0
def solution_given_primes():
    '''
    3. This function solves the problem using the prime decomposition to calculate the number of valid solutions
    '''
    n = 180100
    primes = prime_factors(200000)
    while True:
        dec_primes = decompose_primes(n**2, primes, as_dict=True)
        divs = 1
        for p in dec_primes:
            divs *= (dec_primes[p] + 1)
        if divs > 1999:
            return n
            break
        n += 1
Ejemplo n.º 23
0
def get_n_permutation(limit_value):
    primes = prime_factors(limit_value)
    min_ratio = float('inf')
    candidate = 0
    for i in range(len(primes) - 1, 100, -1):
        for j in range(i, 100, -1):
            number = primes[i] * primes[j]
            if number < 10**7:
                phi_acum = number - 1 - sum([
                    1 for c in range(primes[i], number, primes[i])
                ]) - sum([1 for c in range(primes[j], number, primes[j])])
                if sorted(str(number)) == sorted(str(phi_acum)):
                    if min_ratio > (number / phi_acum):
                        min_ratio = (number / phi_acum)
                        candidate = number
    return candidate
Ejemplo n.º 24
0
def divisors_arithmetic_sequence(limit_n):
    total = 0
    factors = [1] + prime_factors(limit_n)[1:]
    print('Primes calculated!')
    t0 = time()
    for p in factors:
        if p % 4 == 3:
            total += 1
        if 4 * p < limit_n:
            total += 1
        else:
            continue
        if 16 * p < limit_n:
            total += 1
    t1 = time()
    print('Total time to get solution: ', t1 - t0)
    return total
Ejemplo n.º 25
0
def phytagorean_triangle(limit_value):
    primes = prime_factors(int(math.sqrt(limit_value)) + 1)
    visited = [0] * (limit_value + 1)
    n = 1
    while n < limit_value:
        lower = n + 1
        ns = n**2
        for m in range(lower, limit_value, 2):
            if mcd(n, m, primes):
                total = sum([m**2 - ns, 2 * m * n, m**2 + ns])
                if total <= limit_value:
                    for i in range(total, limit_value + 1, total):
                        visited[i] += 1
                else:
                    break
        n += 1
    return sum([1 for i in visited if i == 1])
Ejemplo n.º 26
0
def prime_triplets_bf(limit_value):
    primes = prime_factors(int(math.sqrt(limit_value)) + 1)
    total = 0
    values = []

    for a in range(len(primes)):
        for b in range(len(primes)):
            pt1 = primes[a]**2 + primes[b]**3
            if pt1 >= limit_value:
                break
            for c in range(len(primes)):
                pt2 = pt1 + primes[c]**4
                if pt2 >= limit_value:
                    break
                total += 1
                values.append(pt2)
    return len(set(values))
Ejemplo n.º 27
0
def smallest_in_amicable_chain(limit_value):
    primes = prime_factors(limit_value, False)
    print('primes_calculated!')
    sieve = sum_proper_divisors(limit_value, primes)
    print('Sieve calculated')
    max_len = 0
    max_chain = []
    visited = {}
    for i in range(2, limit_value + 1):
        if primes[i] == 0:
            ch = amicable_chain(i, limit_value, sieve, primes)
            if len(ch) > max_len:
                max_len = len(ch)
                max_chain = ch
        if i % 10**5 == 0:
            print(i, max_len, min(max_chain))
    return min(max_chain)
Ejemplo n.º 28
0
def get_n(limit_value):
    limit_sqrt = int(math.sqrt(limit_value))
    primes = prime_factors(limit_sqrt)
    ref = 3/7
    diff = float('inf')
    num = 0
    for i in range(limit_value,0,-1):
        pivot = int(3*(i/7))
        for j in range(pivot+2,pivot-2,-1):      
            tmp = j/i
            if tmp < ref:
                if ref-tmp<diff:
                    if set(find_prime_factors(j,primes))!=set(find_prime_factors(i,primes)):
                        diff = ref-tmp
                        num = j
                break
    return num
Ejemplo n.º 29
0
def euclid_pythagorean_triple():
    return_type = namedtuple('Data', 'abc a b c')
    primes = prime_factors(500)
    all_combinations = set([1])  # Not returned as a prime

    for i in range(1, len(primes) + 1):
        all_combinations.update(
            [product(tuple_) for tuple_ in combinations(primes, i)])

    valid_set = sorted(all_combinations)

    for k in valid_set:
        for n, i in enumerate(valid_set):
            for m in valid_set[i:]:
                if gcd(m, n) == 1 and k * m * (m + n) == 500:
                    return return_type(k**3 * 2 * m * (m**4 - n**4),
                                       k * (m**2 - n**2), 2 * m * n * k,
                                       k * (m**2 + n**2))
Ejemplo n.º 30
0
def primes_runs():
    primes = prime_factors(100005)
    m = {}
    n = {}
    s = {}
    digits= '0123456789'
    for d in digits:
        m[d]=0
        n[d]=0
        s[d]=0

    digits_number = 10

    visited = {}
    for d1 in digits:
        ar = d1*(digits_number-1)
        for d2 in ''.join([d for d in digits if d!=d1]):
            for idx in range(len(n)+1):
                num = ar[:idx]+d2+ar[idx:]
                if num[0]=='0':
                    continue
                num_int =int(num)
                if num not in visited:
                    visited[num]=1
                    if is_prime(num_int,primes):
                        max_checker(num,m,n,s)

    complement = ''.join([d for d in digits if m[d]!=digits_number-1])
    for d1 in complement:
        ar = d1*(digits_number-2)
        for d2 in ''.join([d for d in digits if d!=d1]):
            for idx in range(len(ar)+1):
                num = ar[:idx]+d2+ar[idx:]
                for d3 in ''.join([d for d in digits if d!=d1]):
                    for idx1 in range(len(num)+1):
                        num1 = num[:idx1]+d3+num[idx1:]
                        if num1[0]=='0':
                            continue
                        num1_int = int(num1)
                        if num1 not in visited:
                            visited[num1]=1
                            if is_prime(num1_int,primes):
                                max_checker(num1,m,n,s)
    return sum(s.values())
Ejemplo n.º 31
0
def prime_triplets(limit_value):
    primes = prime_factors(int(math.sqrt(limit_value)) + 1)
    total = 0
    values = []

    for pivot in range(len(primes)):
        for index in range(pivot):
            if (primes[pivot]**2 + primes[index]**3 +
                    primes[index]**4) >= limit_value:
                break
            triplet_variation = triplet_generation(primes[index],
                                                   primes[pivot], limit_value)
            total += len(triplet_variation)
            values += triplet_variation
        pivot_triplet = primes[pivot]**2 + primes[pivot]**3 + primes[pivot]**4
        if pivot_triplet < limit_value:
            total += 1
            values.append(pivot_triplet)
    return len(set(values))
Ejemplo n.º 32
0
def numbers_with_n_distinct_factors(num_distinct = 4):
    '''
    Find the first four integers each with four distinct prime factors
    problem 47
    '''
    Counter = collections.Counter
    number_factors = [[],[]]
    for i in range(2,1000000):
        first = [i**v for i,v in Counter(prime_factors(i)).items()]
        number_factors.append(first)
        if len(first) >= num_distinct:
            test_set = set(first)
            b = number_factors[-num_distinct:-1]
            expected = num_distinct * 2
            for c in b[::-1]:
                test_set.update(c)
                if len(test_set) < expected:
                    break
                expected += num_distinct
            else:
                return number_factors[-num_distinct:]
Ejemplo n.º 33
0
def pe3(n=600851475143):
	'''What is the largest prime factor of the number 600851475143?'''

	return max(utils.prime_factors(n))
Ejemplo n.º 34
0
def is_primitive_root(k, n):
    factors = prime_factors(n-1)
    return all(pow(k, (n-1)//f[0], n) > 1 for f in factors)
Ejemplo n.º 35
0
def solve():
    '''Main function'''

    num = 600851475143

    return max(prime_factors(num))
Ejemplo n.º 36
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?
"""

from utils import prime_factors


target = 600851475143
print max(prime_factors(target))
Ejemplo n.º 37
0
"""
Project Euler Problem 5
=======================

2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers
from 1 to 20?
"""

from collections import Counter
from utils import prime_factors

UPPER = 20

all_factors = Counter()
for i in range(1,UPPER+1):
  for prime, count in Counter(prime_factors(i)).items():
    if count>all_factors[prime]:
      all_factors[prime] = count

product = 1
for prime, count in all_factors.items():
  product = product*(prime**count)

print product
Ejemplo n.º 38
0
Archivo: p516.py Proyecto: kryptn/euler
def hamming(n,limit=None):
    phi = utils.euler_totient(n)
    pf = utils.prime_factors(phi, limit)
    if max(pf) <= 5:
        return True
    return False
Ejemplo n.º 39
0
#
# The prime factors of 13195 are 5, 7, 13 and 29.
#
# What is the largest prime factor of the number 600851475143 ?
#
#

from utils import prime_factors

VALUE = 600851475143
factors = prime_factors(VALUE)
print "Largest Prime factor is: %s" % factors[-1]
Ejemplo n.º 40
0
def prob3():
    return utils.prime_factors(600851475143)[-1::]