235
\$\begingroup\$

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.

Task

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.

Input

  • 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

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.

Catalog

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>

\$\endgroup\$
8
  • 2
    \$\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\$ Dec 12, 2017 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, 2017 at 12:51
  • 1
    \$\begingroup\$ Could a case be made for locking this challenge and posting a new, less restrictive one? \$\endgroup\$
    – Shaggy
    Jun 25, 2018 at 12:59
  • 2
    \$\begingroup\$ @Shaggy Seems like a question for meta. \$\endgroup\$
    – Dennis
    Jun 25, 2018 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, 2018 at 13:45

368 Answers 368

1
6 7
8
9 10
13
1
\$\begingroup\$

Stuck, 3 bytes

iv|

Prints 1 for primes and 0 for non-primes. (The definition of "truthy/falsy values" means I can't use iv, because Stuck prints False/True without knowing what those are.)

\$\endgroup\$
1
\$\begingroup\$

Scala, 96 bytes

#!/usr/bin/env scala
print(((a:Int)=>if(a==2)true;else!2.to(a-1).exists(a%_==0))(args(0).toInt))

JVM and yet not last place :D

Does use some bash functionality but I'm using Scala so don't be too hard on me.

\$\endgroup\$
3
  • \$\begingroup\$ It's possible in 50 bytes. :) \$\endgroup\$ Sep 24, 2015 at 12:07
  • \$\begingroup\$ @EmilLundberg That code won't run. You need a main method or use the same trick I used. \$\endgroup\$
    – Martijn
    Sep 24, 2015 at 15:13
  • \$\begingroup\$ Huh, you're right that it doesn't compile as scalac prime.scala. But it does run as scala prime.scala. \$\endgroup\$ Sep 24, 2015 at 15:47
1
\$\begingroup\$

K, 29 bytes

(x>1)&&/x!'2_!1+_sqrt x:0$0:`

Got this off Rosetta Code, so marked it as community wiki.

\$\endgroup\$
1
\$\begingroup\$

XPath 2.0, 45 40 bytes

$i>1 and empty((2 to $i -1)[$i mod .=0])

For readability, incl. non-mandatory spaces (45 bytes)

$i > 1 and empty((2 to $i - 1)[$i mod . = 0])

In XPath, the only way to hand input like an integer to the processor is by passing it a parameter, in this case $i. This is hardly performant, and obvious improvement would be to use:

$i > 1 and empty((2 to math:sqrt($i) cast as xs:integer)[$i mod . = 0])

But since "shortest in any given language" and not performance was the goal, I'll leave the original in.

How it works

For people new to XPath, it works as follows:

  1. Create a sequence up to the current number:

    (2 to $i - 1)
    
  2. Filter all that have a modulo zero (i.e., that divide properly)

    [$i mod . = 0]
    
  3. Test if the resulting sequence is empty, if it non-empty, there is a divisor

    empty(...)
    
  4. Also test for special-case 1:

    $i > 1
    

The query as a whole returns the string true (2, 5, 101, 5483) or false (1, 4, 5487).

As a nice consequence, you can find all divisors (not prime divisors!) using an even shorter expression:

(2 to $i - 1)[$i mod . = 0]

will return (3, 5, 7, 15, 21, 35) for input 105.

\$\endgroup\$
1
\$\begingroup\$

XSLT 3.0, 209 203 201 bytes

<transform xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:x="x" version="3.0"><function name="x:p" expand-text="1"><param name="i"/>{$i>1 and empty((2 to $i -1)[$i mod .=0])}</function></transform>

Update 1: removed spaces in $i > 1, . = 0 and $i - 1.
Update 2: changed expand-text="yes" in expand-text="1", which is a new XSLT 3.0 feature

In expanded form, with the usual prefixes:

<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:x="x"
    version="3.0">    

    <xsl:function name="x:p" expand-text="yes">
        <xsl:param name="i"/>{
            $i > 1 and empty((2 to $i - 1)[$i mod . = 0])
    }</xsl:function>

</xsl:stylesheet>

This method uses the XSLT 3.0 feature to have a function as entry point (earlier versions did not support this). It uses the same XPath expression explained in my other post.

XSLT is notoriously verbose and starts with quite a few bytes declaring namespaces etc.

The function must be called with a typed value that derives from xs:integer. Most processor will consider that the default type if given an integer literal.

\$\endgroup\$
1
\$\begingroup\$

SWI-Prolog, 51 bytes

a(X):-X>1,\+ (Y is X-1,between(2,Y,I),0=:=X mod I).

This uses predicate between/3 which is not an ISO-Prolog predicate.

\$\endgroup\$
3
  • \$\begingroup\$ You can save 6 bytes by shifting the range of I up by 1 (thus removing the necessity for Y) and using I-1 in the mod. TIO link \$\endgroup\$
    – 0 '
    Dec 20, 2017 at 20:42
  • \$\begingroup\$ You can save another 2 bytes by replacing a(X) with -X. \$\endgroup\$
    – 0 '
    Dec 23, 2017 at 17:33
  • \$\begingroup\$ A bit of competition: codegolf.stackexchange.com/questions/57617/… \$\endgroup\$
    – 0 '
    Dec 24, 2017 at 6:30
1
\$\begingroup\$

JavaScript, 57

Prime finding regex.

alert(!/^1?$|^(11+?)\1+$/.test(Array(prompt()+1).join(1)))
\$\endgroup\$
3
  • \$\begingroup\$ That won't work. prompt() returns a string, not a number, so for input 3, you wind up with the string 31. The whole conversion isn't needed though. The questions allows reading the input in unary. \$\endgroup\$
    – Dennis
    Sep 17, 2015 at 19:40
  • \$\begingroup\$ Yeah, I was thinking of a way to fix it. Guess I never got around to actually fixing it... \$\endgroup\$
    – RK.
    Sep 17, 2015 at 19:59
  • 1
    \$\begingroup\$ Just adding + before the prompt() should work. \$\endgroup\$ Dec 6, 2015 at 18:49
1
\$\begingroup\$

Python 3, 54 bytes

A just for fun post that abuses the all function.

y=int(input());print(all(y%p for p in range(2,y))|y>1)

Explanation:

Takes all the numbers from 2 to y and calculate the mod of y and that number and return false if any of those are 0.

Edits:
Add the 1 check (+4 bytes)
Fix the check 1 logic (0 bytes)
Remove the [] (Thanks FryAmTheEggman!) (-2 bytes)
Remove the -1 from range (Thanks FryAmTheEggman!) (-2 bytes)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ all can take a generator, so you don't need []. Also range(a,b) already returns [a, ..., b-1]. \$\endgroup\$ Sep 17, 2015 at 19:50
  • \$\begingroup\$ Cool, thanks for the tip :) \$\endgroup\$
    – J Atkin
    Sep 17, 2015 at 23:37
