mirror of
https://github.com/nim-lang/Nim.git
synced 2026-06-05 11:24:08 +00:00
Replace factorial function with a compile time one (#7276)
* Replace factorial function with a compile time one * Fix the indentation * Update
This commit is contained in:
@@ -29,11 +29,21 @@ proc binom*(n, k: int): int {.noSideEffect.} =
|
||||
for i in countup(2, k):
|
||||
result = (result * (n + 1 - i)) div i
|
||||
|
||||
proc fac*(n: int): int {.noSideEffect.} =
|
||||
proc createFactTable[N: static[int]]: array[N, int] =
|
||||
result[0] = 1
|
||||
for i in 1 ..< N:
|
||||
result[i] = result[i - 1] * i
|
||||
|
||||
proc fac*(n: int): int =
|
||||
## Computes the faculty/factorial function.
|
||||
result = 1
|
||||
for i in countup(2, n):
|
||||
result = result * i
|
||||
const factTable =
|
||||
when sizeof(int) == 4:
|
||||
createFactTable[13]()
|
||||
else:
|
||||
createFactTable[21]()
|
||||
assert(n > 0, $n & " must not be negative.")
|
||||
assert(n < factTable.len, $n & " is too large to look up in the table")
|
||||
factTable[n]
|
||||
|
||||
{.push checks:off, line_dir:off, stack_trace:off.}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user