TheAlgorithms-Python
112 строк · 2.5 Кб
1"""
2Combinatoric selections
3
4Problem 47
5
6The first two consecutive numbers to have two distinct prime factors are:
7
814 = 2 × 7
915 = 3 × 5
10
11The first three consecutive numbers to have three distinct prime factors are:
12
13644 = 2² × 7 × 23
14645 = 3 × 5 × 43
15646 = 2 × 17 × 19.
16
17Find the first four consecutive integers to have four distinct prime factors each.
18What is the first of these numbers?
19"""
20
21from functools import lru_cache
22
23
24def unique_prime_factors(n: int) -> set:
25"""
26Find unique prime factors of an integer.
27Tests include sorting because only the set really matters,
28not the order in which it is produced.
29>>> sorted(set(unique_prime_factors(14)))
30[2, 7]
31>>> sorted(set(unique_prime_factors(644)))
32[2, 7, 23]
33>>> sorted(set(unique_prime_factors(646)))
34[2, 17, 19]
35"""
36i = 2
37factors = set()
38while i * i <= n:
39if n % i:
40i += 1
41else:
42n //= i
43factors.add(i)
44if n > 1:
45factors.add(n)
46return factors
47
48
49@lru_cache
50def upf_len(num: int) -> int:
51"""
52Memoize upf() length results for a given value.
53>>> upf_len(14)
542
55"""
56return len(unique_prime_factors(num))
57
58
59def equality(iterable: list) -> bool:
60"""
61Check equality of ALL elements in an interable.
62>>> equality([1, 2, 3, 4])
63False
64>>> equality([2, 2, 2, 2])
65True
66>>> equality([1, 2, 3, 2, 1])
67False
68"""
69return len(set(iterable)) in (0, 1)
70
71
72def run(n: int) -> list:
73"""
74Runs core process to find problem solution.
75>>> run(3)
76[644, 645, 646]
77"""
78
79# Incrementor variable for our group list comprehension.
80# This serves as the first number in each list of values
81# to test.
82base = 2
83
84while True:
85# Increment each value of a generated range
86group = [base + i for i in range(n)]
87
88# Run elements through out unique_prime_factors function
89# Append our target number to the end.
90checker = [upf_len(x) for x in group]
91checker.append(n)
92
93# If all numbers in the list are equal, return the group variable.
94if equality(checker):
95return group
96
97# Increment our base variable by 1
98base += 1
99
100
101def solution(n: int = 4) -> int:
102"""Return the first value of the first four consecutive integers to have four
103distinct prime factors each.
104>>> solution()
105134043
106"""
107results = run(n)
108return results[0] if len(results) else None
109
110
111if __name__ == "__main__":
112print(solution())
113