1
\$\begingroup\$

Python 2, 45 bytes

Not the smallest entry, but I took a slightly different approach to detecting the prime numbers. Maybe it inspires someone to create an even smaller version. I couldn't discover any more savings myself.

i=a=n=input()
while i>2:i-=1;a*=n%i
print a>1
\$\endgroup\$
1
\$\begingroup\$

Scala, 50 bytes

val i=readInt
print(i>1&&(2 to i-1 forall(i%_>0)))

In case output to STDERR is forbidden, 65 bytes:

val i=scala.io.StdIn.readInt
print(i>1&&(2 to i-1 forall(i%_>0)))
\$\endgroup\$
1
\$\begingroup\$

Desmos, 108 104 94 bytes

k=2
1\left\{\sum _{n=2}^k\operatorname{sign}\left(\operatorname{mod}\left(k,n\right)\right)+2=k,0\right\}

To use, enter a new line. Then, call p\left(n\rgiht). The output will be bottom right on that line.

Edit 1: Shaved {x-1} to x.

Edit 2: Changed input format to a more STDIN-esque model.

\$\endgroup\$
4
  • \$\begingroup\$ I'm not sure how Desmos works or is scored, but \left\{2=\sum _{n=1}^x\left\{0=\operatorname{mod}\left(x,n\right),0\right\},0\right\} at... possibly 101 bytes? \$\endgroup\$
    – lirtosiast
    Sep 29, 2015 at 4:31
  • \$\begingroup\$ 1. The link gives me timeouts. If I change the protocol to HTTP, it works. 2. The question doesn't allow submitting functions. The closest to user input I could find is putting k=1 in one field and \left\{\sum _{n=2}^k\operatorname{sign}\left(\operatorname{mod}\left(k,n\right)\right)+2=k,0\right\} in the next. \$\endgroup\$
    – Dennis
    Sep 29, 2015 at 6:58
  • \$\begingroup\$ Just got a-1\prod_{n=2}^{a-1} mod(a,n), 29 bytes. Returns >0 for primes, 0 for non-primes. Note that the old solution could be golfed at least down to \left\{\sum_{n=2}^k sign(mod(k,n))+2=k,0\right\}, 48 bytes. \$\endgroup\$ Aug 23, 2020 at 5:15
  • \$\begingroup\$ @EthanChapman I think you meant to place parentheses around a-1, so it would be 31 bytes. Also, it can actually be further brought down to 26 bytes: (a-1)∏_{n=3}^amod(a,n-1). \$\endgroup\$
    – Aiden Chow
    Feb 23, 2022 at 2:32
