Java recursive function to calculate: e = 1 + 2/1 + 3/2 + 4/3 + 5/4 + ... + n/(n-1)

Asked

Viewed 611 times

2

My code:

  /**
    * Funcao para calcular: e = 1 + 2/1 + 3/2 + 4/3 + 5/4 + ... + n/(n-1)
    *
    * @param termos - quantidade de termos do somatorio
    *
    * Teste:
    *   para termos = 4
    *   soma = 1 + 2 + 1.5 + 1.33...
    *   soma = 5.83333...
    */
  public static double funcao01(int termos){

    double somatorio = 0.0;

    // se a quantidade de termos for igual a 1 retornar valor da base
    if (termos == 1){

      return 1;

    } else {

      somatorio = termos / (funcao01(termos - 1));

    } // fim do if

    return somatorio;

  } // fim da funcao01

Exit:

Saída do programa

What am I doing wrong? How to do this recursive function ?

2 answers

2

Substitute

somatorio = termos / (funcao01(termos - 1));

for

somatorio = funcao01(termos - 1) + termos / (double)(termos - 1);

The double is important to avoid the whole division.

1


You should imagine that recursion is a logic that always repeats itself in all elements of a series.

  /**
    * Funcao para calcular: e = 1 + 2/1 + 3/2 + 4/3 + 5/4 + ... + n/(n-1)
    *
    * @param termos - quantidade de termos do somatorio
    *
    * Teste:
    *   para termos = 4
    *   soma = 1 + 2 + 1.5 + 1.33...
    *   soma = 5.83333...
    */
  public static double funcao01(int termos){

    // se a quantidade de termos for igual a 1 retornar valor da base
    if (termos == 1){

      return 1;

    } else {

      return = funcao01(termos - 1) + (termos / (double)(termos-1));

    } // fim do if

  } // fim da funcao01

Taking advantage of the same recursion logic, but in a much simpler sequence.

/*
somatorio = 4+4+4+4+4 = 20

int soma=0;

for(int i = 0, i<5, i++ )
{
    soma = soma + 4;
}

printf("%d", soma);
*/

#include <stdio.h>

int somatorio(int n)
{
    if(n == 1)
    {
        return 4; // valor do primeiro elemento
    }

    retorn = somatorio(n-1)+4;
}


int main (void)
{
    printf("%d", somatorio(5));
    return 0;
}

This is the logic:

/*
Primeiro retorno
[somatorio(5-1)]+4
n=4

segundo retorno
[[somatorio(4-1)]+4]+4
n=3

terceiro retorno
[[[somatorio(3-1)]+4]+4]+4
n=2

quarto retorno
[[[[somatorio(2-1)]+4]+4]+4]+4
n=1

quinto retorno
[[[[[4]+4]+4]+4]+4 = 20

*/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.