For Python, we don't need to supply the optional initializer 1. And reduce resides in the functools namespace (much like mul is in operator). I assume we're not talking about that peculiar dialect of Python that is no longer supported a few months from now.
the first C version looks the best to me, it is extremely clear and concise. For a slight improvement, declare the variable c inside the loop.
Yet, since 20! is the last factorial representable in a u64, there is not much a point for these functions, and you should definitely check for n<21. It would be more elegant to store a lookup table with the 21 possible results. In practice you would want the logarithm of the factorial, that is computed by the "lgamma" function from the C standard math.h. Is such a thing available in rust? Edit: if you use doubles (which is more reasonable for that use case), you can also do that:
Comments (380) 116 threads
Earlier commentsFor example in C it would look something like this:
Or with recursion: In any case, I thin Rust looks better in every way with its cleaner syntax.Nah, lots of other languages can do this.
Ruby: Haskell:Python:
Continue this thread — 1 reply
Without the initializer, factorial(0) doesn't work.
But a more idiomatic C version would be
(defn factorial [n] (reduce *' (range 1 (inc n))))
Yet, since 20! is the last factorial representable in a u64, there is not much a point for these functions, and you should definitely check for n<21. It would be more elegant to store a lookup table with the 21 possible results.
In practice you would want the logarithm of the factorial, that is computed by the "lgamma" function from the C standard math.h. Is such a thing available in rust?
Edit: if you use doubles (which is more reasonable for that use case), you can also do that:
http://www.literateprogramming.com/knuthweb.pdf
(actual "code" starts on section C)
All comments shown.
Couldn't load more comments. Check your connection and try again.