1
\$\begingroup\$

Simplex v.0.5, 23 bytes

Can probably be golfed. It's really the square root declaration that hurts. *regrets removing p (prime checking) command from syntax and sighs*

i*R1UEY{&%n?[j1=o#]R@M}
i                        ~~ takes numeric input
 *                       ~~ copies and increments pointer
  R1UEY                  ~~ takes the square root and rounds it down
       {              }  ~~ repeats until zero cell met at end
        &                ~~ read and store the value to the register
         %               ~~ takes input mod current, move pointer left
          n              ~~ logically negates current (0 -> 1, 1 -> 0)
           ?[     ]      ~~ evaluates inside if the current cell
             j1=         ~~ inserts a new cell to check for a 1 case
                o#       ~~ outputs the result and terminates program
                   R@    ~~ goes right, pulls the value from the register
                     M   ~~ decrement value
\$\endgroup\$
1
\$\begingroup\$

Groovy, 36 bytes

I found a variation of this in a course on groovy that I'm taking:

p={x->x==2||!(2..x-1).find{x%it==0}}

Test code:

println ((2..20).collect {"Is $it prime? ${p(it) ? 'Yes':'No'}"})
\$\endgroup\$
1
  • \$\begingroup\$ p={x->!(2..<x).find{x%it==0}|x==2}, saves 2 bytes. \$\endgroup\$ Jan 17, 2017 at 9:06
1
\$\begingroup\$

PHP, 59 bytes

Credit goes to Geobit's answer. I basically just changed it from java to PHP.

function f($n){for($i=2;$i<$n;)$n=$n%$i++<1?:$n;echo $n>1;}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ function f($n){for($i=1;++$i<$n;)$n=$n%$i?$n:0;echo$n>1;} is shorter. The language name is "Java" by the way, not "java". \$\endgroup\$
    – Blackhole
    Nov 7, 2015 at 10:59
1
\$\begingroup\$

AppleScript, 158 Bytes

Note that the special case for 1 adds a full 20 bytes.

set x to(display dialog""default answer"")'s text returned's words as number
repeat with i from 2 to x/2
if x mod i=0 then return 0
end
if x=1 then return 0
1

If this program ever returns 0, it won't get to the final statement, which returns 1. Therefore, truthy is 1, falsey is 0.

\$\endgroup\$
1
  • \$\begingroup\$ This might be golfed more. Might not need words. Might not need as number, because x+0 might make a number. Might not need spaces after numbers (from2, 0then, 1then). I can't check because I'm off my Mac. \$\endgroup\$
    – kernigh
    Nov 17, 2017 at 0:55
1
\$\begingroup\$

Microscript II, 2 bytes

N;

Unlike the original Microscript, Microscript II provides a builtin for primality testing.

\$\endgroup\$
1
\$\begingroup\$

Mathematica, 48 47 bytes

<<PrimalityProving`
Echo@ProvablePrimeQ@Input[]

Saved 1 byte thanks to Martin Büttner. Echo is a new function in Mathematica 10.3. In older versions, use Print.

\$\endgroup\$
0
1
\$\begingroup\$

C, 59 bytes

main(_,i){scanf("%d",&_);for(i=_;_%--i;);putchar(!--i+48);}

If anything other than 1 counted as "falsey", then this would be 3 bytes smaller:

main(_,i){scanf("%d",&_);for(i=_;_%--i;);putchar(i+48);}

Please tell me if the second one is valid.

\$\endgroup\$
1
  • \$\begingroup\$ 1. Your code gives a FP exception for input 1 on my system. 2. An integer n is falsy if the statement if(n){...} does not execute .... For C, this means that only 0 is falsy. \$\endgroup\$
    – Dennis
    Nov 16, 2015 at 3:33
1
\$\begingroup\$

Mouse-2002, 22 bytes

 ?x:x.1-&FACT &SQR x.\!

Uses Wilson's theorem:

?x:                      ~ get an integer input; put it in x
   x.1-                  ~ put x-1 on the stack
       &FACT             ~ factorial it and push
             &SQR        ~ square it and push
                  x.\!   ~ modulo (x-1)!^2 % x; print

The version that doesn't use a variable is eight bytes longer, but this is because Mouse's stack operations have four- and five-byte long names. :(

\$\endgroup\$
1
\$\begingroup\$

JavaScript function golf, 16 13 bytes

p(pr(iai()));

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.

p2a(pr(iai()));

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

p(pr(iai()));
p( prints
  pr( if
     iai() an integer input into a prompt
          ) is prime
           ); into the console.
\$\endgroup\$
2
  • \$\begingroup\$ So, why does this have a negative score? \$\endgroup\$
    – cat
    Mar 20, 2016 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, 2016 at 22:40
1
\$\begingroup\$

Pyke, 2 bytes

_P

If the P function is given a negative number, it returns whether it's prime or not.

\$\endgroup\$
1
\$\begingroup\$

Factor, 56 bytes

Literally ungolfable.

USING: math.primes conv io ;
readln string>number prime?
\$\endgroup\$
3
  • \$\begingroup\$ I haven't used Factor recently, so I don't remember what must be done to print the t/f result of prime? \$\endgroup\$
    – kernigh
    Nov 17, 2017 at 1:04
  • \$\begingroup\$ @kernigh print or maybe >string print? why are you asking \$\endgroup\$
    – cat
    Nov 18, 2017 at 18:24
  • \$\begingroup\$ The task wants the result on STDOUT or something like it. This code leaves the result on the stack, and I can't remember if Factor would print the result, or if one must add more code to print the result. \$\endgroup\$
    – kernigh
    Nov 20, 2017 at 5:59
1
\$\begingroup\$

Pyth, 2 bytes

P_

Try it here!

Pyth now has implicit input!

\$\endgroup\$
1
\$\begingroup\$

Molecule, 3 bytes

Inp

Explanation:

Inp
I   read input
 n  convert to number
  p primality test
\$\endgroup\$
1
\$\begingroup\$

LiveCode 8, 708 bytes

on mouseUp
    ask ""
    put p(it) into field "a"
end mouseUp
function p n
    if n is 1 then return false
    repeat with i=2 to n-1
        if n mod i is  0 then return false
    end repeat
    return true
end p
        

This code can be placed inside any button. It will print true or false to a field named a. It should work for small-ish integers, but will probably freeze/crash on anything too large. Byte count is size of saved LiveCode stack with one button and one field and with this code in the button.

\$\endgroup\$
1
\$\begingroup\$

Unipants' Golfing Language, 53 47 bytes

i$cu^d^-l_u^^/%cu%?%d%:_?coc$d$$:__^d^-:_u?cuo:

Try it online!

(It has been implemented as a standard example in the interpreter.)

\$\endgroup\$
1
\$\begingroup\$

Fith, 30 bytes

*math* load line >int prime? .

This language isn't great for golfing...

This uses the prime? function in the *math* library. Here's a version using only builtins, which is pretty much what the library function does:

line >int -> x 2 x range { x swap mod } map all .

Explanation:

line           \ line of input
>int           \ cast to int
-> x           \ set x to the top of the stack
2 x            \ push 2, then x
range          \ range from [2, x)
{ x swap mod } \ anonymous function which calculates x mod its argument
map            \ map that function onto the generated range
all            \ return 1 if everything in the list is Boolean true, else 0
.              \ print the top of the stack

You may be able to tell that this language is just a little bit inspired by Forth. It also takes cues from PostScript, Python, and functional programming.

\$\endgroup\$
1
\$\begingroup\$

C, 54 bytes

i;main(j){for(scanf("%d",&i);i%++j;);putchar(49^j<i);}
  • Must be run without parameters, so j is initialized to 1.
  • Reads from standard input.
  • Prints 1 for primes, 0 for composites (no newline).
  • Could save 2 bytes with unprintable output - I'm not sure if \x00 and \x01 qualify as falsy/truthy.
\$\endgroup\$
2
  • \$\begingroup\$ '\0' and '\1' are truthy and falsy according to our definition, so printing NUL or SOH should be fine. \$\endgroup\$
    – Dennis
    Jun 16, 2016 at 22:58
  • \$\begingroup\$ for a less esoteric output format than printing \0 or \1, you could return i==j and save 4 bytes in the process \$\endgroup\$
    – c--
    Jul 27, 2023 at 15:55
1
\$\begingroup\$

brainfuck, 208 202 bytes

This is the code I wrote for my Sesos answer. See that answer for a detailed explanation.

This code assumes input fits in a single cell. Attempting to take input from an empty file must set the cell to zero. It works on an unbounded tape with no wrapping, including one that can go negative. It works for all positive numbers. Output will be a byte with a value of 0 or 1.

[->+>+<<]++>[-<->]+<[>-<,]>[->+<]>[[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>-]<<<<<<+[<<<<<<]>>>>>>[-<+>]++[<[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>>][[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<<<<<<]>>>>>>>>[>]>[<+>,]+<[>-<-]>.
\$\endgroup\$
0
1
\$\begingroup\$

RPN, 16 bytes

lambda x isprime

This define a function checking the primality of it's argument.

Call like this:

<number> lambda x isprime eval
\$\endgroup\$
1
6 7
8
9 10
13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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