write a prog to input an integer x? wheer x>0?for
integer x,the program as to convert it into sum of
consecutive positive integters/
4 example the sum of interger 10=1+2+3+4.
the total number of consecutive positive integers
should be maximum example 9=2+3+4 and 9=4+5 but 9=2+3+4 is valid
some integer such as 4 cannot be represented
as a sum of consecutive positive integers.
in that case output is no answer
----------------------------------------------------------------------------------------------------------------------
# include <iostream.h>
int main()
{
int num; // to get the number from user.
int sum = 0; //To sum of consecutive numbers.
int flag = 0; // To verify whether reqd sum is get or not
int loop; // for loop
int start; // To remember the starting of consecutive number.
char numbers[100];
cout << "Enter a number greater than 0: ";
cin >> num;
int loopstart = 1; // for starting of loop.
while (loopstart < num) //Loop to change the starting of consecutive numbers.
{
sum = 0; //Sum of consecutive numbers.
for (loop = loopstart; loop < num; loop++) //Loop to get the sum of consecutive numbers until the sum is get
{
sum = sum + loop;
if (sum == num) //if sum of consecutive number matches with the entered number.
{
flag = 1;
start = loopstart; // to remember the starting of number.
loopstart = num; // to come out while loop
break; //TO come out for loop
}
}
loopstart =loopstart + 1;
}
if (flag == 1)
{
cout << num << "=";
int j;
int arr = 0;
for (j = start; j<= loop;j++)
{
if (j < (loop)) // Print numbers followed by plus sign
{
cout << j << "+";
}
else // It will print last number without plus sign
{
cout << j << endl ;
}
}
}
else
{
cout << "Not Possible";
}
system ("PAUSE");
return 0;
}