## Consecutive Sums

### February 12, 2019

Given the positive integer 15, there are three ways to take consecutive positive integers that sum to 15: 1+2+3+4+5, 4+5+6 and 7+8.

Your task is to write a program that, given a positive integer, finds all the ways that consecutive positive integers can sum to the target integer. 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.

Advertisements

Quite a nifty one, reminiscent of Euler… Here is my take on it, using Julia 1.0:

function SumOfConsecutiveNumbers(x::Int64)

n = div(x,2)

n1 = n + 1

S = Array{Array{Int64}}(undef, n)

c = 0

end

Cheers!

There is another way to solve the problem:

Let the series be k, k+1, k+2, …k+n = N

Then k(n+1) + n(n+1)/2 = N (1)

or (n+1)(n+2k) = 2N (2)

Thus we find all the divisors of 2N and solve for n and k. Some solutions do not give an integral value for k are therefore not valid.

@Ernie: nice solution. Given 2N = ab, k is integral when a and b are of different parities, so we have a (non-trivial) series for N for each odd divisor of N (and this explains Praxis’s observation on 10^n,whose odd divisors are 5^i, 1 <= i <= n).

Here’s some actual code for that solution:

Interval is [k..k+n] for n > 0, sum is k*(n+1)+ n(n+1)/2 = (n+1)(n+2k)/2

so 2N = ab with parity of a and b different. The odd one of a and b must

factor N, and any odd divisor of N will result in an interval sum:

An equivalent function to test cosums – the sum of integers between n and m (inclusive, with n <= m) is (m-n+1)(m+n)/2 decreasing n increases this product and decreasing m decreases the product:

And for a test, print out the numbers where there are more solutions than any lower number:

Looks like we are generating https://oeis.org/A053624, Highly Composite Odd Numbers:

A quick and dirty Haskell version.

Hello Everyone,

This is my first post. I am very new to programming and wanted to improve with some problem solving. Here is my solution using Javascript. I definitely did not make the output pretty. Hope this post works. Thanks

Can’t seem to post my entry

yyy

What in the name of sanity happened to my lovely indentation?

https://en.support.wordpress.com/code/posting-source-code/

ie. do something like this:

@richard: I think I got the formatting fixed properly. Let me know if I did something wrong. The easiest way to post code is just to wrap it with pre … /pre tags.

Here’s a solution in C.

Example Usage: