ProgrammierenUebung1/Uebung5/Aufgabe1/Fibonacci.java

31 lines
819 B
Java
Raw Permalink Normal View History

2023-12-04 19:55:59 +00:00
public class Fibonacci {
public static void main(String[] args) {
int iterativ = printFibonacciIterative(45);
System.out.println(iterativ);
int recursive = fibonacciRecursive(45);
System.out.println(recursive);
}
public static int printFibonacciIterative(int n) {
//Hilfsvariablen a und b
int a = 1, b = 1;
int sum = 0;
//for-Schleife für die iterative Berechnung der Fibonacci Folge
for (int i = 1; i < n-1; i++) {
sum = a + b;
a = b;
b = sum;
}
return sum;
}
private static int fibonacciRecursive(int a) {
if (a == 1 || a == 2) {
return 1;
} else {
return fibonacciRecursive(a - 1) + fibonacciRecursive(a - 2);
}
}
}