52 lines
887 B
Java
52 lines
887 B
Java
public class Rekursion {
|
|
public Rekursion() {
|
|
System.out.println(fibonacci(10));
|
|
System.out.println(fibonacciIterativ(10));
|
|
System.out.println("Result " + mystery(5));
|
|
}
|
|
|
|
public int fibonacci(int n) {
|
|
if (n == 0) {
|
|
return 0;
|
|
} else if (n == 1) {
|
|
return 1;
|
|
} else {
|
|
return fibonacci(n-1) + fibonacci(n-2);
|
|
}
|
|
}
|
|
|
|
public int fibonacciIterativ(int n) {
|
|
if (n == 0) {
|
|
return 0;
|
|
} else if (n == 1) {
|
|
return 1;
|
|
}
|
|
|
|
int next = 0;
|
|
|
|
int a = 1;
|
|
int b = 0;
|
|
|
|
for (int index = 0; index < n; index++) {
|
|
next = a + b;
|
|
a = b;
|
|
b = next;
|
|
}
|
|
|
|
return next;
|
|
}
|
|
|
|
public int mystery(int n) {
|
|
System.out.println(n);
|
|
if (n <= 1) {
|
|
return 1;
|
|
}
|
|
|
|
return n + mystery(n-1);
|
|
}
|
|
|
|
private static String getString(int binaryNum) {
|
|
return String.valueOf(binaryNum);
|
|
}
|
|
}
|