题目
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
解题思路
(1)序列为连续且递增为1,构造高低位low,high,代表首项及尾项,项数为high-low+1,即可求出总和,总和小于sum,high自增;大于sum,low自增;等于sum时,返回次序列。
源代码
import java.util.ArrayList;
public class FindContinuousSequence {
private static ArrayList<ArrayList<Integer>> res = new ArrayList<>();
public static ArrayList<ArrayList<Integer>> FindCountinuousSequence(int sum) {
if (sum < 3)
return res;
int low = 1;
int high = 2;
while (low < high) {
int sum1 = (low + high) * (high - low + 1) / 2;//利用等差数列的求和公式:(首项+尾项)X项数/2
if (sum1 < sum)
high++;
if (sum1 > sum)
low++;
if (sum1 == sum) {
addresult(low, high);
low++;
}
}
return res;
}
private static void addresult(int low, int high) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = low; i <= high; i++)
arrayList.add(i);
res.add(arrayList);
}
public static void main(String[] args) {
System.out.println(FindCountinuousSequence(100));
}
}