From 73dd771a0b3e1f15a0b33406f371e53d014e1a0a Mon Sep 17 00:00:00 2001 From: Vector-013 Date: Thu, 5 Oct 2023 20:21:27 +0530 Subject: [PATCH] Added recursive factorial calculator (#1326) --- math/factorial_recursion.c | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 math/factorial_recursion.c diff --git a/math/factorial_recursion.c b/math/factorial_recursion.c new file mode 100644 index 00000000..6ac6aed1 --- /dev/null +++ b/math/factorial_recursion.c @@ -0,0 +1,40 @@ +#include +#include +#include + +// finds factorial of a given inegral input. Assumes 0!=1. +int factorial(int n) +{ + if (n == 0) + { + return 1; // base case + } + return n * factorial(n - 1); // based on the fact that n*(n-1)! = n! +} + +bool check_arrays(int *a, int *b, int pos) +{ + if (factorial(a[pos]) == b[pos]) + return true; + else + return false; +} + +static void tests() +{ + /* tests have a few integral factorials*/ + int tests[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + int expected[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800}; + + for (int i = 0; i < 11; i++) + { + assert(check_arrays(tests, expected, i) == true); + } + printf("All test cases passed !\n"); +} + +int main() +{ + tests(); + return 0; +} \ No newline at end of file