Skip to content

Commit b3ae392

Browse files
Kush1101cclauss
andauthored
Created problem_34 in project_euler (#2305)
* Create __init__.py * Add files via upload * Rename solution.py.py to solution.py * Delete __init__.py * Update and rename solution.py to sol1.py * Update sol1.py * Create __init__.py * Update __init__.py * Delete __init__.py * Add files via upload * Update __init__.py * Add #\n * Update sol1.py Incorporates the proposed changes * Update sol1.py * Update sol1.py * Update project_euler/problem_34/sol1.py Co-authored-by: Christian Clauss <[email protected]> * Update project_euler/problem_34/sol1.py Co-authored-by: Christian Clauss <[email protected]> * Update project_euler/problem_34/sol1.py Co-authored-by: Christian Clauss <[email protected]> * Update project_euler/problem_34/sol1.py Co-authored-by: Christian Clauss <[email protected]> * Update sol1.py * Update sol1.py * Update sol1.py * Use int(n) instead of floor(n) Co-authored-by: Christian Clauss <[email protected]>
1 parent d687030 commit b3ae392

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

project_euler/problem_34/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#

project_euler/problem_34/sol1.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
3+
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
4+
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
5+
"""
6+
7+
8+
def factorial(n: int) -> int:
9+
"""Return the factorial of n.
10+
>>> factorial(5)
11+
120
12+
>>> factorial(1)
13+
1
14+
>>> factorial(0)
15+
1
16+
>>> factorial(-1)
17+
Traceback (most recent call last):
18+
...
19+
ValueError: n must be >= 0
20+
>>> factorial(1.1)
21+
Traceback (most recent call last):
22+
...
23+
ValueError: n must be exact integer
24+
"""
25+
26+
if not n >= 0:
27+
raise ValueError("n must be >= 0")
28+
if int(n) != n:
29+
raise ValueError("n must be exact integer")
30+
if n + 1 == n: # catch a value like 1e300
31+
raise OverflowError("n too large")
32+
result = 1
33+
factor = 2
34+
while factor <= n:
35+
result *= factor
36+
factor += 1
37+
return result
38+
39+
40+
def sum_of_digit_factorial(n: int) -> int:
41+
"""
42+
Returns the sum of the digits in n
43+
>>> sum_of_digit_factorial(15)
44+
121
45+
>>> sum_of_digit_factorial(0)
46+
1
47+
"""
48+
return sum(factorial(int(digit)) for digit in str(n))
49+
50+
51+
def compute() -> int:
52+
"""
53+
Returns the sum of all numbers whose
54+
sum of the factorials of all digits
55+
add up to the number itself.
56+
>>> compute()
57+
40730
58+
"""
59+
return sum(
60+
num
61+
for num in range(3, 7 * factorial(9) + 1)
62+
if sum_of_digit_factorial(num) == num
63+
)
64+
65+
66+
if __name__ == "__main__":
67+
print(compute())

0 commit comments

Comments
 (0)