简体   繁体   中英

Solve harmonic-factorial sequence with java recursion

I'm trying to understand reqursion, but I have found one task, I couldn't solve for few days already.

X = 1/1 + 1/(1*2) + 1/(1*2*3) + 1/(1*2*3*4) + 1/(1*2*3*4*5) .....

how can I solve it for 100 repeats without conditional operators?

Can it be solved without recursion?

I've tried this code, but it doesn't work correctly and it contains "If".

public static double harFac(double n) {
    if (n == 1) return 1;
    return (1.0 / (n * harFac(n - 1))) + harFac(n - 1);
}

I believe you could do something like this:

double result = 0;
int div = 1;
for (int i = 1; i <= 100; i++){
    result += 1.0 / div; /*the division needs to take place in floating point*/
    div *= i+1; 
}

You'll very quickly run into trouble if you evaluate the denominator like that as it will run to a limit very quickly. When working with floating point, it's also a good idea to evaluate the smaller terms first.

Fortunately you can solve both of these problems by recasting the expression to

1 * (1 + 1/2 * ( 1 + 1/3 * (1 + 1/4 * ( ... ) ) ) )

So your final term is in the recursion is foo = 1 + 1.0/100 , the penultimate term in the recursion is 1 + 1/98 * foo , and so on.

I personally wouldn't use recursion to solve this, rather use a loop in a single function.

You're along the right lines but you shouldn't be calling harFac twice. You need to instead calculate the divisor. I can't see how you would do this without an if condition, though.

public static double harFac(double n)
{
    if (n == 1) return 1;

    int divisor = 1;
    for (int i = 2; i <= n; ++i) divisor *= i;

    return (1.0 / divisor) + harFac(n - 1);
}

This doesn't work beyond around n = 30 because the divisor becomes so massive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM