Reverse factorial

前端 未结 17 1515
南笙
南笙 2020-12-05 03:12

Well, we all know that if N is given it\'s easy to calculate N!. But what about the inverse?

N! is given and you are about to find N - Is that possible ? I\'m curio

17条回答
  •  醉话见心
    2020-12-05 03:39

    Multiple ways. Use lookup tables, use binary search, use a linear search...

    Lookup tables is an obvious one:

    for (i = 0; i < MAX; ++i)
        Lookup[i!] = i; // you can calculate i! incrementally in O(1)
    

    You could implement this using hash tables for example, or if you use C++/C#/Java, they have their own hash table-like containers.

    This is useful if you have to do this a lot of times and each time it has to be fast, but you can afford to spend some time building this table.

    Binary search: assume the number is m = (1 + N!) / 2. Is m! larger than N!? If yes, reduce the search between 1 and m!, otherwise reduce it between m! + 1 and N!. Recursively apply this logic.

    Of course, these numbers might be very big and you might end up doing a lot of unwanted operations. A better idea is to search between 1 and sqrt(N!) using binary search, or try to find even better approximations, though this might not be easy. Consider studying the gamma function.

    Linear search: Probably the best in this case. Calculate 1*2*3*...*k until the product is equal to N! and output k.

提交回复
热议问题