"和为n的连续整数序列"的Java实现

package test20121006;

public class AddToN {
	private int N;
	private int[] array;

	public AddToN(int N) {
		this.N = N;
		int arrayLength = N / 2 + 5;
		// if (this.N % 2 == 0) {
		// arrayLength = N / 2 + 1;
		// } else {
		// arrayLength = N / 2 + 2;
		// }
		array = new int[arrayLength];
		for (int i = 1; i < arrayLength; i++) {
			array[i] = i;
		}
	}

	public void findSubsequence() {
		///int subNum = 0;
		int first = 2;
		int second = 1;
		int sum = this.array[second] + this.array[first];
		while (second < first) {
			if (sum < this.N) {
				first++;
				sum += this.array[first];
			} else if (sum > this.N) {
				sum -= this.array[second];
				second++;
			} else {
				System.out.println(second + "	" + first);
				sum -= this.array[second];
				second++;
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		AddToN atn = new AddToN(50);
		atn.findSubsequence();

	}

	public int getN() {
		return N;
	}

}

点赞