面试题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的相关文章:
更多相关讨论分析
阅读全文
0 0
- 面试题03:Sum of odd numbers
- CodeWars:Sum of odd numbers
- [Haskell] CodeWars|Sum of odd numbers
- Sum All Odd Fibonacci Numbers
- Sum All Odd Fibonacci Numbers
- Sum All Odd Fibonacci Numbers
- FCC----------- Sum All Odd Fibonacci Numbers
- SPOJ ODDDIV - Odd Numbers of Divisors
- Sum of 'n' Numbers
- Sum of Numbers
- Sum of Square Numbers
- Sum of Triangular Numbers
- google2016面试题-count of smaller numbers after self
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- Sum of Consecutive Prime Numbers
- 1120. Sum of Sequential Numbers
- sum of all integer numbers
- Java面试宝典2017版
- 加班?去追求自己的人生吧
- PHP上传文件大小限制问题 post_max_size对大小的影响及解决方法
- 2017.09.11工作日记
- 明明的随机数
- 面试题03:Sum of odd numbers
- SQL查询入门(中篇)
- eclipse 安装maven插件
- 计算机系统进制概述与转换
- 《MySQL入门很简单》学习笔记(15)之第15章MySQL用户管理(关键词:MySQL/用户管理/权限表/普通用户/root用户)
- codeblocks快速注释多行以及取消注释
- Codeforces 853C 树状数组
- 菜鸡学习之归并排序(分治法)------学习算法记录2
- 一、计算机网络之TCP/IP协议