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
}