From b77445479bf262eb74b83484c9b2776c74d7b4bb Mon Sep 17 00:00:00 2001 From: Parth Mittal Date: Sat, 11 Oct 2025 17:46:19 +0530 Subject: [PATCH] Create reverse_factorial_recursive.py Added reverse factorial recursive algorithm with doctests --- maths/reverse_factorial_recursive.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 maths/reverse_factorial_recursive.py diff --git a/maths/reverse_factorial_recursive.py b/maths/reverse_factorial_recursive.py new file mode 100644 index 000000000000..40dd93f127fc --- /dev/null +++ b/maths/reverse_factorial_recursive.py @@ -0,0 +1,21 @@ +def reverse_factorial(num: int, i: int = 1) -> int: + """ + Return n if n! equals the given num, else return -1. + + This function finds the integer n such that n! == num using recursion. + If no such n exists, returns -1. + + >>> reverse_factorial(120) + 5 + >>> reverse_factorial(24) + 4 + >>> reverse_factorial(150) + -1 + >>> reverse_factorial(1) + 1 + """ + if num == 1: + return i + if num % i != 0: + return -1 + return reverse_factorial(num // i, i + 1)