Recursion: Calculate the sum of the first odd odd values starting at 5

3

I'm doing some exercises on and I stopped in that a few days ago.

I came up with the following code:

  /**
    * Funcao: Soma dos primeiros valores ímpares positivos começando em 5.
    * @param quantidade - quantidade de valores a somar
    *
    * valores esperados para quantidade = 1
    * 5
    * valores esperados para quantidade = 4
    * 32
    */
  public static int funcao06 (int quantidade){

    int resposta = 5;

    if(quantidade > 1){

      IO.println ("(" + quantidade + ") Valor Impar: " + (funcao06(quantidade - 1) + 2));      

    } else {

      resposta = 5;
      IO.println ("(" + quantidade + ") Valor Impar: " + resposta);

    }// fim do se

    return (resposta);

  } // fim do funcao06

The output of my function:

What am I doing wrong?!

    
asked by anonymous 20.09.2018 / 02:57

2 answers

4

I got the solution by following the following reasoning:

  • Every odd number is generated by the formula 2 * n + 1;
  • The base case of recursion is f (0) = 5 (must begin with 5);

With these hypotheses we try to generalize a formula for recursion:

f(0) = 5
f(1) = 5 + 7 = 12              = f(0) + 7
f(2) = 5 + 7 + 9 = 21          = f(1) + 9
f(3) = 5 + 7 + 9 + 11 = 32     = f(2) + 11

From the above table we notice that we add a value to the result of the previous function. This value can be reached with the formula 2 * (n + 2) + 1 plus 2 in the formula of the odd numbers is due to the beginning of the 5.

Soon the final formula is:

(n + 1) = 1 (n + 1)

Transforming into code we have:

public int soma(int quantidade) {
    if(quantidade == 0) {
        return 5;
    } else {
        return soma(quantidade - 1) + 2*(quantidade + 2) + 1 ;
    }
}

See on Ideone

    
20.09.2018 / 03:34
2

Recursive solution to sum a given number of odd numbers from an initial value:

private static int somarImpares(int valor, int quantidade) {
    assert valor % 2 != 0 : "valor: " + valor;
    assert quantidade > 0 : quantidade;

    if (quantidade > 1)
        return valor + somarImpares(valor+2,  quantidade-1);
    else
        return valor;
}

(works even for even numbers if the first assert is removed, the two assert are mainly for documentation)

To facilitate , the following method can also be implemented

 public static int somarImparesAPartir5(int quantidade) {
    return somarImpares(5, quantidade);
}
    
20.09.2018 / 12:27