Skip to content

Commit c938e73

Browse files
authored
Added solution for Project Euler problem 129. (TheAlgorithms#3113)
* Added solution for Project Euler problem 129. * Added doctest for solution() in project_euler/problem_129/sol1.py * Update formatting. Reference: TheAlgorithms#3256 * More descriptive function and variable names, more doctests.
1 parent 28d33f4 commit c938e73

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

project_euler/problem_129/__init__.py

Whitespace-only changes.

project_euler/problem_129/sol1.py

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

0 commit comments

Comments
 (0)