HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Divide an integer into the sum of consecutive positive numbers

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
dividetheintonumberssumpositiveintegerconsecutive

Problem

Today I am trying to solve an classical problem:


For any $n\in \Bbb{N}^+$, If it can be represent as the sum of consecutive positive numbers, find out them.

For example:

$$15 = 1+2+3+4+5$$
$$15=4+5+6$$
$$15=7+8$$

And I have an ugly method, its time complexity is: $O(n^2)$. I use two for loop to exhaustion all possibilities.

for(int i=1;i<n;i++)
{
    for(int j=i;j<n;j++)
    {
        sum+=j;
        if(sum==n)
        {   //print out the answer
            for(int l=i;l<=j;l++)
            {
                cout << l << "+ ";
            }
            cout << endl;
            break;
        }
    }
    sum = 0;
}


I think there may be exist a more effective solution, But I am failed until now. Please help me.

for i from 1 to n
{
   for j from i to n
   {
       sum <- sum + j
       if sum equal n
       {
          print the result
       }
   }
   sum <- 0
}

Solution

Here's an alternative way of viewing D.W.'s hint. Using the formula $\sum_{i=1}^m i = \frac{(m+1)m}{2}$,
$$ \sum_{i=a+1}^b i = \sum_{i=1}^b i - \sum_{i=1}^a i = \frac{b^2+b}{2} - \frac{a^2+a}{2} = \frac{(b-a)(b+a+1)}{2}. $$
Given a factorization $2n = xy$, we can solve the system $x = b-a$, $y = b+a+1$. The result is $b = (y+x-1)/2$, $a = (y-x-1)/2$. So we want $x,y$ to have different parities (this is only a restriction if $n$ is even) and $y \geq x+1$. Also, $b \neq a+1$ corresponds to $x \neq 1$.

For example, for $n = 15$ we have $2n = 30 = 2 \cdot 15 = 3 \cdot 10 = 5 \cdot 6$. These correspond to the following pairs $(a,b)$:
$$ (6,8),(3,6),(0,5). $$
These, in turn, correspond to the representations
$$
15 = 7+8 = 4+5+6 = 1+2+3+4+5.
$$

This leads to an $O(n)$ algorithm (in the appropriate computation model). I'll let you work out the remaining details.

Context

StackExchange Computer Science Q#24552, answer score: 8

Revisions (0)

No revisions yet.