Skip to content

Commit 74a915c

Browse files
committed
Added solution for Project Euler problem 145
1 parent 77b243e commit 74a915c

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

project_euler/problem_145/__init__.py

Whitespace-only changes.

project_euler/problem_145/sol1.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
"""
2+
Problem 145: https://projecteuler.net/problem=145
3+
4+
Name: How many reversible numbers are there below one-billion?
5+
6+
Some positive integers n have the property that the
7+
sum [ n + reverse(n) ] consists entirely of odd (decimal) digits.
8+
For instance, 36 + 63 = 99 and 409 + 904 = 1313.
9+
We will call such numbers reversible; so 36, 63, 409, and 904 are reversible.
10+
Leading zeroes are not allowed in either n or reverse(n).
11+
12+
There are 120 reversible numbers below one-thousand.
13+
14+
How many reversible numbers are there below one-billion (10^9)?
15+
16+
17+
Solution:
18+
19+
Here a brute force solution is used to find and count the reversible numbers.
20+
21+
"""
22+
from __future__ import annotations
23+
24+
25+
def check_if_odd(sum: int) -> int:
26+
"""
27+
Check if the last digit in the sum is even or odd. If even return 0.
28+
If odd then floor devision by 10 is used to remove the last number.
29+
Process continues until sum becomes 0 because no more numbers.
30+
>>> check_if_odd(36)
31+
0
32+
>>> check_if_odd(33)
33+
1
34+
"""
35+
while sum > 0:
36+
if (sum % 10) % 2 == 0:
37+
return 0
38+
sum = sum // 10
39+
return 1
40+
41+
42+
def find_reverse_nr(nr: int) -> int:
43+
"""
44+
Reverses the given number. Does not work with number that end in zero.
45+
>>> find_reverse_nr(36)
46+
63
47+
>>> find_reverse_nr(409)
48+
904
49+
"""
50+
reverse = 0
51+
52+
while nr > 0:
53+
temp = nr % 10
54+
reverse = reverse * 10 + temp
55+
nr = nr // 10
56+
57+
return reverse
58+
59+
60+
def solution(nr: int) -> int:
61+
"""
62+
Loops over the range of numbers.
63+
Checks if they have ending zeros which disqualifies them from being reversable.
64+
If that condition is passed it generates the reveresed number.
65+
Then sum up n and reverse(n).
66+
Then check if all the numbers in the sum are odd. If true add to the answer.
67+
>>> solution(1000000000)
68+
608720
69+
>>> solution(1000000)
70+
18720
71+
>>> solution(1000000)
72+
18720
73+
>>> solution(1000)
74+
120
75+
"""
76+
answer = 0
77+
for x in range(1, nr):
78+
if x % 10 != 0:
79+
reversed_nr = find_reverse_nr(x)
80+
sum = x + reversed_nr
81+
answer += check_if_odd(sum)
82+
83+
return answer
84+
85+
86+
nr = 1000000000
87+
88+
if __name__ == "__main__":
89+
print(f"{solution(nr) = }")

0 commit comments

Comments
 (0)