TheAlgorithms-Python
57 строк · 1.5 Кб
1"""
2Project Euler Problem 129: https://projecteuler.net/problem=129
3
4A number consisting entirely of ones is called a repunit. We shall define R(k) to be
5a repunit of length k; for example, R(6) = 111111.
6
7Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there
8always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least
9such value of k; for example, A(7) = 6 and A(41) = 5.
10
11The least value of n for which A(n) first exceeds ten is 17.
12
13Find the least value of n for which A(n) first exceeds one-million.
14"""
15
16
17def least_divisible_repunit(divisor: int) -> int:
18"""
19Return the least value k such that the Repunit of length k is divisible by divisor.
20>>> least_divisible_repunit(7)
216
22>>> least_divisible_repunit(41)
235
24>>> least_divisible_repunit(1234567)
2534020
26"""
27if divisor % 5 == 0 or divisor % 2 == 0:
28return 0
29repunit = 1
30repunit_index = 1
31while repunit:
32repunit = (10 * repunit + 1) % divisor
33repunit_index += 1
34return repunit_index
35
36
37def solution(limit: int = 1000000) -> int:
38"""
39Return the least value of n for which least_divisible_repunit(n)
40first exceeds limit.
41>>> solution(10)
4217
43>>> solution(100)
44109
45>>> solution(1000)
461017
47"""
48divisor = limit - 1
49if divisor % 2 == 0:
50divisor += 1
51while least_divisible_repunit(divisor) <= limit:
52divisor += 2
53return divisor
54
55
56if __name__ == "__main__":
57print(f"{solution() = }")
58