64 points · by DmitryNovikov · 10y ago · 45 comments
n as 12 makes a lot of sense. n as a number too large to count doesn't make sense in the context of real programs.
The formal definition of time complexity measures relative to the size of the input, which in this case would be proportional to the number of elements in the list.
> n as a number too large to count doesn't make sense in the context of real programs
The definition of big-O notation involves taking the limit as n goes to infinity. It doesn't really even make sense if you only have a finite (even if huge) number of problem instances, since then everything is bounded by a constant.
The lower and upper bound differ, but they are both still constant.
template<int64_t n> int64_t fact() { return n * fact<n-1>(); } template<> int64_t fact<0>() { return 1; }
The book "Modern C++ design" from Alexandrescu extensively covers that kind of stuff.
There might even be a way to use a loop and constexprs.
Eg, Stirlings approximation for ln(n!) should serve fairly well for moderate and above values of n. And knowing your statistical distribution at large n you can likely find a decent distribution from a discrete case requiring n! into a continuous one, eg Gaussian.
Only in number theory problems do you actually need bignums for factorials, and those are usually toy problems or modulo some big prime.
I don't know of any actual applications where you need to compute the bignum factorial. I'm curious what the GP needed it for.
When I wrote games for older hardware every frickin' thing possible used look up tables to maximize speed.
Coincidentally I received this type of problem later when interviewing at MS, but it wasn't Raymond Chen's group.
For portability reasons, it might be better just using bit tricks and letting the compiler try to optimize it though. Clang and GCC do pretty well here.
edit: Investigating further, this intrinsic was introduced into gcc around 2006, which means I'm not sure it would have been available to me at the time.
┬────────────────
┼─────────────┬──
│ ──┬──────── ┼ ┬
│ ┬─┼─┬────── │ │
│ │ │ ┼─┬─┬── │ │
│ │ │ ┼─┼─┼─┬ │ │
│ │ │ └─┤ ├─┘ │ │
│ │ │ ├─┘ │ │
│ │ ├───┘ │ │
│ ├─┘ │ │
└─┤ │ │
└───────────┤ │
└─┘
(a diagram of factorial on Church numerals)