- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathsol1.py
57 lines (46 loc) · 1.52 KB
/
sol1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Problem 125: https://projecteuler.net/problem=125
The palindromic number 595 is interesting because it can be written as the sum
of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2.
There are exactly eleven palindromes below one-thousand that can be written as
consecutive square sums, and the sum of these palindromes is 4164. Note that
1 = 0^2 + 1^2 has not been included as this problem is concerned with the
squares of positive integers.
Find the sum of all the numbers less than 10^8 that are both palindromic and can
be written as the sum of consecutive squares.
"""
LIMIT=10**8
defis_palindrome(n: int) ->bool:
"""
Check if an integer is palindromic.
>>> is_palindrome(12521)
True
>>> is_palindrome(12522)
False
>>> is_palindrome(12210)
False
"""
ifn%10==0:
returnFalse
s=str(n)
returns==s[::-1]
defsolution() ->int:
"""
Returns the sum of all numbers less than 1e8 that are both palindromic and
can be written as the sum of consecutive squares.
"""
answer=set()
first_square=1
sum_squares=5
whilesum_squares<LIMIT:
last_square=first_square+1
whilesum_squares<LIMIT:
ifis_palindrome(sum_squares):
answer.add(sum_squares)
last_square+=1
sum_squares+=last_square**2
first_square+=1
sum_squares=first_square**2+ (first_square+1) **2
returnsum(answer)
if__name__=="__main__":
print(solution())