Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic Recursion

Tags:

java

recursion

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

like image 785
John Smith Avatar asked Aug 03 '15 09:08

John Smith


People also ask

What is recursive arithmetic?

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 .

Can an arithmetic sequence be recursive?

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.

What is a recursive equation example?

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!


2 Answers

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.

like image 75
Eran Avatar answered Oct 25 '22 09:10

Eran


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;
like image 22
rakeb.mazharul Avatar answered Oct 25 '22 11:10

rakeb.mazharul