diff options
author | Andreas Rumpf <rumpf_a@web.de> | 2018-05-06 08:03:29 +0200 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2018-05-06 08:03:29 +0200 |
commit | 272bbad7844aa6f5eead28c25942c3c2c5a24884 (patch) | |
tree | 4672b688ac7ac43c2bb160a9e46b06ccdbbad75d /lib/pure/math.nim | |
parent | dfc17e5f8e0652ebc4c693e5a5900a122b85ab95 (diff) | |
parent | d8fde9daba32019a35933cb97f482de5cf3669fa (diff) | |
download | Nim-272bbad7844aa6f5eead28c25942c3c2c5a24884.tar.gz |
Merge branch 'devel' into araq-parser-fixes
Diffstat (limited to 'lib/pure/math.nim')
-rw-r--r-- | lib/pure/math.nim | 18 |
1 files changed, 14 insertions, 4 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim index cbd04a145..5f3240e00 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -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.} |