Reverse factorial

前端 未结 17 1506
南笙
南笙 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:44

    If the input number is really N!, its fairly simple to calculate N.

    A naive approach computing factorials will be too slow, due to the overhead of big integer arithmetic. Instead we can notice that, when N ≥ 7, each factorial can be uniquely identified by its length (i.e. number of digits).

    • The length of an integer x can be computed as log10(x) + 1.
    • Product rule of logarithms: log(a*b) = log(a) + log(b)

    By using above two facts, we can say that length of N! is:

    which can be computed by simply adding log10(i) until we get length of our input number, since log(1*2*3*...*n) = log(1) + log(2) + log(3) + ... + log(n).

    This C++ code should do the trick:

    double result = 0;
    for (int i = 1; i <= 1000000; ++i) {  // This should work for 1000000! (where inputNumber has 10^7 digits)
        result += log10(i);
        if ( (int)result + 1 == inputNumber.size() ) {    // assuming inputNumber is a string of N!
            std::cout << i << endl;
            break;
        }
    }
    

    (remember to check for cases where n<7 (basic factorial calculation should be fine here))

    Complete code: https://pastebin.com/9EVP7uJM

提交回复
热议问题