File tree 2 files changed +68
-0
lines changed
2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ #
Original file line number Diff line number Diff line change
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 ())
You can’t perform that action at this time.
0 commit comments