A positive natural number, (for e.g. 27), can be represented as follows:
2+3+4+5+6+7
8+9+10
13+14
where every row represents a combination of consecutive natural numbers, which add up to 27.
Write a program which inputs a positive natural number N and prints the possible consecutive number combinations, which when added give N.
Test your program for the following data and some random data.
SAMPLE DATA
INPUT:
N = 9
OUTPUT:
4 + 5
2 + 3+ 4
INPUT:
N = 15
OUTPUT:
7 +8
1 +2+ 3+ 4+ 5
4 +5+ 6
INPUT:
N = 21
OUTPUT:
10+ 11
1+ 2+ 3+ 4+ 5+ 6
6+ 7+ 8
import java.io.*;
class ISC06PQ1
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number : "); //inputting the number
int n=Integer.parseInt(br.readLine());
int sum=0,c=0,j=0;
for(int i=1;i<n;i++)
{
sum=i;
j=i+1;
/* adding consecutive natural numbers till sum is less than the given number */
while(sum<n)
{
sum=sum+j;
j++;
}
/* when the above while condition is false, then either the sum is equal to
that number or is greater than that number
So, we will be printing the series of consecutive numbers only if the sum is
equal to that number*/
if(sum==n)
{
for(int k=i;k<j;k++)
{
if(k==i)
System.out.print(k);
else
System.out.print(" + "+k);
}
System.out.println();
}
}
}
}
2+3+4+5+6+7
8+9+10
13+14
where every row represents a combination of consecutive natural numbers, which add up to 27.
Write a program which inputs a positive natural number N and prints the possible consecutive number combinations, which when added give N.
Test your program for the following data and some random data.
SAMPLE DATA
INPUT:
N = 9
OUTPUT:
4 + 5
2 + 3+ 4
INPUT:
N = 15
OUTPUT:
7 +8
1 +2+ 3+ 4+ 5
4 +5+ 6
INPUT:
N = 21
OUTPUT:
10+ 11
1+ 2+ 3+ 4+ 5+ 6
6+ 7+ 8
import java.io.*;
class ISC06PQ1
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number : "); //inputting the number
int n=Integer.parseInt(br.readLine());
int sum=0,c=0,j=0;
for(int i=1;i<n;i++)
{
sum=i;
j=i+1;
/* adding consecutive natural numbers till sum is less than the given number */
while(sum<n)
{
sum=sum+j;
j++;
}
/* when the above while condition is false, then either the sum is equal to
that number or is greater than that number
So, we will be printing the series of consecutive numbers only if the sum is
equal to that number*/
if(sum==n)
{
for(int k=i;k<j;k++)
{
if(k==i)
System.out.print(k);
else
System.out.print(" + "+k);
}
System.out.println();
}
}
}
}