summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authornotTito <capoiosct@gmail.com>2018-05-04 08:37:57 +0300
committerAndreas Rumpf <rumpf_a@web.de>2018-05-04 07:37:57 +0200
commit8f7bd6cf5ce3772466d90648a182fcd82ded9156 (patch)
tree628c2869c6ef2e16776df1ff9160e75294417e97 /lib
parentf94fafff9b6734a82bd252a03ba19057e1913cb8 (diff)
downloadNim-8f7bd6cf5ce3772466d90648a182fcd82ded9156.tar.gz
Replace factorial function with a compile time one (#7276)
* Replace factorial function with a compile time one

* Fix the indentation

* Update
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/math.nim18
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.}