I’m really getting the hang of recursion (or so I think), but this problem is tripping me up. I’m trying to return 1 + 1/2 + 1/3 + … + 1/n, but no matter what I try the method returns 1.0. I cannot for the life of me figure out what’s wrong.
public static double harmonic(int n) {
if(n == 1) {
return 1;
} else {
return (1 / n) + (1 / harmonic(n - 1));
}
}
Well, for one, you don’t want to return
(1 / n) + (1 / harmonic(n - 1)), but also you need to usedoublearithmetic:If you left it as
1 / harmonicyou’d return another function entirely:That is a very confusing function to figure out, btw, but I think (with my 3rd time editing it) I got it right this time.