less than 1 minute read

The factorial of a number n is defined as n! = n * (n - 1) * (n - 2) * ... * 1.

Given a positive integer a, return n such that n! = a. If there is no integer n that is a factorial, then return -1.

Constraints

  • 0 < a < 2 ** 31

https://binarysearch.com/problems/Inverse-Factorial

ExamplesPermalink

Example 1Permalink

Input

  • a = 6

Output

  • answer = 3

Explanation

3! = 6

Example 2Permalink

Input

  • a = 10

Output

  • answer = -1

Explanation

10 is not any integer factorial.

SolutionPermalink

int solve(int a)
{
if (a <= 0)
return -1;
int divisor = 1;
while (a > 1 && a % divisor == 0)
{
a /= divisor;
divisor++;
}
return a == 1 ? divisor - 1 : -1;
}

Categories:

Updated:

Leave a comment