Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.


Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.


  • If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

  • If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

    In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

    For scoring purposes, submit the program that corresponds to the input 1.


Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

  • This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

  • Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

    The language Piet, for example, will be scored in codels, which is the natural choice for this language.

    Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

  • Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

    Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

  • If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

  • Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

  • Unless they have been overruled earlier, all standard rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.


The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 57617; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

  • \$\begingroup\$ Can I take inputs as negative numbers, where abs(input) would be the number I am testing? \$\endgroup\$ – Stan Strum Sep 6 '17 at 3:40
  • 1
    \$\begingroup\$ Is there a reason for the full program requirement, rather than allowing the full range of default input types? E.g. answering with a function that takes its input as an argument, is currently disallowed? codegolf.meta.stackexchange.com/questions/2447/… \$\endgroup\$ – Lyndon White Dec 12 '17 at 6:21
  • 2
    \$\begingroup\$ @LyndonWhite This was intended as a catalog (like “Hello, World!”) of primality tests, so a unified submission format seemed preferable. It's one of two decisions about this challenge that I regret, the other being only allowing deterministic primality tests. \$\endgroup\$ – Dennis Dec 12 '17 at 12:51
  • 1
    \$\begingroup\$ @Shaggy Seems like a question for meta. \$\endgroup\$ – Dennis Jun 25 '18 at 13:44
  • 1
    \$\begingroup\$ Yeah, that's what I was thinking. I'll let you do the honours, seeing as it's your challenge. \$\endgroup\$ – Shaggy Jun 25 '18 at 13:45

298 Answers 298

6 7 8 9

C++, 96 bytes

main(int c,char**a){int n=atoi(a[1]);for(c=2;c<n;c++){if(n%c==0){puts("0");return;}}puts("1");}

It the same method as the C program using trial division, it just reads the value in as command line arguement.


Yorick, 20 characters


read(,"i") reads an integer from STDIN and is_prime is the builtin prime tester of Yorick. Outputs 1 if prime and 0 otherwise.


VBA Excel - 53 bytes

Golfed, to run in the immediate window :

t=false:for i=2 to j-1:t=(t Or j mod i=0):next:?not t

Performs a simple check for all values from 2 to j (the input)-1. If every division has a non-0 modulo, then it returns true (prime), otherwise it returns false (non-prime or error).

If you want to test this here is a larger code snippet that provides an inputbox for j:

j=inputbox(a):t=false:for i=2 to j-1:t=(t or j mod i=0):next:?not t

And for people that need it in a sub/function (ungolfed) :

function isprime(byval j as integer)  ' sanitize input to an integer.
  t=false                             ' set default return to false.
  for i=2 to j                        ' loop starting at 2 (so 1 or less is not prime).
    t=(t or j mod i=0)                ' check if i is a divisor of j
  next                                '      and add to existing return
  isprime=not t                       ' if any i is a divisor then the return is false
end function                          '      so return the opposite (isprime)
  • \$\begingroup\$ By the rules, if you have an input method you have to incorporate it. Also, little bug, you're returning TRUE for 1. In the spirit of your approach, I suggest turning the test around (and saving a couple of bytes): j=inputbox(7):t=j>1:for i=2 to j\2:t=t and 0<j mod i:next:?t \$\endgroup\$ – Joffan Jun 24 '16 at 5:42

Hassium, 140 Bytes

use Math;func main(){n=Convert.toNumber(input());b=Math.floor(Math.sqrt(n));for(i=2;i<=b;++i)if(n%i==0){println("0");exit(0);}println("1");}


use Math;
func main () {
        n = Convert.toNumber(input());
        b = Math.floor(Math.sqrt(n));
        for (i = 2; i<= b; ++i)
                if (n % i == 0) {

Mathcad 15, 15 bytes

valid in both Mathcad 15 and Mathcad Prime 3.1

not valid in Mathcad Prime Express (no symbolics)

n:=103   IsPrime(n)->

where -> is the symbolic evaluation operator



would be shorter still

edit 103 to taste

In response to the question from @Dennis the following might be helpful

Mathcad is, from a user perspective, a whiteboard in which you directly type in your expressions, programs, plots, etc and obtain the results either directly in the worksheet or export them (in some instances (eg, Excel) you can embed a "component" directly in the worksheet and access the application through the component. It also allows you mix text and expressions across the page(s) as well as down, making it almost a literate programming system.

In the above example, the input and output are all on the worksheet. All you need to do to change the 103 is click on it, delete the digits and add your own. If auto calculation is on, then Mathcad updates the output from the IsPrime function, otherwise choose the manual calculate option (which is simply pressing F9 in the case of Mathcad 15). Simples.

There are also file read and write functions if you want to do it the hard way, but Mathcad's interface makes it completely unnecessary for such a simple task.

See this link https://www.ptcusercommunity.com/message/420452#420452 for an example of an over-the-top means of finding the middle value of a vector (list). What you see is what I typed in or what Mathcad computed in response. If I were to edit the worksheet to, say, change v1's value from seq(6)+11 to seq(9)+20, Mathcad would almost instantly change the output from the "augment" expression to show the new value of v1 together with its corresponding indices. I'd have to manually rearrange the v2 expressions to make room for the new v1 but that's as simple as dragging the mouse around the affected expressions, which selects them, and then dragging the expressions to the new location. Easy. Even I can do it!

  • 2
    \$\begingroup\$ Is there no way of obtaining user input in Mathcad? \$\endgroup\$ – Dennis Sep 12 '15 at 1:28
  • \$\begingroup\$ That depends upon what you mean by "obtaining user input". I've added a bit more text to my original post to help clarify how a typical Mathcad might change the number to be tested - just edit it directly on the Mathcad "worksheet" and Mathcad will update the result. \$\endgroup\$ – Stuart Bruff Sep 12 '15 at 8:23
  • \$\begingroup\$ Please make sure you add in the byte count to the title of your post so that it can register on the leader board. Check the question on how to format it. \$\endgroup\$ – rayryeng - Reinstate Monica Sep 12 '15 at 16:28
  • \$\begingroup\$ Do you which algorithm is used by IsPrime? Are you sure it's not a probabilistic one like Miller-Rabin? \$\endgroup\$ – Martin Ender Sep 14 '15 at 9:45

Burlesque, 7 bytes

blsq ) 71fC
blsq ) 71fCL[1==
blsq ) 72fC
{2 2 2 3 3}
blsq ) 72fCL[1==

fC does a prime factorization. If the length of the resulting block is 1, then we have a prime. Note that this isn't as fast as a Miller-Rabin or similar obviously :p. With the next planned release this will be two bytes.


AniRad, 30 29 bytes

Probably not the shortest program:


Another possible program is, 30 bytes:



  • # = Starting point, pointer direction is to the right
  • W = User input, directly adds this to the stack
  • I = If-statement, or is equal to
  • P = If the stack is prime
  • v = If false, assign the pointer direction to the right
  • > = If true, assign the pointer direction to the bottom
  • ~ = Reset the stack
  • 0 / 1 = Assign the stack to 0 / 1
  • = = Print the result of the stack

The following paths are executed in this program:

  • If W = prime, path = WIP~1=
  • If W != prime, path = WIP~0=

This is a 2D esolang I created, which looks a bit like a magic square. This is a programming language in it's early stage, so a lot of functions aren't implemented yet. Also, a lot of bugs might occur, if you find a bug, please report it.


JavaScript function golf, 16 13 bytes


function golf has just got a primality test function, that you can try online in the console on the language page! The primality test function took me 3 commits on GitHub.

Returns 1 if prime, else 0.

The variant with the alert costs us 15 bytes.


And... the first ever explanation of a function golf program!

p( prints
  pr( if
     iai() an integer input into a prompt
          ) is prime
           ); into the console.
  • \$\begingroup\$ So, why does this have a negative score? \$\endgroup\$ – cat Mar 20 '16 at 2:18
  • \$\begingroup\$ @cat I assume it's because people think it's a function. The challenge calls for a complete program and this has function in the name. It looks like a full program to me though. \$\endgroup\$ – DanTheMan Jun 23 '16 at 22:40

Gogh, 1 byte


Run using:

$ ./gogh oi "e" <input>

The operator e pushes the primality of the TOS. Implicit input and output.


Pylongolf2, 4 bytes



c    read input
 n   convert to integer
  z  primality test (beta8+)
   ~ print it.

Racket, 31 bytes

(require math)(λ(n)(prime? n))

A standard library has a function for it. If we want to keep the import but write our own, we could do this for 51 bytes:

(require math)(λ(n)(equal?(list 1 n)(divisors n)))

On the other hand, if builtins were disallowed, for 64 55 bytes, thanks to @MatthewButterick, we can write our own:

(λ(n)(=(count(λ(i)(=(modulo n(+ i 1))0))(range n))2))

Old one, for 64:

(λ(n)(equal?'(1)(filter(λ(i)(zero?(modulo n i)))(range 1 n))))
  • \$\begingroup\$ 55 bytes: (λ(n)(=(count(λ(i)(=(modulo n(+ i 1))0))(range n))2)) \$\endgroup\$ – Matthew Butterick Apr 11 '16 at 5:49
  • \$\begingroup\$ @MatthewButterick Nice! I'll add that. \$\endgroup\$ – cat Apr 11 '16 at 10:47
  • \$\begingroup\$ @MatthewButterick from the docunentation, it seens like range needs two args, but I guess I was very tired when I was reading it. \$\endgroup\$ – cat Apr 11 '16 at 10:57
  • \$\begingroup\$ Also, (λ(n)(prime? n)) is the same as prime?, so if (require math)(λ(n)(prime? n)) is an acceptable 31-byte answer, then (require math)prime? ought to be an acceptable 20-byte answer \$\endgroup\$ – Matthew Butterick Apr 11 '16 at 17:29
  • \$\begingroup\$ @MatthewButterick I was very tired when I edited that in last night and I swore I read your name correctly... sorry about that :P \$\endgroup\$ – cat Apr 11 '16 at 19:20

Sage, 22 bytes

lambda N:N in Primes()

Try it online

  • \$\begingroup\$ (Super old but...) Submissions have to be full programs. \$\endgroup\$ – totallyhuman Sep 2 '17 at 2:17

UGL, 26 bytes


Try it online!

How it works:

id?u:                       int i = input(); if i==1: i=0;
     cuu                    int test = 2;
        l              _u:  while test != -1:
         ^^/_c=?                if i % test == 0:
                _=o                 print(i==test);
                   cd$              test = -1;

reticular, 6 bytes


A four-byte function:



i       take input
 n      convert to number
  @p    check for primality
    p   print
     ;  terminate
  • \$\begingroup\$ (non-competing) language is newer than the challenge. \$\endgroup\$ – mbomb007 Sep 22 '16 at 19:39
  • \$\begingroup\$ @mbomb007 is that really necessary? This is a catalog. \$\endgroup\$ – Conor O'Brien Sep 22 '16 at 20:24
  • \$\begingroup\$ Oh, idk. I guess not then \$\endgroup\$ – mbomb007 Sep 22 '16 at 20:29

R, 19 Bytes


Starts with a right assign to n. i.e. precede the code with the desired n. then it merely checks primeness of n. Prints TRUE or FALSE implicitly

If you don't like right assign as an input method then for 24 bytes you get:


Which assigns within the operator.

If you want explicit answer printing, then for 28 bytes:


RProgN, 102 Bytes

 'i' asoc true i 1 - ] 1 > while [ 'a' asoc i a / i a // = if [ [ false else [ end a 1 - ] 1 > end [ [


 'i' asoc           # Associate the implicit input with i
true i              # Push true to the stack, push i to the stack
1 -                 # Subtact 1 from the top of the stack
] 1 >               # Duplicate the top value of the stack, compare that it's larger than 1
while               # While the top of the stack contains a truthy value
    [               # Pop the top of the stack (The conditional in this case)
    'a' asoc        # Associate the top of the stack with a
    i a /           # Push i divided by a to the top of the stack
    i a // =        # Push i integeral divided by a to the top of the stack, compare the top and underneith the top for equality
    if              # if i/a = floor(i/a), essentially
        [ [ false   # Pop the conditional, and the 'true' we slipped in earlier, push false in in place of it
    else            #
        [           # Pop the conditional anyway
    end             #
    a 1 - ] 1 >     # Subtract 1 from a, duplicate it, and compare that it's larger than 1
end                 #
[ [                 # Pop the conditional, the value of a, which leaves only the bottom value we previously inserted, which is implicitly printed

RProgN doesn't have any method of input as of yet, as such, Any input needs to be written in pure form at the very start of the code, such that 23 'i' asoc .... An Extra byte is added to the score, because a space is required in front of any command.


Pyret, 58 bytes

(i == 1) or any({(x):num-modulo(i,x) == 0},range(2,i))

You can try this online by copying the code into the online Pyret editor!

Pyret programs are designed to be run in the online editor, so there's no way to read from STDIN. Here, the variable i represents the input. The program returns true if i is not prime and false if i is prime.

  • 1
    \$\begingroup\$ If there's no input from STDIN, maybe its best to do a function instead \$\endgroup\$ – Jo King Jun 20 '18 at 0:14
  • 1
    \$\begingroup\$ @JoKing This challenge doesn't allow functions. \$\endgroup\$ – Ørjan Johansen Jun 20 '18 at 1:46

Yabasic, 43 bytes

For d=2To n

Try it online!


Pepe, 53 bytes

Uses trial-and-error modulus, so gets slower in larger integers.


Try it online! Outputs 0 for truthy and none for falsy.


strict, 122 bytes

num t
num i 2
num r
get t
jen t 1 n
jen t 2
mrk m
set r t
mod r i
add i 1
jen t i
jgn r 0 m
mrk n
out: not 
out: prime

Reads input from stdin. Because the language doesn't have truthy/falsy values, it outputs either "prime" or "not prime".


num target
num i 2
num remainder
get target

# exceptions
jen target 1 not
jen target 2 prime

# loop from 2 to target
mrk main
    set remainder target
    mod remainder i
    add i 1
jen target i prime
jgn remainder 0 main

mrk not
    out: not\s

mrk prime
    out: prime\n
  • \$\begingroup\$ Welcome to Code Golf Stack Exchange! I'm not sure how best to test this; do you have a link to some sort of online interpreter? I can't access the link thanks to my stupid corporate network restrictions. \$\endgroup\$ – Giuseppe Jun 28 '19 at 15:50
  • \$\begingroup\$ @Giuseppe Unfortunately, there is no online interpreter. How much are you restricted? Would a direct mega.nz download link work? \$\endgroup\$ – programical Jun 28 '19 at 16:12

Rust, 124 bytes

fn main(){let s=&mut"".into();std::io::stdin().read_line(s);let n=s.parse().unwrap();print!("{}",n>1&&(2..n).all(|x|n%x>0))}

Try it online!

How complicated it has to be to read an integer from stdin...


Wren, 48 43 bytes

I feel surprised that I think better when using W instead of Wren. Also, the 1-primalty problem is fixed.


Try it online!

  • 1
    \$\begingroup\$ Fails for 1, just like your previous answer. \$\endgroup\$ – Jo King Dec 21 '19 at 22:23

Spice, 93 bytes

;i;m;t;c;r@REA i;ADD 0 1 c;SUB i 1 m;ADD c 1 c;MOD i c t;SWI t 1 9;SWI c m 3;ADD 0 1 r;OUT r;

This outputs [1] for a prime, and [] for a non-prime.

Un-golfed explanation:

;i;m;t;c;r@ - Declare vars (@ marks end of declarations)
(line 0) REA i;      - Read input into i
(line 1) ADD 0 1 c;  - Set counter c = 1
(line 2) SUB i 1 m;  - Set store input-1 as m
(line 3) ADD c 1 c;  - Start of loop, c+=1
(line 4) MOD i c t;  - Store mod of  t=i%c
(line 5) SWI t 1 8;  - if t < 1 (if non-prime, leave loop) to line 8
(line 6) SWI c m 3;  - if c < m continue loop (go to line 3)
(line 7) ADD 0 1 r;  - set result as truthy value - r = 1
(line 8) OUT r;      - output result, r

tq, 10 bytes



Uses Wilson's theorem to do the prime-checking.

?-1!        # Generate all numbers from 2 to input - 1
    x,      # Preserve this value, prevent it from being printed
      p*p   # Generate all possible combinations of those numbers
         %? # Does the product of any combination equal to the input?

Symbolic Raku, 17 bytes

$_=?($_%%[^] ^$_)

Try it online!

Suprisingly, this is shorter than the my previous Raku answer, though one byte longer than using the built-in


$_=                # Set the output to
   ?(           )  # The boolean of
     $_            # If the input is
       %%          # Divisible by
         [^]       # Only one of
             ^$_   # The range from 0 to input-1

C# (Visual C# Interactive Compiler), 62 bytes

int n=int.Parse(ReadLine()),i=2;while(n%i>0&i++<n);Write(n<i);

Try it online!


LCGFuck inputNumeric=true, 138 bytes

(Will turn this into a GitHub repository soon)

1 1im1-1
1 1om2-1
1 1om1 1
<{>>>o+1 1m0<<om
<<<++1 1 1 32
1 4 12 69 4
1 1 7 78 2

Try it online through this TIO JS interpreter

A brainfuck variant invented by me but uses a list of linear congruential generators (LCGs) instead of cells.

The \$N=1\$ case took too much more bytes to deal with.

Ungolfed and Explanation

1 1 im 1 -1                    # Storage for the input, since the input can only be retrieved once
1 1 om 2 -1                    # Used to prevent wrapping. Necessary for handling N = 1 case
1 1 om 1 1                     # Counts up from 2 to N
<{                             # While N % counter == 0 (If N == 1 the loop is skipped)
 >>>o+                         #  Gets and increments the counter value
 1 1 m 0 <<om                  #  Use a new LCG to check N % counter
<}                             # Loop
1 -1 om 0 >+om                 # The output of this LCG will be 2 if N is prime
<<<++                          # Move two states forward (2 - 2 = 0 if prime)
1 1 1 32                       # LCG for space
1 4 12 69 4                    # LCG for E, I, M
1 1 7 78 2                     # LCG for N, O, P, R, T
{>>>+++++c+c+++++c+++<<c<{+}}  # Output "NOT " if this LCG is not at state 0
>>>c++c<c+c+c                  # Output "PRIME"

Technical Details

(Copied from my obsolete challenge proposal on an LCGFuck interpreter)

An LCG is defined with 5 numbers, like 12345 678 90 -123 45. The last two numbers are optional and default to 0.

LCGFuck has 3 storage variables, the LCG list, the number list and the number memory. The functions are as follows:

  • LCG list: Cyclic list that stores all LCGs created. Every entry is in turn a list of 5 numbers in the order [a, b, c, d, e] as notated in the introduction. It has a pointer that controls which LCG is chosen at the moment, and moves in a cycle through the list.
  • Number list: Ordinary list that stores the numbers for LCG definition. It can store at most 5 numbers.
  • Number memory: A single variable that can be read and written with an input or an LCG output.

LCGFuck has 14 operators, namely:

  • \n (newline): Creates an LCG with the numbers in the order of [a, b, c(, d(, e))] and clears the list if the number list contains 3 or more numbers. No-op if the number list contains no more than 2 numbers.
  • <: Shifts to the previous LCG circularly (back to the last when moving from the first).
  • >: Shifts to the next LCG circularly (back to the first when moving from the last).
  • +: Moves the current LCG to the next state (calculates x' = (a * x + b) mod c)
  • c: Prints the output of the current LCG as a character (with the output as the codepoint).
  • n: Prints the output of the current LCG as a number (with a trailing space)
  • o: Writes the output of the current LCG to number memory
  • i: Reads a value from the input and writes it to number memory. There is two input mode, one reading a character one time (inputNumeric=false), and one reading a number one time (inputNumeric=true)
  • s: Reads the value from number memory and seeds the current LCG with it
  • m: Reads the value from number memory and pushes it to the number list
  • []: Output loop. Executes the loop if the current LCG is non-zero
  • {}: State loop. Executes the loop if the state of the current LCG is non-zero

An integer, optionally with a negative sign at the front, pushes the number to the number list. Any characters other than the newline \n and any of -0123456789[]{}<>+cimnos are no-ops.

The code runs linearly from the first characters, except when loop ends are encountered. Loops can be nested but must be paired accordingly from the innermost loop to the outermost loop.


Help, WarDoq!, 1 byte


Outputs 1 if the input is prime (positive or negative, differs from the other solution), 0 otherwise.

6 7 8 9

Not the answer you're looking for? Browse other questions tagged or ask your own question.