簡體   English   中英

CodeWars - 奇數之和 - For 循環

[英]CodeWars - Sum of odd Numbers - For loop

我試圖制作一段接受“n”輸入的代碼,計算第 n 行數字的總和一個奇數三角形,如下所示:

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

等等。所以對於n = 3 ,總和將是7 + 9 + 1127

我知道 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 一起添加。是否應該存儲前一個循環的結果而不是將其添加到當前循環的結果中?

任何幫助表示贊賞。

在數學上,的總和n個奇數編號的線為n 3,所以這給出正確的結果:

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

我把推導留給讀者......

這是你如何解決這個問題的方法還有其他更快的方法。首先你必須找到第 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 
int rowSumOddNumbers(int n) {
  var odd = [];
  var starts = (n * n) - (n - 1);

  while(n > 0){
    odd.add(starts);
    starts += 2;
    n--;
  }

  int sum = odd.reduce((value, element) => value + element);
  print(sum);
  return sum;
}

這就是你要找的。

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
    }
}

對於 PHP:

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

對於 javascript,這很簡單

Math.pow(n,3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM