Skip to content

Instantly share code, notes, and snippets.

@cpbotha
Created December 9, 2020 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpbotha/d8ef2dc7bea5c473314ac1804a7f9f34 to your computer and use it in GitHub Desktop.
Save cpbotha/d8ef2dc7bea5c473314ac1804a7f9f34 to your computer and use it in GitHub Desktop.
nim implementation of toy zig example
# two nim-lang solutions based on this reddit thread:
# https://old.reddit.com/r/Zig/comments/k9q0vi/append_to_slice_in_zig/
# and this gist:
# https://gist.github.com/LaPingvino/57fb1c0afaacdb1185f247db2b365102
# -- Charl P. Botha <https://charlbotha.com/>
# on this Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz I get:
# with nim 1.4.2 and nim c --gc:orc -d:release:
# {500000002, 2}
# 12.092477559 seconds - seq
# {2, 500000002}
# 9.288986898999999 seconds - iter
# with nim 1.4.2 and nim c --gc:orc -d:release -d:danger:
# (danger means turning off runtime checks)
# {500000002, 2}
# 3.698235387 seconds - seq
# {2, 500000002}
# 0.8933175259999997 seconds - iter
import sequtils, sets, times
# nice and compact, but allocates sequence
proc solutions_seq(a: int, b: int, m: int): HashSet[int] =
result = toSeq(1..m-1).filterIt((a * it - b) mod m == 0 ).toHashSet()
let t0seq = cpuTime()
echo solutions_seq(2, 4, 1_000_000_000)
echo cpuTime() - t0Seq, " seconds - seq"
# slightly more verbose, but no seq allocation required
proc solutions_iter(a: int, b: int, m: int): HashSet[int] =
result = initHashSet[int]()
for x in 1..m-1:
if (a * x - b) mod m == 0:
result.incl(x)
let t0iter = cpuTime()
echo solutions_iter(2, 4, 1_000_000_000)
echo cpuTime() - t0iter, " seconds - iter"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment