Write a gate that takes some integer n and returns %.y if n is prime, and %.n if n isn't prime.
Last active
May 16, 2018 22:49
-
-
Save tacryt-socryp/6c39682f3d98ef684a26ad9ece308fa3 to your computer and use it in GitHub Desktop.
Prime number checker in Hoon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|% | |
++ 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 | |
-- |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/+ mylib :: import | |
=, mylib :: alias to the subject (don't have to type mylib anymore) | |
|= a=@ | |
^- @ | |
(new-prime a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment