连续正整数-穷举法解决

Problem Description

一个正整数有可能被表示为n(n>=2)个连续正整数之和,如:

15=1+2+3+4+5

15=4+5+6

15=7+8

编程实现输入任意一个正整数,找出符合上面要求的所有连续正整数序列。

Input Description

输入任意一个正整数

Output Description

输出所有满足要求的连续正整数序列,要求每行输出一个序列,每个序列都从最小正数开始,从小到大顺序输出,如果没有符合要求的序列,则输出“NONE”。

Sample Input

15

Sample Output

1 2 3 4 5 
4 5 6 
7 8 
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n=scan.nextInt();
		int start,end=0;
		boolean temp=false;
		for(int i=1;i<=n/2;i++) {
			start=i;
			int sum=0;
			sum+=i;
			while(i<=n/2+1) {
				i++;
				sum+=i;
				if(sum==n) {
					end=i;
					temp=true;
					for(int k=start;k<=end;k++) {
						System.out.print(k+" ");
					}
					System.out.println();
					break;
				}
			}
			i=start;
		}
		if(temp==false) {
			System.out.println("NONE");
		}
		scan.close();
	}

}

 

你可能感兴趣的:(算法)