Skip to content

Commit 7d7f50b

Browse files
authored
Update reverse_factorial_recursive.py
1 parent b774454 commit 7d7f50b

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed
Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
1-
def reverse_factorial(num: int, i: int = 1) -> int:
1+
def reverse_factorial(n: int, divisor: int = 1) -> int:
22
"""
3-
Return n if n! equals the given num, else return -1.
3+
Return x such that x! equals the given n, or -1 if no such integer exists.
44
5-
This function finds the integer n such that n! == num using recursion.
6-
If no such n exists, returns -1.
5+
This function recursively divides the number `n` by successive integers
6+
starting from 1 until it reaches 1. If the division completes exactly at 1,
7+
the last divisor - 1 is the factorial root. Otherwise, return -1.
78
9+
Parameters
10+
----------
11+
n : int
12+
The number whose factorial root is to be found.
13+
divisor : int, optional
14+
The current divisor used in the recursion (default is 1).
15+
16+
Returns
17+
-------
18+
int
19+
The factorial root if it exists, otherwise -1.
20+
21+
Examples
22+
--------
823
>>> reverse_factorial(120)
924
5
1025
>>> reverse_factorial(24)
@@ -13,9 +28,13 @@ def reverse_factorial(num: int, i: int = 1) -> int:
1328
-1
1429
>>> reverse_factorial(1)
1530
1
31+
>>> reverse_factorial(720)
32+
6
1633
"""
17-
if num == 1:
18-
return i
19-
if num % i != 0:
34+
if n < 1:
35+
raise ValueError("Input must be a positive integer.")
36+
if n == 1:
37+
return divisor
38+
if n % divisor != 0:
2039
return -1
21-
return reverse_factorial(num // i, i + 1)
40+
return reverse_factorial(n // divisor, divisor + 1)

0 commit comments

Comments
 (0)