## Longest Consecutive Sequence Of Squares

### December 11, 2015

Some numbers can be represented as the sum of a sequence of consecutive squares; for instance, 595 = 6^{2} + 7^{2} + 8^{2} + 9^{2} + 10^{2} + 11^{2} + 12^{2}. Other numbers are not so representable.

Your task is to write a program that finds the longest consecutive sequence of squares that sums to a given number, or determines that no such sequence exists. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

in Python

In Python.

A Python solution using second order differences, so no multiplication:

Is it known whether any integer can be represented as the sum of consecutive squares in more than one way?

@Ernie: Yes; 25 can be represented by the sequences (3 4) or (5). Of these, the longest is (3 4), so it is the desired sequence. The suggested solution will always find the longest sequence because it starts from 1 and increases.

@Ernie: good question. Many numbers have 2 representations, as @praxis says, 25 is the smallest, 365 is the smallest that isn’t a perfect square.

Here’s a modified program that will show us numbers with 3 or more representations:

Output so far:

No quadruple representations so far.

Another question: do numbers with a sum of consecutive squares representation become scarcer as the numbers grow? Experimentally, they seem to, so there is a possibility there is a only a finite number (apart from the perfect squares of course).

To answer my own question: of course there are an infinite number as we can generate new ones as differences of sums of squares. Still not sure about the density. Something like N^(2/3) might be about about right (there are approximately N^(1/3) sums of squares less than N, and we can choose 2 of them to take the difference).

Here is a quadruple representation: 5545037505 (480, 1210), (3570, 3612), (3613, 3654), (7442, 7451)

@Paul: Good stuff! How did you find that one? I’m guessing by generating all differences-of-sums-of-squares directly rather than checking each number for a representation.

Did some investigation of density, N^(2/3)/N seems about right, but I suspect my reasons for coming up with it in the first were bogus.

@Paul: BTW, I think you meant 554503705. Good stuff anyway.

@Matthew. Sorry for the typo. I first generate the cumulative sum of squares. Then simply loop over the start and the end indeces and fill a dictionary. The main problem is that the memory is filled up quickly. Therefore I limit the range for the dict.

Java Script