"和爲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;
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章