Skip to content

Instantly share code, notes, and snippets.

@tacryt-socryp
Last active May 16, 2018 22:49
Show Gist options
  • Save tacryt-socryp/6c39682f3d98ef684a26ad9ece308fa3 to your computer and use it in GitHub Desktop.
Save tacryt-socryp/6c39682f3d98ef684a26ad9ece308fa3 to your computer and use it in GitHub Desktop.
Prime number checker in Hoon
|%
++ new-prime
|= n=@
^- @
%- inner-prime [n 2]
++ inner-prime
|= a=[n=@ i=@] :: sample (input mold)
^- @ :: return mold
=+ upper=(div n.a 2) :: define a variable as the upper limit of variables to check = n/2
=+ res=(mod n.a i.a) :: res = n % i
?: (gte 0 n.a) :: if 0 >= n
%.n :: true, return not prime
?: (gte 1 n.a) :: false, check if 1 >= n
%.y :: true, 1 is not technically prime, but it needs to be considered prime for goldbach to work
?: (lte i.a upper) :: false, check if i <= upper
?: .=(res 0) :: true, check if res == 0
%.n :: true, return false
%- inner-prime [n.a .+(i.a)] :: false, call inner prime with n, (i + 1)
?: .=(res 0) :: check if res == 0
?: .=(n.a 2) :: true, check if n == 2
%.y :: true, return true
%.n :: false, return false
%.y :: return true
--
/+ mylib :: import
=, mylib :: alias to the subject (don't have to type mylib anymore)
|= a=@
^- @
(new-prime a)

Prime number checker

Write a gate that takes some integer n and returns %.y if n is prime, and %.n if n isn't prime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment