From b3bc5c1aff1f025b54c85791a0fd12f681df9e3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20M=C3=BCller?= Date: Wed, 27 Nov 2024 15:55:23 -0800 Subject: [PATCH] add iterative and recursive fibonacci functions --- benchmarks/fib_dynamic.cdc | 4 ++-- benchmarks/fib_iterative.cdc | 19 +++++++++++++++++++ benchmarks/fib_recursive.cdc | 12 ++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 benchmarks/fib_iterative.cdc create mode 100644 benchmarks/fib_recursive.cdc diff --git a/benchmarks/fib_dynamic.cdc b/benchmarks/fib_dynamic.cdc index ac608f3c4..55248afa1 100644 --- a/benchmarks/fib_dynamic.cdc +++ b/benchmarks/fib_dynamic.cdc @@ -17,5 +17,5 @@ fun fib(_ n: Int): Int { access(all) fun main() { - assert(fib(14) == 377) -} \ No newline at end of file + assert(fib(23) == 28657) +} diff --git a/benchmarks/fib_iterative.cdc b/benchmarks/fib_iterative.cdc new file mode 100644 index 000000000..a7a162270 --- /dev/null +++ b/benchmarks/fib_iterative.cdc @@ -0,0 +1,19 @@ +access(all) +fun fib(_ n: Int): Int { + var fib1 = 1 + var fib2 = 1 + var fibonacci = fib1 + var i = 2 + while i < n { + fibonacci = fib1 + fib2 + fib1 = fib2 + fib2 = fibonacci + i = i + 1 + } + return fibonacci +} + +access(all) +fun main() { + assert(fib(23) == 28657) +} diff --git a/benchmarks/fib_recursive.cdc b/benchmarks/fib_recursive.cdc new file mode 100644 index 000000000..5b06a75a4 --- /dev/null +++ b/benchmarks/fib_recursive.cdc @@ -0,0 +1,12 @@ +access(all) +fun fib(_ n: Int): Int { + if n < 2 { + return n + } + return fib(n - 1) + fib(n - 2) +} + +access(all) +fun main() { + assert(fib(23) == 28657) +}