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
The main logic of the program is as follows:
For every integer i less than half of the input number (since once the half path is crossed the sum will always exceeds the input number), add consutive integers till the sum
is either equal to the input number or exceeds it. If the sum equals the input number print the
consecutive integers starting from i. See the code below
while(sum !=natural_numb) {
sum +=k;
if(sum>=natural_numb)
break;
k++;
counter++;
}
k++ helps to add consecutive integers to the sum and counter counts the number of times
the addition operation takes place. Rest is reveled by the code itself.
import java.util.*;
public class ISC2006Q1 {
public static void main(String[] args) {
int N;
Scanner in = new Scanner(System.in);
System.out.println("Enter the natural number:");
N = in.nextInt();
IntegerSum obj = new IntegerSum(N);
System.out.println("OUTPUT:");
obj.consecutiveIntegerSum();
in.close();
}
}
class IntegerSum {
public void consecutiveIntegerSum() {
int counter,sum,k;
flag=false;
for(int i=1;i<=natural_numb/2;i++) {
sum=0;
counter=0;
k=i;
while(sum !=natural_numb) {
sum +=k;
if(sum>=natural_numb)
break;
k++;
counter++;
}
if(sum==natural_numb) {
flag=true;
for(int j=0;j<counter+1;j++) {
if(j==counter)
System.out.print((j+i)+"="+natural_numb);
else
System.out.print((j+i)+"+");
}
System.out.println();
}
}
if(flag==false)
System.out.println(natural_numb+" cannot be written as sum of consecutive natural
numbers:");
}
IntegerSum(int N){
natural_numb=N;
}
private int natural_numb;
private boolean flag;
}