【问题标题】:How to find the sum of n odd integers starting from 1? [closed]如何求从 1 开始的 n 个奇数之和? [关闭]
【发布时间】:2018-05-04 10:20:19
【问题描述】:

今天面试,不知道怎么回答这个问题……

给出一个递归算法,找出第一个n奇正整数之和。

例如:

如果n=3,则正整数为1+3+5,总和为9

【问题讨论】:

    标签: php algorithm sum integer


    【解决方案1】:

    使用递归是不必要的开销,但这满足要求:

    代码:(Demo)

    function sum_recursive($n){
        return ($n<<1)-1 + ($n>1 ? sum_recursive($n-1) : 0);
    }
    
    $number_of_odd_numbers=range(1,10);  // test cases
    foreach($number_of_odd_numbers as $n){  // iterate test cases
        echo "$n => " , sum_recursive($n) , "\n";
    }
    

    功能逻辑:

    • 因为$n 总是1 或更多,所以没有任何安全措施可以检查0
    • 在每次递归调用中,使用shift left bitwise operator(为了获得最佳性能)将$n 乘以2(一次)然后减1,然后将该数字添加到递归调用的返回值中。
    • $n 递减到1 时,停止递归并将0 添加到计算中。

    输出:

    1 => 1
    2 => 4
    3 => 9
    4 => 16
    5 => 25
    6 => 36
    7 => 49
    8 => 64
    9 => 81
    10 => 100
    

    抛开问题要求不谈,纯算术方法将非常快速且代码简洁(新学校风格只需 5 个字符):

    pow($n,2)  // pow() is the old-school call
    
    $n**2  // is new-school
    

    实现:(Demo)

    $number_of_odd_numbers=range(1,10);  // test cases
    
    foreach($number_of_odd_numbers as $n){  // iterate test cases
        echo "$n => " , pow($n,2) , "\n";
        //    ^^-input  ^^^^^^^^^--- square $n
    }
    

    输出:

    1 => 1     // 1
    2 => 4     // 1,3
    3 => 9     // 1,3,5
    4 => 16    // 1,3,5,7
    5 => 25    // 1,3,5,7,9
    6 => 36    // 1,3,5,7,9,11
    7 => 49    // 1,3,5,7,9,11,13
    8 => 64    // 1,3,5,7,9,11,13,15
    9 => 81    // 1,3,5,7,9,11,13,15,17
    10 => 100  // 1,3,5,7,9,11,13,15,17,19
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2021-04-23
      • 2016-01-21
      相关资源
      最近更新 更多