简体   繁体   English

使用Java递归求解谐波阶乘序列

[英]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) ..... 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? 没有条件运算符,如何解决100次重复?

Can it be solved without recursion? 是否可以解决而无需递归?

I've tried this code, but it doesn't work correctly and it contains "If". 我已经尝试过此代码,但是它无法正常工作,并且包含“ 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. 因此,您在递归中的最后一项是foo = 1 + 1.0/100 ,在递归中倒数第二项是1 + 1/98 * foo ,依此类推。

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. 您的harFac是正确的,但您不应两次致电harFac You need to instead calculate the divisor. 您需要计算除数。 I can't see how you would do this without an if condition, though. 不过, if没有if条件,我将看不到如何实现。

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. 由于除数变得如此之大,因此无法超过n = 30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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