给定一个正整数,输出连续递增的和为该整数的序列

public class SequenceDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数");
        while (scanner.hasNext()) {
            int input = scanner.nextInt();
            getIncrNum(input);
            System.out.println("请输入一个整数");
        }
    }

    public static void getIncrNum(int num) {
        StringBuilder stringBuilder = new StringBuilder();
        int mid = (num + 1) / 2;
        for (int i = 1; i <= mid; i++) {
            for (int j = i + 1; j <= mid; j++) {
                stringBuilder.setLength(0);
                int sum = 0;

                // 从 i-j求和
                for (int k = i; k < j + 1; k++) {
                    sum += k;
                    stringBuilder.append(k + " ");
                }
                
                if (sum == num) {
                    System.out.println("序列数为:" + stringBuilder.append("= " + num));
                }
            }

        }
    }
}

运行结果如下:

请输入一个整数
15
序列数为:1 2 3 4 5 = 15
序列数为:4 5 6 = 15
序列数为:7 8 = 15
请输入一个整数
21
序列数为:1 2 3 4 5 6 = 21
序列数为:6 7 8 = 21
序列数为:10 11 = 21

你可能感兴趣的:(数据结构,算法)