From cb83365a24197cc74695e889c0bc87ee5a5d5029 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Wed, 23 Oct 2024 11:15:20 -0400 Subject: [PATCH] One branch recursion --- datastructures/recur.go | 9 +++++++++ datastructures/recur_test.go | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 datastructures/recur.go create mode 100644 datastructures/recur_test.go diff --git a/datastructures/recur.go b/datastructures/recur.go new file mode 100644 index 0000000..4e8edda --- /dev/null +++ b/datastructures/recur.go @@ -0,0 +1,9 @@ +package datastructures + +func Factorial(n int) int { + if n < 1 { + return 1 + } + + return n * Factorial(n-1) +} diff --git a/datastructures/recur_test.go b/datastructures/recur_test.go new file mode 100644 index 0000000..a2e53a2 --- /dev/null +++ b/datastructures/recur_test.go @@ -0,0 +1,38 @@ +package datastructures + +import "testing" + +func TestFactorial(t *testing.T) { + + cases := []struct { + Name string + Input int + Expected int + }{ + { + "Factorial of 5", + 5, + 120, + }, + { + "Factorial of 10", + 10, + 3628800, + }, + { + "Factorial of 12", + 12, + 479001600, + }, + } + + for _, test := range cases { + t.Run(test.Name, func(t *testing.T) { + got := Factorial(test.Input) + + if got != test.Expected { + t.Errorf("Error got: %d want: %d", got, test.Expected) + } + }) + } +}