I'd like to write a recursive function that returns a double and takes an int as input.
If input == 1, return 1.
If input == 2 the function must return 1.25 (the sum of what was previously returned, multiplied by 1.25)
If input == 3 the function must return the sum of input = 2 and input = 1, multiplied by 1.25, therefore (1 + 1.25) * 1.25 = 2.8126
If input == 4 the output must be (1 + 1.25 + 2.8126) * 1.25 = 6.32825etc etc
My attempt:
double _calc(int index) {
if (index == 1) return 1;
double tot = 0;
tot += _calc(index -1);
return tot * 1.25;
}
But the result is not what I expected.
I can achieve the correct result with a non recursive function:
double _calc(int index) {
if (index == 1) return 1;
if (index == 2) return 1.25;
var tmp = [for(var i=0; i<index; i+=1) 0.0];
tmp[0] = 1;
tmp[1] = 1.25;
for (int i=2; i<index; i++) {
for (int j=i; j>=0; j--) {
tmp[i] += tmp[j];
}
tmp[i] = tmp[i] * 1.25;
}
return tmp[index-1];
}
If it's possible, I'd like to get the correct result with a recursive function
Thanks in advance