The palindromic number is interesting because it can be written as the sum of consecutive squares:
There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is .
Note that has not been included, as this problem is concerned with the squares of positive integers.
Find the sum of all the numbers less than that are both palindromic and can be written as the sum of consecutive squares.
Our approach to the problem involves defining two functions.
A function to check if a number is a palindrome.
A function that returns the sum of a set of numbers less than the argument that is palindromic and can be written as consecutive square sums.
A palindrome is a word or number that reads the same when reversed, e.g., 1001, civic, etc.
is_palindromic() function checks if a number is a palindrome by converting the number to a string, slicing backward, which gives the reverse of the number, and checking if the reversed number is equal to the number.
is_sum() function gets the sum of the palindromes that can be written as consecutive square sums, e.g., can be written as .
is_sum() gets the sum of all numbers that can be written as consecutive square sums and checks whether it is palindromic, less than the argument, and that it isn’t a perfect square as they are excluded.
is_sum() returns the sum set of numbers that passed the given condition.
The sequence of consecutive square sums follows the pattern as shown below.
def is_palindromic(num): a = str(num) reverse = a[::-1] if a == reverse: return num def is_sum(n): limit = int(n ** 0.5) #The total number of sum squares pals = set() #An empty set to add our palindromes for i in range(1, limit): sum2 = 0 for j in range(i, limit): sum2 = sum2 + j ** 2 #check if sum2 is a palindrome, not a perfect square #and not greater than the passed argument if is_palindromic(sum2) and (sum2 ** 0.5).is_integer() == False and sum2 < n: pals.add(sum2) return sum(pals) print(is_sum(10 ** 8))
The code works fine but runs slower for high values of ; it can be improved to run faster.
View all Courses