我是靠谱客的博主 醉熏金鱼,这篇文章主要介绍求和为s的连续正整数序列,现在分享给大家,希望可以做个参考。

题目:

输入一个正整数s,打印出所有和为s的连续正整数序列(至少包含两个数字)

样例输入:
21

样例输出:
1 2 3 4 5 6
6 7 8
10 11

Code:

public class list {



    public void printList(int a, int b) {
        for (int i = a; i <= b; i++) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
    public void sumList(int s) {
        int start = 1;
        int end = 2;
        int half = (s + 1) / 2;
        int sum = start + end;
        while (start < half) {
            if (sum == s) {
                sum = sum - start;
                printList(start, end);
                start++;
                end++;
                sum = sum + end;
            } else if (sum < s) {
                end++;
                sum+=end;
            } else {
                sum-=start;
                start++;
            }
        }
    }

    @Test
    public void testList() {
        sumList(21);
    }

}

最后

以上就是醉熏金鱼最近收集整理的关于求和为s的连续正整数序列的全部内容,更多相关求和为s内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(138)

评论列表共有 0 条评论

立即
投稿
返回
顶部