Any Positive Integer can be represented in the form of Summation of few consecutive Natural Numbers.
e.g., Say number is 27.
then it can be represented as
13 + 14
8 + 9 + 10
2 + 3 + 4 + 5 + 6 + 7
So, the following program will take the positive number and show all combination that can make the number as a Summation.
import java.lang.*; import java.io.*; public class NumSum { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader ( new InputStreamReader(System.in)); System.out.print("\n Enter a Positive Number:: "); int n=Integer.parseInt(in.readLine()); String seq = new String(); if(n>0) { for(int i=(n/2)+1; i>=1; i--) { boolean f=true; int s=n; int j=i; for(; j>1 || s>=0; j--) { s-=j; if(s==0) { f=false; break; } } if(!f) { System.out.println(); for( ; j<i; j++) { System.out.print(j + " + "); } System.out.print(j); } } } } }
Note: The file name must be NumSum.java
Comments