VL-Programmieren/VL05/Aufgabe01/Aufgabe01.java

58 lines
1.4 KiB
Java

package VL05.Aufgabe01;
/**
* Vorlesung 5 / Aufgabe 1
*
* @author Sebastian Brosch
*/
public class Aufgabe01 {
public static void main(String[] args) {
final int MAX_NUMBER = 45;
// get all fibonacci numbers using a iterative solution.
for (int i = 0; i < MAX_NUMBER; i++) {
System.out.printf("Fibonacci Nr. %d: %d\n", (i + 1), iterativeFibonacci(i));
}
// get all fibonacci numbers using a recursive solution.
for (int j = 0; j < MAX_NUMBER; j++) {
System.out.printf("Fibonacci Nr. %d: %d\n", (j + 1), recursiveFibonacci(j));
}
}
/**
* Method to get a specific fibonacci number using a iterative solution.
*
* @param nth The number of the fibonacci number.
* @return The fibonacci number.
*/
private static int iterativeFibonacci(int nth) {
int[] fib = { 1, 1 };
for (int i = 0; i <= nth; i++) {
if (i < fib.length)
continue;
int result = fib[0] + fib[1];
fib[0] = fib[1];
fib[1] = result;
}
return fib[1];
}
/**
* Method to get a specific fibonacci number using a recursive number.
*
* @param nth The number of the fibonacci number.
* @return The fibonacci number.
*/
private static int recursiveFibonacci(int nth) {
if (nth == 0 || nth == 1) {
return 1;
} else {
return recursiveFibonacci(nth - 2) + recursiveFibonacci(nth - 1);
}
}
}