This is optimal in terms of time complexity and space complexity, and much faster than the naive recursive algorithm, which is exponential in terms of run time.
It does look as though your assignments in your loop aren't quite right, though. You want
int oldi = i;
i = n+i;
n = oldi;
HOWEVER, your approach has a crucial weakness, which is that you will quickly overflow the bounds of an int
. Even with a 64-bit value, you'll get wrong answers by the time you hit f(100).
To get correct answers with arbitrary indices, you will need an arbitrary size integer library.
A related issue came up yesterday with calculating the Fibonacci series in Go.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…