What I want to do is by using a for
loop, calculate the sum of roots under roots (not a math guy, don't know how you call that).
The sequence should go like this:
Sqrt(2 + Sqrt(2 + ... + Sqrt(2))), where n > 0.
For example, if n = 3
on the for
loop (while i = 1, i++)
, it should make this arithmetic sequence:
sum += Math.Sqrt(2 + Math.Sqrt(2 + Math.Sqrt(2)));
and if n = 4:
sum += Math.Sqrt(2 + Math.Sqrt(2 + Math.Sqrt(2 + Math.Sqrt(2))));
So the problem is I don't know how to loop trough n
by adding roots under roots until the loop ends.
My code template
public static double GetSumOfRoots(int n)
{
double sum = 0;
for (int i = 1; i <= n; i++)
{
sum += ...;
}
return sum;
}
Please tell me if I am not clear on my description, I will do my best, thank you.
Unwrap the loop, and have a look on what's going on:
n : formula
-------------------------------------------------------
0 : 0 = 0
1 : Sqrt(2) = Sqrt(2 + item(0))
2 : Sqrt(2 + Sqrt(2)) = Sqrt(2 + item(1))
3 : Sqrt(2 + Sqrt(2 + Sqrt(2))) = Sqrt(2 + item(2))
....
n : Sqrt(2 + ...) = Sqrt(2 + item(n - 1))
....
Having math done, you can write corresponding code:
public static double GetSumOfRoots(int n)
{
if (n < 0)
throw new ArgumentOutOfRangeException(nameof(n));
double sum = 0;
for (int i = 1; i <= n; i++)
{
// Note assignment = instead of +=
sum = Math.Sqrt(2 + sum);
}
return sum;
}
You can simplify the routine with a help of Linq:
using System.Linq;
...
public static double GetSumOfRoots(int n)
{
if (n < 0)
throw new ArgumentOutOfRangeException(nameof(n));
return Enumerable
.Range(0, n)
.Aggregate(0.0, (s, a) => Math.Sqrt(2 + s));
}
Demo:
var report = string.Join(Environment.NewLine, Enumerable
.Range(0, 10)
.Select(n => $"{n} : {GetSumOfRoots(n)}"));
Console.Write(report);
Outcome:
0 : 0
1 : 1.4142135623730951
2 : 1.8477590650225735
3 : 1.9615705608064609
4 : 1.9903694533443939
5 : 1.9975909124103448
6 : 1.9993976373924085
7 : 1.999849403678289
8 : 1.9999623505652022
9 : 1.9999905876191524