您的位置:首页 > 其它

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.

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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: