zoukankan      html  css  js  c++  java
  • 百度程序题目连续数问题 另解


    /**
     * 百度之星程序大赛第一题
     * @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
    */

  • 相关阅读:
    Gitlab使用腾讯企业邮箱
    查看Binlog内容
    微信小游戏手记
    clickhouse手记
    腾讯云手记
    go框架gin
    go idea debug
    go手记
    crontab手记
    Laravel-cors 跨域
  • 原文地址:https://www.cnblogs.com/chaohi/p/2330348.html
Copyright © 2011-2022 走看看