面试题03:Sum of odd numbers

来源:互联网 发布:淘宝个人店铺怎么过户 编辑:程序博客网 时间:2024/06/05 15:05

Given the triangle of consecutive odd numbers:

            1          3     5       7     9    11   13    15    17    1921    23    25    27    29...

*Calculate the row sums of this triangle from the row index (starting at index 1)
e.g.:rowSumOddNumbers(1); // 1; rowSumOddNumbers(2); // 3 + 5 = 8*

分析:简而言之就是求这个三角的每一行的和。
首先,可以看出,第n行有n个数。可以分析得出,到第n行最后一个数为止,数字的数目一共为(n^2+n)/ 2;而每一个数字的值是等差数列,可以得到求和公式,最后可以得到前n行为止(从第一行开始)所有数的合是[(n^2+n)/2]^2;求第n行的和就是用当n=n时的值减去n=n-1时的值,可得到结果为n^3;

public class Demo6 {    public static int rowSumOddNumbers(int n) {        //TODO        int num = (int) Math.pow(n, 3) ;       return num;     }    @Test    public void test(){        System.out.println("1------------>> " + Demo6.rowSumOddNumbers(1));        System.out.println("2------------>> " + Demo6.rowSumOddNumbers(2));        System.out.println("3------------>> " + Demo6.rowSumOddNumbers(3));    }

可以参考Stack Overflow的相关文章:
更多相关讨论分析