Skip to content

Add Fibonacci Number #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions src/dynamic_programming/fibonacci_number.clj
Original file line number Diff line number Diff line change
@@ -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))))))
22 changes: 22 additions & 0 deletions test/dynamic_programming/fibonacci_number_test.clj
Original file line number Diff line number Diff line change
@@ -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)))))