階乗
factorial
$ n! = n(n-1)!
$ 0!\coloneqq 1 と定義する
code:jl
factorial.(collect(0:20))
# 1
# 1
# 2
# 6
# 24
# 120
# 720
# 5040
# 40320
# 362880
# 3628800
# 39916800
# 479001600
# 6227020800
# 87178291200
# 1307674368000
# 20922789888000
# 355687428096000
# 6402373705728000
# 121645100408832000
# 2432902008176640000
20! = 2^(18) * 3^8 * 5^4 * 7^2 * 11*13*17*19
同じ方法で末尾の0の長さがわかるあんも.icon
code:jl
factorial(20) # 2432902008176640000
typemax(Int64) # 9223372036854775807
factorial(big(21)) # 51090942171709440000
code:jl
const _fact_table64 = let _fact_table64 = Vector{Int64}(undef, 20)
for n in 2:20
_fact_table64n = _fact_table64n-1 * n end
Tuple(_fact_table64)
end
function factorial_lookup(
n::Union{Checked.SignedInt,Checked.UnsignedInt},
table::Union{NTuple{20,Int64},NTuple{34,UInt128}}, lim::Int)
idx = Int(n)
idx < 0 && throw(DomainError(n, "n must not be negative."))
idx > lim && throw(OverflowError(lazy"$n is too large to look up in the table; consider using factorial(big($n)) instead"))
idx == 0 && return one(n)
f = getfield(table, idx)
return oftype(n, f)
end
factorial(n::Union{Int64,UInt64}) = factorial_lookup(n, _fact_table64, 20)