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

来源:互联网 发布:淘宝日本男装品牌 编辑:程序博客网 时间:2024/05/17 03:24
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 stubAddToN atn = new AddToN(50);atn.findSubsequence();}public int getN() {return N;}}

原创粉丝点击