输入一个正整数n,输出所有和为n的连续正整数序列

  public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.print("please input a positive integer:");
            int n = sc.nextInt();
            if(n <= 2) break;
            int count = getSubInteger(n);
            
            System.out.println(n + "共有 " + count + " 种连续分解!");
            
            System.out.println("=========================");
        }
        sc.close();
    }
    
    public static int getSubInteger(int n) {
        int min = 1;
        int max = 1;
        int sum = 0;
        int count = 0;
        while (min <= (n-1) / 2 ) {
            if (sum == n) {
                System.out.print(n + " = ");
                for (int k = min; k < max; k++) {
                    if (k < max - 1)
                        System.out.print(k + " + ");
                    else
                        System.out.print(k);
                }
                System.out.println();
                count++;
                min++;
                max = min;
                sum = 0;
            } else if (sum > n) {
                min++;
                max = min;
                sum = 0;
            } else {
                sum = sum + max;
                max++;
            }
        }
        return count;
    }

 

posted @ 2018-11-17 21:44  束发读诗书  阅读(2095)  评论(0编辑  收藏  举报