Java – arithmetic recursion
•
Java
I am trying to write a code to calculate the following for a given integer n:
1/1 + 1/2 + 1/3 ... + 1/n
This is the code I have written so far:
public class RecursiveSum { public static double Sumto(int n) { if (n == 0) { return 0.0; } else if (n > 0) { return 1/n + 1/Sumto(n - 1); } else { throw new IllegalArgumentException("Please provide positive integers"); } } public static void main(String[] args) { System.out.println(Sumto(5)); } }
However, it always outputs:
Infinity
What's the problem and how can I solve it?
thank you
Solution
You have two questions:
You must perform floating-point division (i.e. replace 1 / N with 1.0 / N) and sumto (n – 1) should be added to 1.0 / N to get sumto (n)
public static double Sumto(int n) { if (n == 0) { return 0.0; } else if (n > 0) { return 1.0/n + Sumto(n - 1); } else { throw new IllegalArgumentException("Please provide positive integers"); } }
The reason for getting infinity is that when sumto (n – 1) is 0.0 and sumto (0) is 0.0, 1 / sumto (n – 1) returns infinity
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码