Add Tailrecursive Fibonacci

This commit is contained in:
Matti 2024-06-10 15:37:50 +02:00
parent 2a7ba7393c
commit c7aa18990e
3 changed files with 30 additions and 10 deletions

3
.idea/misc.xml generated
View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" default="true" project-jdk-name="openjdk-22" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -21,12 +21,12 @@ public class aufg1 {
result = 0;
} else if (number < 2) {
result = 1;
}else if (number == 10) { // Optimization1
result = 89;
}else if (number == 20) { // Optimization2
result = 10946;
}else if (number == 30) { // Optimization3
result = 1346269;
// }else if (number == 10) { // Optimization1
// result = 89;
// }else if (number == 20) { // Optimization2
// result = 10946;
// }else if (number == 30) { // Optimization3
// result = 1346269;
}else {
result = fibonacciRec(number-1) + fibonacciRec(number-2);
}
@ -34,11 +34,30 @@ public class aufg1 {
return result;
}
public static int fiboTailRec(int number){
return helper(++number, new int[] {0,1});
}
private static int helper(int number, int[] result){
if (number < 0){
return 0;
}
if (number < 2){
return result[number];
}
int temp = result[0] + result[1];
result = new int[] {result[1], temp};
return helper(number-1, result);
}
public static void main(String[] agrs){
// Fib(47) causes an Integer Overflow
for (int i=0; i<46; i++) {
System.out.println("i " + i + ": " + fibonacciIter(i));
System.out.println("i " + i + ": " + fibonacciRec(i));
System.out.println("i " + i + ": " + fiboTailRec(i));
System.out.println("==========");
}
}

View File

@ -4,9 +4,9 @@ public class Demo {
public static void main(String[] args) {
Queenproblem Q = new Queenproblem();
Q.solve();
// System.out.println("========\n");
// Q.setField(new int[]{0,0,0,0,0,0,0,0});
// Q.solve();
System.out.println("====================================\n");
Q.setField(new int[]{0,0,0,0,0,0,0,0});
Q.solve();
}
}