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:
parent
f94fafff9b
commit
8f7bd6cf5c
1 changed files with 14 additions and 4 deletions
|
|
@ -29,11 +29,21 @@ proc binom*(n, k: int): int {.noSideEffect.} =
|
||||||
for i in countup(2, k):
|
for i in countup(2, k):
|
||||||
result = (result * (n + 1 - i)) div i
|
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.
|
## Computes the faculty/factorial function.
|
||||||
result = 1
|
const factTable =
|
||||||
for i in countup(2, n):
|
when sizeof(int) == 4:
|
||||||
result = result * i
|
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.}
|
{.push checks:off, line_dir:off, stack_trace:off.}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue