## Longest Sequence Of Consecutive Odd Integers

### October 20, 2015

Today’s exercise is to find the longest sequence of consecutive odd integers that add to a given sum. For instance, given the target 160701, the three consecutive odd integers 53565, 53567 and 53569 sum to 160701, but the 391 consecutive odd integers from 21 to 801 also sum to 160701, and are the longest sequence of consecutive odd integers to do so, so they are the correct answer.

Your task is to write a program to find the longest sequence of consecutive odd integers that add to a given sum. 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

Not the haskellest/most efficient implementation but…

Two solutions in Python. The functions powerset is from the itertools documentation, is_prime and rho_factors are from the Primes Essay (ProgrammingPraxis). isqrt is the integer square root.

The sum of the first k odd numbers is k*k. Therefore, the sum of consecutive odd numbers is the difference between two perfect squares. For example, 160701 = 160801 – 100 = 401*401 – 10*10 = sum from 11th odd number to the 401st odd number (note: the sum of the first 10 odd numbers are subtracted, so the 11th odd number is the first one in the sequence of consecutive odd numbers).

If the search starts from zero, then the first sequence found that sums to n is necessarily the longest, because adding another term at the high end will require subtracting at least one term from the small end.

N.B.: 53569 is the 26785th odd number and 53565 is the 26783rd odd number.

26785**2 – (26783 – 1)**2 = 717436225 – 717275524 = 160701

A couple more Python solutions, the first moves the starting position b up from 0, maintaining end position a with sum s such that s >= n (so it’s quite like Paul’s first solution). The second is based on Mike’s insight that we are after a factorization of n of the form (a+b)(a-b) and is basically Fermat’s factorization algorithm (it could be improved with a better check for t being an exact square):

A quick & dirty version in C++. (Although, except for iostreams, it is a C version as well.)

a production of my pencil and keyboard, supported by a bit of mathematics