Recursividade | em Java
Autor: Marcelo's Oliveira | Publicado: 2011-12-10T02:10:00-08:00

RECURSIVIDADE
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Dizemos um objeto ser recursivo, quando ele é definido em termos de si próprio. Quando um método recursivo é chamado para resolver algum problema, na verdade, o método é capaz de resolver apenas o(s) caso(s) mais simples(s) ou o(s) caso(s) basico(s). Se a chamado do método for de um método básico, o método retorna o caso báse. Se o método for chamado com um problema mais complexo, em geral o método divide o programa em duas partes conceituais - uma parte que o método sabe como fazer e a outra que o método não sabe. Para tornar a recurssão realizável, a última parte deve assemelhar-se ao problema original, mas ser uma versão ligeiramente mais simples ou menor dele. Como esse novo problema é parecido com o problema original, o método chama uma nova cópia dele próprio para trabalhar no problema menor - isto é referido como chamada recursiva. O passo de recursão normalmente inclui a instrução return.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; A chaamda recursiva executa enquanto a chamada original para o método está ainda ativa. O passo de recursão (chamada recursiva) pode resultar em muitas outras chamadas recursivas è medida que o método divide cada novo subproblema em duas partes conceituais. Para que a recursão por fim termine, toda vez que o método chamar a si próprio com uma versão mais simples do problema original, a sequência de problemas cada vez menores deve convergir em um caso básico. Nesse ponto, o método reconhece o caso básico e retorna um resultado à cópia anterior do método. Uma sequência de retornos segue até a chamada do método original retornar o resultado final para o chamador.
Exemploque utiliza recursão:
A função fatorial, é pode se tornar em um exemplo clássico sobre recursividade. Ela pode ser definida como:n! = n (n-1)(n-2)...1Na resolução de um fatorial, podemos observar que o fatorial de um número é igual a esse número vezes o fatorial so número anterior a ele.&nbsp;Ex.:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 5! = 5 x 4 x 3 x 2 x 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 5! = 5 x (4 x 3 x 2 x 1)5! = 5 x 4!

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public int fatorial(int f) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (f == 0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; return 1;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (f * fatorial(f - 1));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }




Implementações Recursivas 


Questão1. Receber um número N e calcular a soma dos números pares de 0 até N.
public int somaPares(int n) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; int soma = 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (n == 0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(n%2==0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; soma = n;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return (soma + somaPares(n - 1));
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }

Questão2.&nbsp; Escrever na tela os números de 1 a 50.
public int mostrar(int m){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(m == 50)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return 50;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.println(m);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return(mostrar(m+1));
&nbsp;&nbsp;&nbsp; }


Questão3.&nbsp; Mostre na tela números ímpares de N à 1.
 public int mostraImpares(int n) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (n == 1)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return 1;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(n%2!=0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.printf("%d ",n);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return (mostraImpares(n - 1));
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }&nbsp;

Questão4.&nbsp;&nbsp; Mostre na tela números pares entre N e 0, inclusive.
public int imprimePares(int n) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (n == 0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(n%2==0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.printf("%d ",n);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return (imprimePares(n - 1));
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }

Questão5.&nbsp; Escreva uma função recursiva, SomaSerie(i,j,k: inteiro): inteiro, que devolva
a soma da série de valores do intervalo [i,j], com incremento k.
public int somaSerie(int a, int b, int c){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(a==b)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return a;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else if(a &lt; b)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return (a + somaSerie(a + c, b, c));
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return (b + somaSeriee(a, b + c, c));
&nbsp;&nbsp;&nbsp; }

Questão6. Função recursiva para calcular o MDC de 2 inteiros a,b &gt; 0.
public int mdc(int a, int b){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(b==0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return a;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(a &lt; b)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return mdc(a,b);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return mdc(b, a % b);
&nbsp;&nbsp;&nbsp; }

Questão7. Função recursiva para definir se um número é par ou ímpar.
public boolean parOuImpar(int num){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(num%2== 1)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return false;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(num%2 == 0 || num == 0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return true;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return parOuImpar(num - 1);
&nbsp;&nbsp;&nbsp; }

Questão8. Soma um intervalo fornecido.
public int soma_mn(int m, int n){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(n == m)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return m;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else if(m &lt; n)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return soma_mn(m, n-1) + n;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return soma_mn(m, n+1) + n;
&nbsp;&nbsp;&nbsp; } &nbsp; &nbsp; &nbsp;

Questão9. Série Fibonacci
public int fib(int num){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; int aux;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(num &lt; 2)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return num;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; aux = fib(num - 1) + fib(num - 2);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.println(aux);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return aux;
&nbsp;&nbsp;&nbsp; }


Para Reflexão.... (Com ou sem recursividade)
1. Uma das maneiras de se conseguir a raiz quadrada de um número é  subtrair do número os ímpares consecutivos a partir de 1, até que o  resultado da subtração seja menor ou igual a zero. O número de vezes que  se conseguir fazer a subtração é a raiz quadrada exata (resultado 0) ou  aproximadamente (resultado negativo).  
Ex: 16&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 16-1=15-3=12-5=7-7= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; raiz de 16 é 4.  
Faça um algoritmo que calcule a raiz quadrada de um número digitado pelo usuário utilizando o método citado acima.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int num = 16;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; int cont = 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; for (int i = 1; i &lt;= num; i++) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(i % 2 != 0){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; num = num - i;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; cont++;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }


2.&nbsp; Fazer um programa para calcular a soma dos N primeiros termos da série abaixo:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 100/0! + 99/1! + 98/2! + 97/3! + ...1/100!


3. Um número inteiro positivo n é dito “perfeito” se a soma dos seus divisores (excluindo o próprio n) for igual a n. Por exemplo 6 é um número perfeito, pois 1+2+3=6. Elabore um algoritmo para determinar se um dado número n é um número perfeito.&nbsp;

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; int num = 6;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; int soma = 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; for (int i = 1; i &lt;= num; i++) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(num % i == 0)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; soma += i;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(soma == num)
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; System.out.println("Numero Perfeito!");&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.println("Numero não-Perfeito!");