Alex Rivera | Logout

Harmonic sequence recursion

Asked 2012-10-15T21:27:33.360
11

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));
    }
}
Edit
Report

1 Answer

13

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.

answered 2012-10-15T21:28:26.920

Your Answer