题目:输入一个正数s,打印出所有和为s 的连续正数序列(至少两个数)。
代码如下:
package demo;
import java.util.ArrayList;
import java.util.List;
/**
* 和为s的连续正数序列
*
* @author xiangdonglee
*
*/
public class Test41_2 {
public static List<List<Integer>> findContinuousSequence(int sum) {
List<List<Integer>> result = new ArrayList<>();
if (sum < 3) {
return result;
}
int small = 1;
int big = 2;
int middle = (1 + sum) / 2;
int curSum = small + big;
while (small < middle) {
if (curSum == sum) {
List<Integer> list = new ArrayList<>(2);
for (int i = small; i <= big; i++) {
list.add(i);
}
result.add(list);
}
while (curSum > sum && small < middle) {
curSum -= small;
small++;
if (curSum == sum) {
List<Integer> list = new ArrayList<>(2);
for (int i = small; i <= big; i++) {
list.add(i);
}
result.add(list);
}
}
big++;
curSum += big;
}
return result;
}
public static void main(String[] args) {
test2();
}
private static void test2() {
System.out.println("和为1的连续正数序列:" + findContinuousSequence(1));
System.out.println("和为3的连续正数序列:" + findContinuousSequence(3));
System.out.println("和为4的连续正数序列:" + findContinuousSequence(4));
System.out.println("和为9的连续正数序列:" + findContinuousSequence(9));
System.out.println("和为15的连续正数序列:" + findContinuousSequence(15));
System.out.println("和为100的连续正数序列:" + findContinuousSequence(100));
}
}