CodeWars - 奇数之和 - For循环

时间:2016-03-20 15:44:20

标签: java for-loop

我试图制作一段接受输入“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个奇数。因此,我认为我可以获得该行的第一个数字,然后只需将前两个数字加2,然后求和。

下面的代码不起作用,因此对于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一起添加。我是否需要存储前一个循环的结果而不是将其添加到当前循环的结果中?

任何帮助表示感谢。

5 个答案:

答案 0 :(得分:12)

数学上,奇数的n th 行的总和是n 3 ,所以这给出了正确的结果:

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

我将推导给读者......

答案 1 :(得分:3)

这就是你可以解决问题的方法,也可以采用其他更快的方法。首先你必须在第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 

答案 2 :(得分:0)

这就是你要找的东西。

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

答案 3 :(得分:0)

对于javascript,这很简单

Math.pow(n,3)

答案 4 :(得分:-1)

对于PHP:

pointer-events: none;
相关问题