# Distinct primes factors (Euler Problem 47)¶

Back to overview.

https://projecteuler.net/problem=47

The first two consecutive numbers to have two distinct prime factors are:

14 = 2 × 7

15 = 3 × 5

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 each. What is the first of these numbers?

In [46]:

    def sieve_of_eratosthenes(number):
        primes = []
        prospects = [n for n in range(2, number + 1)]
        while prospects:
            p = prospects[0]
            prospects = [x for x in prospects if x % p != 0]
            primes.append(p)
            if p * p > number:
                break
        return primes + prospects

    import math

    def get_prime_factors(n):
        ps = sieve_of_eratosthenes(n)
        fs = []
        for p in ps:
            if n % p == 0:
                fs.append(p)
            while n % p == 0:
                n = n // p
        return fs

    def trial_division(n):
        a = []
        if n % 2 == 0:
            a.append(2)
        while n % 2 == 0:
            n //= 2
        f = 3
        while f * f <= n:
            if n % f == 0:
                a.append(f)
                while n % f == 0:
                    n //= f
            else:
                f += 2
        if n != 1:
            a.append(n)
        return a

    assert(get_prime_factors(14) == [2, 7])
    assert(get_prime_factors(644) == [2, 7, 23])

    print(trial_division(126))

    [2, 3, 7]

In [54]:

    s = []
    for n in range(2, 1000000):
        if len(trial_division(n)) == 4:
            s.append(n)
        else:
            s = []
        if len(s) == 4:
            s = s[0]
            break

    print(s)
    assert(s == 134043)

    134043

In [ ]: