Fibonacci

[aux_code language=»javascript» theme=»tomorrow» title=»Fibonacci» extra_classes=»»]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int e;
        do {
            try {
                System.out.println("Intro Longitud:");
                e = Integer.parseInt(br.readLine());
                if (e > 0) {
                    System.out.println("Recursivo o iterativo (R|I): 0 para salir.");
                    String op = br.readLine().toUpperCase();
                    if (op.equals("I")) {
                        fibRep(e);
                    } else if (op.equals("R")) {
                        for (int x = 0; x < e; x++) {
                            System.out.println("fib(" + (x + 1) + "): " + fibRec(x));
                        }
                    } else {
                        e = -1;
                        System.out.println("Opción no válida.");
                    }
                } else if (e < 0) {
                    e = -1;
                    System.out.println("El valor ha de ser superior a 0");
                } else {
                    System.out.println("Adiós");
                }
            } catch (IOException | NumberFormatException ex) {
                System.out.println("Sólo valores numéricos");
                e = -1;
            }
        } while (e != 0);
    }

    private static int fibRec(int e) {
        if (e < 2)
            return e;
        return fibRec(e - 1) + fibRec(e - 2);
    }

    private static void fibRep(int e) {
        int n1 = 0;
        int n2 = 1;
        int n3;
        System.out.println("fib(1): 0");
        System.out.println("fib(2): 1");
        for (int i = 1; i <= e - 2; i++) {
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
            System.out.println("fib(" + (i + 2) + "): " + n3);
        }
    }
}
[/aux_code]
Etiquetas: Sin etiquetas

Añadir un comentario

Debes estar conectado para publicar un comentario