Skip to content

Instantly share code, notes, and snippets.

@gnarula
Created February 23, 2012 12:49
Show Gist options
  • Save gnarula/1892686 to your computer and use it in GitHub Desktop.
Save gnarula/1892686 to your computer and use it in GitHub Desktop.
Display all the sequences of consecutive natural numbers that add up to n
/*
* Display all the sequences of consecutive natural numbers that add up to n
*
* @author Gaurav Narula
*
* */
public class consecadd {
private int n;
public consecadd(int n) {
this.n = n;
}
public void getSeries() {
for(int i = 1; i < n; i++) {
String temp = "" + i;
int sum = i;
for(int j = i + 1; j <=n; j++) {
if(sum > n)
break;
if(sum == n) {
System.out.println(temp);
break;
}
sum += j;
temp += " + " + j;
}
}
}
public static void main(String[] args) {
consecadd ob = new consecadd(9);
ob.getSeries();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment