Updatedagain

This commit is contained in:
2024-08-31 19:28:56 +00:00
parent f443bd90b3
commit c1e0a2a278
+9 -2
View File
@@ -4,19 +4,26 @@ import java.util.Scanner;
* fibonacci * fibonacci
*/ */
public class fibonacci { public class fibonacci {
public static long[] fibonacciCache;
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Let's try to get back on the horse!"); System.out.println("Let's try to get back on the horse!");
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Please enter the number you wanna search: "); System.out.println("Please enter the number you wanna search: ");
int fib = sc.nextInt(); int fib = sc.nextInt();
sc.close(); sc.close();
fibonacciCache = new long[1+fib];
System.out.println(fibonacciNum(fib)); System.out.println(fibonacciNum(fib));
} }
public static int fibonacciNum(int x){ public static long fibonacciNum(int x){
if (x <= 1){ if (x <= 1){
return x; return x;
} }
return (fibonacciNum(x-1)+(fibonacciNum(x-2))); if (fibonacciCache[x] != 0){
return fibonacciCache[x];
}
long nthFib = (fibonacciNum(x-1)+(fibonacciNum(x-2)));
fibonacciCache[x] = nthFib;
return nthFib;
} }
} }