一道百度算法比赛题
请编写程序,根据输入的任何一个正整数,找出符合这种要求的所有连续正整数序列。
输入数据:一个正整数,以命令行参数的形式提供给程序。
输出数据:在标准输出上打印出符合题目描述的全部正整数序列,每行一个序列,每个序列都从该序列的最小正整数开始、以从小到大的顺序打印。如果结果有多个序列,按各序列的最小正整数的大小从小到大打印各序列。此外,序列不允许重复,序列内的整数用一个空格分隔。如果没有符合要求的序列,输出“NONE”。
例如,对于15,其输d出结果是:
1 2 3 4 5
4 5 6
7 8
对于16,其输出结果是:
NONE
求各路高手贴代码,记得写注释!
[解决办法]
public static void main(String[] args) {
int inputNum = 21;
getPlus_3();
}
/**
* 通过数学方法来提高效率
*/
public static void getPlus_3() {
int value = 21;
for (int count = 2; value / count - (count / 2) >= 0; count++) {
if (value * 2 % count == 0) {
int min = (value * 2 / count - count + 1) / 2;
if (min > 0) {
int max = min + count - 1;
System.out.println(getStr(min, max));
}
}
}
}
/**
* 从begin到end,打印序列
*/
public static String getStr(int begin, int end) {
StringBuffer sb = new StringBuffer();
for (int i = begin; i <= end; i++) {
sb.append(i + " ");
}
return sb.toString();
}
private static Map<Integer, Integer> getList(int X) {
Map<Integer, Integer> result = new TreeMap<Integer, Integer>();
for (int m = 2; m < Math.sqrt(X+X); m++) {
int n = (2 * X / m - m + 1) / 2;
if ((n + n + m - 1) * (m) / 2 == X) {
result.put(n, m);
}
}
return result;
}