Last active
February 23, 2022 08:54
-
-
Save andrew-wilkes/0e670917542402abc35d94af3e247e68 to your computer and use it in GitHub Desktop.
Optimized Fibonacci number calculator using GDScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Control | |
# Fibonacci number calculation using recursion | |
# This has some optimization where prior numbers are stored in an array | |
# Also, the array is expanded in size as needed | |
func _ready(): | |
# Calculate the nth number and pass in the array to be referenced | |
print(fibo(34, [1, 1])) | |
#print(slow_fibo(34)) | |
func fibo(n: int, arr: Array): | |
if arr.size() <= n: | |
n = fibo(n - 1, arr) + fibo(n - 2, arr) | |
arr.push_back(n) | |
else: | |
n = arr[n] | |
return n | |
func slow_fibo(n): | |
if n < 2: | |
return 1 | |
return slow_fibo(n - 1) + slow_fibo(n - 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment