首页 > 代码库 > java任意n以内连续的和等于n

java任意n以内连续的和等于n

import java.util.Scanner;

/**
 * Created by Admin on 2017/3/25.
 */
public class test01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n=1;
        while (n !=-1){
            n = scanner.nextInt();
            int min = 1, max = 1, sum = 1;
        while (min <= n / 2 + 1) {
            if (sum == n) {
                for (int i = min; i <= max; i++)
                    System.out.print(i + " ");
                System.out.println();
                sum -= min;
                min++;
                max++;
                sum += max;
            }
            if (sum > n) {
                sum -= min;
                min++;
            } else {
                max++;
                sum += max;
            }
        }
    }
    }
}

技术分享

 

java任意n以内连续的和等于n