Factorial is a very impotent one when it comes to Computer Science and Programming. Teachers choose factorial as a good example to teach recursion. But reverse factorial (or some people say, reverser engineering factorial and some say, reverse factorial lookup) is also a good tool to solver particular problems when come to make some search algorithms and some algorithms with permutation calculations.

For this given scene, many people suggest to go with a generic algorithm like below, its a brute-force approach

1
2
3
4
Set X=1.
Generate F=X!
Is F = the input? If yes, then X is N.
If not, then set X=X+1, then start again at #2.

But this is not a good approach for a good programmer you know. Even we can optimize this optimize by using the previous result of F to compute the new F (new F = new X * old F). So I have written a function in C# like below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
static int reverse_factorial(int factorial)
{
	int in_scope_fact = factorial;
	int reverse_factorial_number = 1;
	while (true)
	{
		if (in_scope_fact / reverse_factorial_number == 1)
			return reverse_factorial_number;
		in_scope_fact = in_scope_fact / reverse_factorial_number;
		reverse_factorial_number = reverse_factorial_number + 1;
	}
	return reverse_factorial_number;
}

If you go through the code you can easily understand what I have done. And get full code for the program below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InverseFactorial
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write(reverse_factorial(int.Parse(args[0])));
            Console.ReadLine();
        }

        static int reverse_factorial(int factorial)
        {
            int in_scope_fact = factorial;
            int reverse_factorial_number = 1;
            while (true)
            {
                if (in_scope_fact / reverse_factorial_number == 1)
                    return reverse_factorial_number;
                in_scope_fact = in_scope_fact / reverse_factorial_number;
                reverse_factorial_number = reverse_factorial_number + 1;
            }
            return reverse_factorial_number;
        }
    }
}

Output is

Untitled-1

Advertisements