和为n的连续正序列

 

 

/**
	 * 和为n的连续正数列
	 * 定义序列start=1,end=2,当和sum大于n时,则先将和sum减去最小的start,并移动start++,若是小于n,则sum+=end
	 * ,end++,若是等于则输出[start,end],并使sum加上end,++end
	 * 
	 * @param n
	 */
	public static void sequenceN(int n) {
		int start = 1, end = 2, mid = (n + 1) / 2, sum = start + end;
		while (start < mid) {
			if (sum > n) {
				sum -= start;
				start++;
			} else if (sum < n) {
				end++;
				sum += end;
			} else {
				for (int i = start; i <= end; i++) {
					System.out.print(i + " ");
				}
				System.out.println();
				end++;
				sum += end;
			}
		}
	}

 

posted @ 2012-07-23 10:45  qingyezhu  阅读(210)  评论(0编辑  收藏  举报