2016-03-20 30 views
2

我试图做一段接受“n”输入的代码,计算第n行奇数三角形上的数字总和,如下所示:CodeWars - 奇数的总和 - For循环

   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相加在一起之前的数量应该是因为我需要存储先前循环的结果不是把它添加到当前循环的结果?

任何帮助表示赞赏。

+0

是什么让你为'firstNum'提出'(2 * n) - 1'?这显然是错误的。 – bcsb1001

回答

8

在n 的第线奇数的总和是简单地n的立方体:

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

我把推导给读者。


顺便说一句,你的发言,对n = 43的值应该是74088不正确。它实际上是79507

1

这是有可能更快地等方法also.First你必须找到在第n个line.You第一个数字可以看出,每行的起始号码在顺序如何才能解决这个问题

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的正项和的公式与comman比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 
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 
    } 
}