Sum of the First nth Term of Series
2015-09-29 23:10
309 查看
I saw an interesting algorithm before. It's about the "Sum of the first nth term of Series". The following are some of my summary.
Write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
Rules:
You need to round the answer upto 2 decimal places and return it as String.
If the given value is 0 then it should return 0.00.
You will only be given Natural Numbers as arguments.
Examples:
SeriesSum(1) => 1 = "1.00"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
n=0 => 0
n=1 => 1
n=2 => 4=3*2-2
n=3 => 7=3*3-2
n=4 => 10=3*4-2
n=5 => 13=3*5-2
n>=2 => 3*n-2
So, I had some ideas.
Non-recursion:
It seemed had a more skillfully solution. Take the following code:
Description
Goal:Write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
Rules:
You need to round the answer upto 2 decimal places and return it as String.
If the given value is 0 then it should return 0.00.
You will only be given Natural Numbers as arguments.
Examples:
SeriesSum(1) => 1 = "1.00"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
Analysis
Honestly, my first thought is using recursive program to work out this kind of problems. It looks like that Fibonacci sequence to me. The following are my analytic process.n=0 => 0
n=1 => 1
n=2 => 4=3*2-2
n=3 => 7=3*3-2
n=4 => 10=3*4-2
n=5 => 13=3*5-2
n>=2 => 3*n-2
So, I had some ideas.
Solutions
Recursion:private static string GetSeriesSumResult(int n) { return SeriesSum(n).ToString("F"); } private static double SeriesSum(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } double temp = 3 * n - 2; double result = 1 / temp + SeriesSum(n - 1); return result; }
Non-recursion:
private static string GetSeriesSumResult2(int n) { double result = 0; for (var i = 1; i <= n; i++) { result += 1f / (3 * i - 2); } return result.ToString("F"); }
It seemed had a more skillfully solution. Take the following code:
public static string GetSeriesSumResult3(int n) { return (from i in Enumerable.Range(0, n) select 1.0 / (3 * i + 1)).Sum().ToString("F"); }
相关文章推荐
- 听听那雨
- Light oj 1252 - Maintaining Communities(树形dp)
- Maven私服Nexus的构建
- Can’t connect to Mysql server on ‘127.0.01’(10061)
- 读jQuery官方文档:遍历
- C语言实现时间差、星期、天数算日期(转)
- 【Machine Learning in Action --3】决策树ID3算法预测隐形眼睛类型
- 【codechef】Coffee Breaks(dp,剪枝)
- 个人博客作业Week2
- JS
- AJAX总结
- 数据结构实验之链表八:Farey序列
- 预编译
- 列式数据库
- 将十进制无符号整数转化为任意进制数(大数)
- R-3.1.1 编译安装
- 将该整数每位的数平方后相加,得到一个新的数,如此循环下去,最后能得到1。
- UGUI中的Canvas、Camera和Canvas Scaler
- 全面理解 Unity UI 系统
- 多线程:轮流执行输入输出