sum of all consecutive integers that add up to N

We know that we can not find consecutive numbers above N/2 that adds up to N.So we will  start from start=1 till end=N/2 and check for every consecutive sequence whether it adds up to N or not.If it is then we print that sequence and start looking for the next sequence by incrementing start point.
Given a number N.We have to print all possible sums of consecutive numbers that add up to N. 
Examples:
Input : 100 
Output : 
9 10 11 12 13 14 15 16 
18 19 20 21 22 
Input :125 
Output :
8 9 10 11 12 13 14 15 16 17 
23 24 25 26 27 
62 63
Code is given below-


#include

using namespace std;
int main(void)
{
int end;
float N=125.0;
int start;
int answers[1024];

end = ceil(N / 2); // note that we dont ever have to sum numbers > ceil(N/2)
//set start=1
start = 1;
//repeat the loop from bottom to half
while (start < end)
{
int i;
size_t answer_n;
int sum;

sum = 0;
answer_n = 0;
//check if there exist any sequence from bottom to half which adds up to N
for (i = start; i <= end; i++)
{
answers[answer_n++] = i;
sum = sum + i;
//if sum=N this means consecutive sequence exist
if (sum == N)
{
// found consecutive numbers! print them
int j;
for (j = 0; j < answer_n; j++)
{
printf("%d ", answers[j]);
}
printf("\n");
break;
}
//if sum increases N then it can not exist in the consecutive sequence starting from bottom
if(sum>N)
break;
}
sum = 0;
start++;
}

return 0;
}

Get c++ books here

Comments :

Post a Comment