百度程序题目连续数问题 另解


/**
 * 百度之星程序大赛第一题
 * @author tiger
 * @date : 2010年5月19日
 */
public class baidu {

 /**
  * 返回从i到j的和
  * 等差数列求和公式
  */
 private int qiuhe(int i, int j)
 {
  return ((i + j) * (j - i + 1)) / 2;
 }
 
 /**
  * 主要逻辑在这里
  */
 private void action(int n)
 {
  int m = n / 2 +1;
  for (int i = 1; i <= m; i++) {
   for (int j = i + 1; j <= m; j++) {
    if(qiuhe(i,j) == n)
    {
     print(i,j,n);
    }
   }
  }
 }
 
 /**
  * 输出结果
  */
 private void print(int i, int j, int n)
 {
  String str = "";
  for (int k = i; k <= j; k++) {
   str += k + " + ";
  }
  str = str.substring(0, str.length() - 3) + " = " + n;
  System.out.println(str);
 }
 
 /**
  * 程序入口
  */
 public static void main(String[] args) {
  new baidu().action(120);
 }
}

/*打印结果如下:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120
22 + 23 + 24 + 25 + 26 = 120
39 + 40 + 41 = 120
*/

原文地址:https://www.cnblogs.com/chaohi/p/2330348.html