File tree 2 files changed +56
-0
lines changed
project_euler/problem_125
2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Problem 125: https://projecteuler.net/problem=125
3
+
4
+ The palindromic number 595 is interesting because it can be written as the sum
5
+ of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2.
6
+
7
+ There are exactly eleven palindromes below one-thousand that can be written as
8
+ consecutive square sums, and the sum of these palindromes is 4164. Note that
9
+ 1 = 0^2 + 1^2 has not been included as this problem is concerned with the
10
+ squares of positive integers.
11
+
12
+ Find the sum of all the numbers less than 10^8 that are both palindromic and can
13
+ be written as the sum of consecutive squares.
14
+ """
15
+
16
+
17
+ def is_palindrome (n : int ) -> bool :
18
+ """
19
+ Check if an integer is palindromic.
20
+ >>> is_palindrome(12521)
21
+ True
22
+ >>> is_palindrome(12522)
23
+ False
24
+ >>> is_palindrome(12210)
25
+ False
26
+ """
27
+ if n % 10 == 0 :
28
+ return False
29
+ s = str (n )
30
+ return s == s [::- 1 ]
31
+
32
+
33
+ def solution () -> int :
34
+ """
35
+ Returns the sum of all numbers less than 1e8 that are both palindromic and
36
+ can be written as the sum of consecutive squares.
37
+ """
38
+ LIMIT = 10 ** 8
39
+ answer = set ()
40
+ first_square = 1
41
+ sum_squares = 5
42
+ while sum_squares < LIMIT :
43
+ last_square = first_square + 1
44
+ while sum_squares < LIMIT :
45
+ if is_palindrome (sum_squares ):
46
+ answer .add (sum_squares )
47
+ last_square += 1
48
+ sum_squares += last_square ** 2
49
+ first_square += 1
50
+ sum_squares = first_square ** 2 + (first_square + 1 ) ** 2
51
+
52
+ return sum (answer )
53
+
54
+
55
+ if __name__ == "__main__" :
56
+ print (solution ())
You can’t perform that action at this time.
0 commit comments