Factorial algorithms for arbitrary precision integer are different beast
entirely. Those can take some time.
> > and is the 'fac' here called with uninitialized argument?
>
> Sorry, a typo, should be
> cin>>x;
>
> The point is, constexpr will help us when... the argument is constant;-)
> In the other case, it is just a function.
Yes, that is how 'constexpr' functions work.
> >> Also, instead int we have for example arthmetic modulo 1 178 973 853,
> >> so x can be too bit to put every possible answer in a array.
> >
> > Who suggested to put answers to array?In both functions
>
>
> I just skip two post:
>
> I: constexpr cant help with nonconst.
> somebody: you can put answers in a small array, small because
> 21! is outside range of uint64_t.
> I: for factorial yes, but not always. Look at modified problem
> (factorial modulo).
Ok, indeed there are no silver bullets.
> > all checks are missing but neither puts anything to array.
>
> It doesn't matter, computing "factorial of integer munbers in modulo
> arithmetic" is quite artificial problem. This is only a simple example.
Ok.
> The point is: a simple recursion will be optimized to loop. For more
> complex case it is hard. For example you can write quicksort as a loop
> (using small stack for division points), it isn't even that hard, but
> still most implementations (including standard library) use recursion.
> Can you write extended euclidean algorithm (simple algorithm from
> school:) as loop?
It has been usually described as simple loop? Pseudo-code from wikipedia:
function extended_gcd(a, b)
s := 0; old_s := 1
t := 1; old_t := 0
r := b; old_r := a
while r ≠ 0
quotient := old_r div r
(old_r, r) := (r, old_r - quotient * r)
(old_s, s) := (s, old_s - quotient * s)
(old_t, t) := (t, old_t - quotient * t)
output "Bézout coefficients:", (old_s, old_t)
output "greatest common divisor:", old_r
output "quotients by the gcd:", (t, s)
> I think of course you can, but it won't be pretty
> and wou would waste too much time.
Might be you mix something up here ... it is simple algorithm.
> Of course, if you see something like factorial, you shouldn't event
> think and write it as a loop. But in other case, wasting time on
> rewriting algorithm as a loop I consider premature optimalization.
Depends how large factorials and how often are really need.
Calculating 10,000,000! naively will take minutes and there are
ways to optimize that:
http://www.cs.berkeley.edu/~fateman/papers/factorial.pdf
Sorry it is lisp, but the major number crunchers tend to love lisp.