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
A recursive sequence is a sequence in which terms are defined using one or more previous terms which are given. If you know the nth term of an arithmetic sequence and you know the common difference , d , you can find the (n+1)th term using the recursive formula an+1=an+d .
Recursive Rule For example, arithmetic and geometric sequences can be described recursively. One particularly well-known sequence that is defined recursively is the Fibonacci sequence, in which each term is the sum of the two previous terms.
an=2an−1+3 is a recursive formula because each term, an, refers back to the previous term, an−1. This equation is telling us that whatever term we want to find is equal to 2 times the previous term, plus 3. The first three terms of this sequence are: 4,11,25. Try it Yourself!
You have two issues :
You must perform floating point division (i.e. replace 1/n
with 1.0/n
), and you should add Sumto(n - 1)
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 you got Infinity
was that 1/Sumto(n - 1)
returns Infinity
when Sumto(n - 1)
is 0.0
, and Sumto(0)
is 0.0
.
However, it always outputs: Infinity
Because you are doing 1/0
in the following steps in your code which yields Infinity
.
else if (n > 0) { return 1/n + 1/Sumto(n - 1);
You thought n > 0
escapes the n / 0
stuffs, but nope! Think about the case when n = 1
which passes n > 0
case but fall into a trap to:
1/Sumto(n - 1)
1/Sumto(1 - 1)
1/Sumto(0)
where Sumto(0)
returns 0.0
. Hence,
1/0.0
yields Infinity
. Moreover, use 1.0/n
instead of 1/n
as it is floating point division.
So add another condition, like
if(n == 1)
return 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With