Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


A Python approach to Project Euler palindromic sums

Ubaydah Abdulwasiu

Problem overview

The palindromic number 595595 is interesting because it can be written as the sum of consecutive squares:

62+72+82+92+102+112+12262 + 72 + 82 + 92 + 102 + 112 + 122

There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 41644164.

Note that 1=02+121 = 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 10810^8 that are both palindromic and can be written as the sum of consecutive squares.


Solution analysis

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.

The is_palindromic() is called in is_sum()

The 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.

The is_sum() function gets the sum of the palindromes that can be written as consecutive square sums, e.g., 7777 can be written as 42+52+624^2 + 5^2 + 6^2.

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.

%0 node_1631415194966 1 node_1631415249639 5 node_1631415228750 14 node_1 30 node_2 55 node_3 91 node_1632211462325 ...


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:

    return sum(pals) 

print(is_sum(10 ** 8))
The output passed the project euler's answer case

The code works fine but runs slower for high values of nn ; it can be improved to run faster.



View all Courses

Keep Exploring