# How to analyse the performance of Mathematica on this function?

Using

f[n_] := Sum[1/(Sqrt[k] + Sqrt[k + 1]), {k, 1, n}]


to analyze the well-know series...

I noticed a sudden performance drop (on my outdated PC hardware ) around n=14.

f // FullSimplify


Is there away to overcome this? Memoization comes to mind.

What would be a method to monitor performance of such a function?

Not sure how to go ahead with this.

• Is this a toy problem to ask about timing performance, since Mathematica can perform the sum analytically? Sum[1/(Sqrt[k] + Sqrt[k + 1]), {k, 1, n}] to give -1 + Sqrt[1 + n] Additionally, are you sure you're timing the summation itself and not FullSimplify? The timing results up to n=40 seem reasonable to me. Jan 17 at 15:08
• With f[n_] := f[n] = Sum[1/(Sqrt[k] + Sqrt[k + 1]), {k, 1, n}]; f; // RepeatedTiming I get 4 10^-7 sec what seems rather fast. Jan 17 at 15:40
• @GeorgeVarnavides is right: the slowness comes from FullSimplify, not from Sum. You can use RootReduce instead of FullSimplify: the former is more precisely targeted to the task. Jan 17 at 16:02
• Remove["Global*"] then try Total[Table[1/(Sqrt[k] + Sqrt[k + 1]), {k, n}]] or do the Sum with Method->"Procedural" ignoring the FullSimplify - you will find that in both cases f is initially very fast, but the second time you run it is much slower. Not sure why but possibly caused by some kind of caching in mathematica's automatic simplification. Jan 17 at 16:05

Assuming this is a toy problem: a fast way would be to memoize and root-reduce at every step,

Clear[f];
f = 0;
f[n_Integer?Positive] := f[n] =
RootReduce[f[n - 1] + 1/(Sqrt[n] + Sqrt[n + 1])]

f // AbsoluteTiming
(*    {0.514451, -1 + Sqrt}    *)

• Generate a sequence seq = f /@ Range then looking at its form use Sqrt[FindSequenceFunction[(seq + 1)^2, n]] - 1 Or, since you have the recursion, you can use RSolve, i.e., Clear[f]; f[n] /. RSolve[{f[n] == f[n - 1] + 1/(Sqrt[n] + Sqrt[n + 1]), f == 0}, f[n], n][]` Jan 17 at 16:36
• @BobHanlon of course; but I was assuming that this is a toy problem. Jan 17 at 17:12
• Most of my problems are ( thank G. ) "toy" problems. Jan 18 at 9:00