232
\$\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

355 Answers 355

1
5 6
7
8 9
12
2
\$\begingroup\$

dc, 17 22 bytes

?d*5+v[dz%rdz<M*]dsMxp

Try it online!

I've been on a bit of a dc kick lately and although there's already a dc solution here, this is 10 5 bytes shorter. It follows the I/O request of the original question, which does add two bytes for the explicit input and output (rather than the usual rules these days that allow implicit stack I/O), but okay.

This outputs zero for composite numbers and non-zero for primes.

How it works: this program builds a stack consisting of the modulo of the input with the current stack size (so the stack looks like, from bottom to top, i%2, i%3, i%4, ...), then when it decides it's gone far enough (stack size = input) it multiplies the stack as it unwinds the recursion.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ This fails for 1 and 2. \$\endgroup\$ Mar 16, 2019 at 0:22
  • \$\begingroup\$ Oof, you're right. Not sure how I missed that. It took me five bytes to fix (by precomposing with d*5+v, i.e., x -> int(sqrt(x^2+5)), i.e., 1->2, 2->3, n->n for n>2) \$\endgroup\$ Mar 18, 2019 at 18:09
2
\$\begingroup\$

K (oK), 14 19 bytes

Solution:

2=+/d=_d:x%!x:. 0:`

Try it online!

Example:

root@c957fa0dccbd:/ok# echo 1 | node repl.js examples/prime.k
0
root@c957fa0dccbd:/ok# echo 2 | node repl.js examples/prime.k
1
root@c957fa0dccbd:/ok# echo 5 | node repl.js examples/prime.k
1
root@c957fa0dccbd:/ok# echo 97 | node repl.js examples/prime.k
1

Explanation:

Calculate number of factors for input, if equal to 2, then it's prime.

2=+/d=_d:x%!x:. 0:` / the solution
                0:` / read from stdin
              .     / value (ie convert "123" > 123)
            x:      / store input as x
           !        / range 0..x
         x%         / x divided by ...
       d:           / store as d
      _             / floor
    d=              / d equal to ...
  +/                / sum
2=                  / 2 equals?
\$\endgroup\$
2
\$\begingroup\$

tinylisp, 23 bytes

There's a library function.

(load library
(prime? 1

(Since tinylisp is incapable of taking user input, "For scoring purposes, submit the program that corresponds to the input 1.")

Try it online!


Here's a 112-byte solution using only the base language, no library functions:

(d D(q((F A N)(i(l A N)(D F(a F A)N)(e N A
(d _(q((F N)(i(D F 0 N)(e F N)(_(a 1 F)N
((q((N)(i(e N 1)0(_ 2 N))))1

The first line defines a function D that takes a factor F, an accumulator A (initially 0), and a number N; it returns 1 if N is divisible by F, 0 otherwise.

The second line defines a function _ that takes a minimum factor F and a number N; it returns 1 if N is coprime to all numbers from F to N-1, 0 otherwise.

The third line constructs an anonymous function that takes a number N; it returns 0 if N is 1, and otherwise calls _ with number N and minimum factor 2. As above, the scored code calls the anonymous function with an argument of 1.

\$\endgroup\$
2
\$\begingroup\$

DIVCON, 8 bytes

Prequisities: Enter 1 into the INPUT_MAX prompt.

i*[;-=o]

Explanation

"Partition" by * here means solving x * y = a - a is the original accumulator value. x and y needs to be as close as possible. In addition, the following equality must be satisfied: x>=y

         Description     | Example(0) | Example(1)
         ----------------+------------+-----------
i        Take an input   |  12        | 13
 *       Partition by *  | 4, 3       | 13, 1
         ----------------+------------+-----------
  [      Left branch     |   4        | 13
         Do nothing      | *discarded*| *discarded*
         ----------------+------------+------------
   ;     Right branch    | 3          | 1
    -    x - 1           | 2          | 0
     =   x == 0?         | 0          | 1
      o  Print this value| OUT: 0     | OUT: 1
         ----------------+------------+------------
       ] End both branches

Actually, there is another implicit reverse computation. But, since INPUT_MAX is 1, the extra prompting from i is disabled.

\$\endgroup\$
2
\$\begingroup\$

MAWP, 48 46 54 bytes

@1A<:.>{1A<1:.>2M}!1A[/!!\!/P\!/WA<:.>{%}\2A?0{1M}]1:.

-2 bytes from Dion's suggestion.

+8 bytes after fixing the problem with 1 as input.

Prints 1 for prime and 0 for non-prime. Can probably be golfed by a few more bytes, since it checks for 2 at the beginning first.

Try it!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Should work as expected now. \$\endgroup\$
    – Razetime
    Aug 26, 2020 at 9:10
  • \$\begingroup\$ Looks good now. Can you explain how it works? \$\endgroup\$
    – Dingus
    Aug 26, 2020 at 9:16
  • 1
    \$\begingroup\$ checks for 1 first, then 2, then moves on with a loop till it finds any divisor. \$\endgroup\$
    – Razetime
    Aug 26, 2020 at 9:17
2
\$\begingroup\$

CSASM v2.1.2.2, 207 235 bytes

Prints a 1 (truthy) if the input is a prime integer, 0 (falsy) otherwise.
Truthy values in CSASM are non-zero numbers, non-\0 chars and non-null strings/arrays/objects.
Falsy values in CSASM are zero, the \0 character or null strings/arrays/objects.

func main:
in ""
conv i32
pop $a
push $a
push 2
comp.gte
push $f.o
brtrue a
br b
.lbl a
push 2
dup
pop $1
push $a
sub
brfalse d
.lbl c
clf.o
push $a
push $1
rem
brfalse b
inc $1
push $1
push $a
comp.lt
push $f.o
brtrue c
.lbl d
push 1
print
ret
.lbl b
push 0
print
ret
end

Commented and ungolfed:

func main:
    ; Get the input, convert it to an integer and store it in the accumulator
    in ""
    conv i32
    pop $a

    ; if $a < 2, then $a is not prime
    push $a
    push 2
    comp.gte
    push $f.o
    brtrue initLoop
    br notPrime

    .lbl initLoop
    ; Initialize the loop counter and check if $a == 2
    ; If $a is 2, return truthy early
    push 2
    dup
    pop $1
    push $a
    sub
    brfalse prime

    .lbl loop
        ; Clear the comparison flag
        clf.o

        ; If $a % $1 == 0, then $a is not prime
        push $a
        push $1
        rem
        brfalse notPrime

        ; Loop until $1 >= $a
        inc $1
        push $1
        push $a
        comp.lt
        push $f.o
        brtrue loop

    .lbl prime
    ; $a is prime
    push 1
    print
    ret

    .lbl notPrime
    ; $a is not prime
    push 0
    print
    ret
end
\$\endgroup\$
2
\$\begingroup\$

Arduino, 146 143 bytes

#define S Serial
int p=0,d=1;void setup(){S.begin(300);}void loop(){while(S.available())p=p*256+S.read();if(p&&!(p%++d%p)){S.print(p==d);p=0;}}

Based on the current top answer for C++. I'm not convinced my adaptation is optimal.

Reading in a number from the Serial input is actually pretty annoying in Arduino. Serial.available() gives the number of unread bytes, but unfortunately it caps out at 64, which is too small for me to use unary for this challenge. Instead, I opted to interpret the input as a byte array.
Bitshift is lower precedence than addition, and (p<<8) is longer than p*256 (note the parentheses needed).
In this case, a while loop is actually shorter than a for loop, by 1 character.

Explanation:

#define S Serial /* This macro is worth it in the end, but not by much */

int p = 0, // the case p = 0 is also taken to mean not to even attempt this anyways
    d = 1;

void setup() {
  S.begin(300); // standard is 9600 but 300 is shorter
}

void loop() {
  while (S.available()) // truthy while there are unread bytes
    p = p * 256 + S.read();

  if (p && !(p % ++d % p)) { // second condition from the C++ answer
    S.print(p == d); // method from the C++ answer
    p = 0; // reset this to stop trying
  }
}

I suppose this technically comes with the caveat that no byte of the number can be 0 (so 256 wouldn't work; it's 0x0100), as the serial port takes in null-terminated strings. That said, it's only two more characters to make a version that accepts numbers written in decimal -- just replace p*256+S.read() with p*10+S.read()-48.

Original:

int p=0,d=1;void setup(){Serial.begin(300);}void loop(){while(Serial.available())p=p*256+S.read();if(p&&!(p%++d%p)){Serial.print(p==d);p=0;}}
\$\endgroup\$
2
\$\begingroup\$

Rust (full program), 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...

\$\endgroup\$
1
  • 2
    \$\begingroup\$ using args is shorter 105 bytes \$\endgroup\$
    – Hydrazer
    Nov 1, 2021 at 15:11
2
\$\begingroup\$

K (ngn/k), 18 bytes

1=+/1>(!x)!'x:.1:0

Try it online!

\$\endgroup\$
2
\$\begingroup\$

WTFstack, 13 bytes

1g{?(!)?/x<{;

WTFstack is my new programming language in which mathematical operations work on the entire stack at once.

Returns a stack of [1] if prime, and an empty stack if composite.

Interpreter

Explanation

1g            # is the input > 1?
  {           # if so, continue. else, print the stack and exit
   ?          # push the user input
    (         # -1
     !        # factorial
      )       # +1
       ?      # push the input again
        /     # divide all values on the stack by the input
         x    # push if the number is an integer or not (0 or 1)
          <   # swap the top two values on the stack
           {  # is the top of the stack truthy? if so, continue, else exit
            ; # discard the top of the stack
\$\endgroup\$
2
\$\begingroup\$

minigolf, 29 bytes

iT+:,:ns,:n*;s,_;*i=+0=s0=0=*

Attempt This Online!

Explanation

Generate a multiplication table of (input-1)x(input-1):

iT+                input - 1
:                  duplicate
,                  map in [1..i-1]:
  :                  duplicate i-1 so that it's preserved across iterations of map
  ns                 swap current iteration item underneath
  ,                  map in [1..i-1]:
    :                  dup curr. iter. item of outer loop (so that it's preserved)
    n*                 multiply by curr. iter. item of this map loop
  ;                  end map
  s,_                swap up & drop our preserved curr. map value
;                  end map

Aftermath of the multiplication table:
*                  flatten
i=                 Set by equality w/ input
+                  sum that
0=                 = 0? (i.e. no items in that table that equals input)
                   Note: at this point we have i-1 underneath our top value
s                  Swap i-1 upwards
0=0=               Set all >0 values to 1
*                  Multiply (i.e. if i-1 is zero, our prime checking output is 0.)
\$\endgroup\$
2
\$\begingroup\$

LiveCode, 128 bytes

on mouseUp
   ask ""
   put it div 2 into i
   repeat with j=2 to it-1
      put it mod j*i into i
   end repeat
   put i>0
end mouseUp

Put in a button and press the button. Asks for a number, puts true or false reporting primality into the message box. LiveCode does support stdin and stdout, but other answers here used this method so I am as well.

A function would make more sense to me, but that doesn't seem to be the accepted method here.

Explanation

Should be pretty clear:

Starts with 0 if the input is 1, or 1 or more if input > 1.

Then for every number from 2 to the input - 1, multiplies the running total by the input modulo the number. If any of the numbers evenly divide the number, the running total will change to (and remain for the rest of the loop) zero.

At the end, report whether the running total is greater than 0. If it is, the input is prime, if it has been zero-ified at any point, the input is not prime.

\$\endgroup\$
2
\$\begingroup\$

GAIA, 1 byte

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and nice answer \$\endgroup\$
    – The Thonnu
    Apr 18 at 19:03
2
\$\begingroup\$

Tabloid, 358 293 bytes

DISCOVER HOW TO x WITH a, b WHAT IF b BEATS 1 WHAT IF ((a DIVIDED BY b) MODULO 1) BEATS 0 SHOCKING DEVELOPMENT x OF a, b MINUS 1 LIES! SHOCKING DEVELOPMENT 0 LIES! SHOCKING DEVELOPMENT 1 EXPERTS CLAIM y TO BE LATEST NEWS ON "" YOU WON'T WANT TO MISS x OF y, y MINUS 1 PLEASE LIKE AND SUBSCRIBE

Input through a JavaScript prompt(), and output 1! if the input is prime and 0! otherwise (exclamation point due to language restrictions)

-65 bytes by using BEATS (greater than) instead of SMALLER THAN (less than) and IS ACTUALLY (equal to), inverting some if conditions on the way

Readable version

DISCOVER HOW TO x WITH a, b
    WHAT IF b BEATS 1
        WHAT IF ((a DIVIDED BY b) MODULO 1) BEATS 0
            SHOCKING DEVELOPMENT x OF a, b MINUS 1
        LIES!
            SHOCKING DEVELOPMENT 0
    LIES!
        SHOCKING DEVELOPMENT 1
EXPERTS CLAIM y TO BE LATEST NEWS ON ""
YOU WON'T WANT TO MISS x OF y, y MINUS 1
PLEASE LIKE AND SUBSCRIBE

Original (358 bytes)

DISCOVER HOW TO x WITH a, b RUMOR HAS IT WHAT IF b SMALLER THAN 2 SHOCKING DEVELOPMENT 1 LIES! RUMOR HAS IT WHAT IF ((a DIVIDED BY b) MODULO 1) IS ACTUALLY 0 SHOCKING DEVELOPMENT 0 LIES! SHOCKING DEVELOPMENT x OF a, b MINUS 1 END OF STORY END OF STORY EXPERTS CLAIM y TO BE LATEST NEWS ON "" YOU WON'T WANT TO MISS x OF y, y MINUS 1 PLEASE LIKE AND SUBSCRIBE

Readable version

DISCOVER HOW TO x WITH a, b RUMOR HAS IT
    WHAT IF b SMALLER THAN 2
        SHOCKING DEVELOPMENT 1
    LIES! RUMOR HAS IT
        WHAT IF ((a DIVIDED BY b) MODULO 1) IS ACTUALLY 0
            SHOCKING DEVELOPMENT 0
        LIES!
            SHOCKING DEVELOPMENT x OF a, b MINUS 1
        END OF STORY
    END OF STORY
EXPERTS CLAIM y TO BE LATEST NEWS ON ""
YOU WON'T WANT TO MISS x OF y, y MINUS 1
PLEASE LIKE AND SUBSCRIBE
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Apr 21 at 1:09
  • \$\begingroup\$ This language should be called “BREAKING NEWS” \$\endgroup\$ May 13 at 13:14
2
\$\begingroup\$

Rockstar, 119 117 107 bytes

Outputs -0.5 for primes and 0 for composites.

listen to N
let D be N
let P be N-1
while P and D-2
let D be-1
let M be N/D
turn M up
let P be N/D-M

say P

Try it here (Code will need to be pasted in)

listen to N         :Read input string into variable N
let D be N          :Initialise D as N
let P be N-1        :Initialise P as N-1, which will be 0 (falsey) if N=1
while P and D-2     :While P and D-2 are not zero
let D be-1          :  Decrement D
let M be N/D        :  Assign N/D to variable M
turn M up           :  Round M up
let P be N/D-M      :  Reassign N/D-M to P
                    :End while loop
say P               :Output P
\$\endgroup\$
2
\$\begingroup\$

Trilangle 1.3, 31 bytes

<'?<#2%._zS<.>(/.,)2-.^\_/!@.)@

Reads a single integer from STDIN, and prints 1 iff it's prime.

Try it on the online interpreter!

TL;DR

Keeps a running counter that starts at 2, and increments it until (input % counter) == 0. Then, it prints '1' if input == counter.

What is Trilangle?

Trilangle is a 2-D stack-based programming language. Program flow can be redirected with "mirrors" /|\_ or with branches <^7>vL. The branches can split, merge, or reflect control flow, depending on how they're used. If the IP walks off the board, it continues one row or diagonal to its left.

Code Explanation

Unfolds to this example from the README:

       <
      ' ?
     < # 2
    % . _ z
   S < . > (
  / . , ) 2 -
 . ^ \ _ / ! @
. ) @ . . . . .

Equivalent to this C code:

#include <stdio.h>

// Get an integer from stdin. Implementation provided by the interpreter.
extern int getint(void);

int main() {
  // RED PATH
  int input = getint();
  int counter = 2;
  while (input % counter)
    // GREEN PATH
    ++n;
  // BLUE PATH
  if (input == counter)
    // YELLOW PATH
    return 0;
  // MAGENTA PATH
  puts("1");
  return 0;
}

This uses the new 2DUP instruction z to make stack management easier: it copies both the input and counter so that they may be operated on non-destructively. The older version below used a combination of j (indexed read), 2 (duplicate), and S (swap) to achieve a similar effect.

Older answer: Trilangle 1.0,  42  41 40 bytes

'2.?..<_.@j.2'2,<|>(%!.\S)S,,)S<.....@>-
\$\endgroup\$
1
\$\begingroup\$

Pyth, 8 bytes

&>Q1!tPQ

Alternative that doesn't support values less than 2:

!tPQ
\$\endgroup\$
0
1
\$\begingroup\$

Perl, 35 bytes

Uses regular expressions...

$_=1x$_;s/^(11+?)\g1+$//;print$_>1

That's 34 bytes of code, plus one byte for the -n switch needed to fetch a line from stdin. Outputs 1 if the number is prime, or nothing otherwise

\$\endgroup\$
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
5 6
7
8 9
12

Your Answer

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

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