From d93b9e4f1ddd8b8cdbd039393ba6f70398d0206c Mon Sep 17 00:00:00 2001 From: IcarusTheFly Date: Mon, 7 Oct 2024 21:06:40 +1100 Subject: [PATCH 1/2] Add Fibonacci Number --- src/dynamic_programming/fibonacci_number.clj | 19 ++++++++++++++++ .../fibonacci_number_test.clj | 22 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/dynamic_programming/fibonacci_number.clj create mode 100644 test/dynamic_programming/fibonacci_number_test.clj diff --git a/src/dynamic_programming/fibonacci_number.clj b/src/dynamic_programming/fibonacci_number.clj new file mode 100644 index 0000000..b23a8c5 --- /dev/null +++ b/src/dynamic_programming/fibonacci_number.clj @@ -0,0 +1,19 @@ +(ns fibonacci) + +;; +;; @function fibonacci +;; @description Fibonacci is the sum of the previous two Fibonacci numbers. +;; @param {Integer} n - The input integer. +;; @return {Integer} Fibonacci of n. +;; @see [Fibonacci_Numbers](https://en.wikipedia.org/wiki/Fibonacci_number) +;; + +(defn fibonacci [n] + (if (not (integer? n)) + (throw (IllegalArgumentException. "Input should be an integer")) + (loop [i 1 + first-num 0 + second-num 1] + (if (>= i n) + second-num + (recur (inc i) second-num (+ first-num second-num)))))) \ No newline at end of file diff --git a/test/dynamic_programming/fibonacci_number_test.clj b/test/dynamic_programming/fibonacci_number_test.clj new file mode 100644 index 0000000..cdd9511 --- /dev/null +++ b/test/dynamic_programming/fibonacci_number_test.clj @@ -0,0 +1,22 @@ +(ns fibonacci-test + (:require [clojure.test :refer :all] + [fibonacci :refer [fibonacci]])) + +(deftest test-fibonacci + ;; Testing for invalid type + (testing "Testing for invalid type" + (is (thrown? IllegalArgumentException (fibonacci "0"))) + (is (thrown? IllegalArgumentException (fibonacci "12"))) + (is (thrown? IllegalArgumentException (fibonacci true)))) + + (testing "fibonacci of 0" + (is (= 0 (fibonacci 0)))) + + (testing "fibonacci of 1" + (is (= 1 (fibonacci 1)))) + + (testing "fibonacci of 10" + (is (= 55 (fibonacci 10)))) + + (testing "fibonacci of 25" + (is (= 75025 (fibonacci 25))))) From 7c5b39981aeadec42344bc965c140fd77b701a04 Mon Sep 17 00:00:00 2001 From: IcarusTheFly Date: Mon, 7 Oct 2024 21:08:55 +1100 Subject: [PATCH 2/2] Add Fibonacci Number to Directories --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index e556961..be0d243 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -22,6 +22,9 @@ * [using vector](/src/data_structures/queue/vector.clj) * [using list](/src/data_structures/queue/list.clj) +## Dynamic Programming +* [Fibonacci Number](https://github.com/TheAlgorithms/Clojure/blob/main/src/dynamic_programming/fibonacci_number.clj) + ## Sorting * [Merge Sort](https://github.com/TheAlgorithms/Clojure/blob/main/src/sorts/merge_sort.clj) * [Quick Sort](https://github.com/TheAlgorithms/Clojure/blob/main/src/sorts/quick_sort.clj)