【问题标题】:CodeWars - Sum of odd Numbers - For loopCodeWars - 奇数之和 - For 循环
【发布时间】:2016-03-20 15:44:19
【问题描述】:

我尝试编写一段代码,接受输入“n”,计算第 n 行数字之和为奇数三角形,如下所示:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29

等等。所以对于n = 3,总和将是7 + 9 + 11,即27

我知道 n 不仅是行号,还等于该行上的数字数。所以n = 3 上面也有 3 个奇数。因此,我认为我可以得到该行的第一个数字,然后循环将前一个数字加二,然后求和。

我下面的代码不起作用,因此对于n=43 的输入,我的代码计算得出总和是3570,而它实际上等于79507

public static int rowSumOddNumbers(int n) {
    int firstNum = (2 * n) - 1;
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += (firstNum + 2);
    }
    return total;
}

我相信我的问题是我没有将前一个数字与当前数字 + 2 相加。是不是我需要存储前一个循环的结果而不是将其添加到当前循环的结果中?

任何帮助表示赞赏。

【问题讨论】:

  • 是什么让你想出(2 * n) - 1firstNum?这显然是错误的。

标签: java for-loop


【解决方案1】:

在数学上,第 nth 行奇数的和是 n3,所以这给出了正确的结果:

int rowSumOddNumbers(int n) {
    return n * n * n;
}

我把推导留给读者...

【讨论】:

    【解决方案2】:

    这是解决问题的方法,可能还有其他更快的方法。首先,您必须找到第 n 行中的第一个数字。您可以看到每一行的起始数字都是按顺序排列的

    1 3 7 13 21 ... 
    

    因此第 n 个任期将是 (n-1)^2 + (n-1)+1

    一旦你找到了,你就可以找到该行中所有数字的总和 通过从该数字迭代到该行中的术语数

    for(int i=0;i<n;i+=2)
    {
        sum+=(Nth_Term+i);
    }
    

    或者简单地应用 AP 的 n 项之和公式,comman ratio 为 2

    sum= n*( 2*Nth_Term + (n-1)*2)/2 ;  
    

    如果您将第 N 项的值放入上述公式中,您会发现它的计算结果为 n^3.

    sum = n*( 2* ((n-1)^2 + (n-1)+1) + (n-1)*2)/2 = n^3 
    

    【讨论】:

      【解决方案3】:

      对于 javascript,这很简单

      Math.pow(n,3)
      

      【讨论】:

      • 别忘了回车
      【解决方案4】:

      这就是你要找的。​​p>

      public class RowSumOddNumbers {
      
          public static int array[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
      
          public static int rowSumOddNumbers(int n) {
              int firstIndex = 0;
              for (int i = 1; i < n; i++) {
                  firstIndex += i;
              }
              int total = 0;
              for (int i = firstIndex; i < firstIndex + n; i++) {
                  total += array[i];
              }
              return total;
          }
      
          public static void main(String[] args) {
              System.out.println(RowSumOddNumbers.rowSumOddNumbers(3)); //27
              System.out.println(RowSumOddNumbers.rowSumOddNumbers(1)); //1
              System.out.println(RowSumOddNumbers.rowSumOddNumbers(2)); //8
          }
      }
      

      【讨论】:

        【解决方案5】:

        对于 PHP:

        function rowSumOddNumbers($n) {
          return pow($n, 3);
        }
        

        【讨论】:

        • 嗨,欢迎来到 SO。虽然我们感谢您的回答,但请注意问题是关于 Java(您可以看到标签),而不是 PHP。
        猜你喜欢
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 2019-08-05
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 2019-02-11
        相关资源
        最近更新 更多