Created
February 23, 2012 12:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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