I am studying recursion now, I stumbled upon a problem, I can’t solve it for a long time.

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

How to solve this without conditional operators and preferably recursion?

I tried this code, but it does not work correctly.

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

Closed due to the fact that off-topic participants Kromster , Anton Shchyrov , user194374, Alex , aleksandr barakin 2 Dec '16 at 19:14 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is closed, as it is customary to ask questions in Russian only on Russian in Stack Overflow . Please translate your question into Russian or use Stack Overflow in English ." - Kromster, Anton Shchyrov, Community Spirit, Alex, aleksandr barakin
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Welcome to Stack Overflow in Russian! Welcome to StackOverflow in English. This is a site. Please either translate the question in English . If you want to be a translate, it will be reopened. - Nofate

2 answers 2

1 / n! = [1 / (n - 1)!] / N

public static double factor(double n) { if (n == 1) return 1; return factor(n - 1) / n; } public static double sum(double n) { double res = 0; for(int i = 1; i <=n; i++) res += factor(i); return res; } 
  • one
    at each step, factorial calculation is not a good idea - the complexity of the algorithm turns into a quadratic + possible problems with overflow. - Artem Konovalov
  • @ArtemKonovalov factorial calculation through recursion is not a good idea in itself. And if the author needs exactly recursion, up to 99%, that this is a test task for recursion - Anton Shchyrov

Try my solution:

 public static BigDecimal sum(int n) { BigDecimal result = BigDecimal.ZERO; BigDecimal factor = BigDecimal.ONE; for (int i = 1; i <= n; i++) { factor = factor.multiply(BigDecimal.valueOf(i)); result = res.add(BigDecimal.ONE.divide(factor, MathContext.DECIMAL128)); } return result; }