Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Harmonic sequence recursion

Tags:

java

recursion

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));
    }
}
like image 412
vaindil Avatar asked Oct 15 '12 21:10

vaindil


Video Answer


1 Answers

You want to use floating point division:

public static double harmonic(int n) {
    if(n == 1.0) {
        return 1.0;
    } else {
        return (1.0 / n) + (1.0 / harmonic(n - 1.0));
    }
}

That is: 1/2 is 0; 1/2.0 is 0.5.

like image 197
Claudiu Avatar answered Oct 16 '22 02:10

Claudiu