I am trying to write a code that computes 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 is the problem and how can I fix it?
Thank you