192
\$\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\$
  • \$\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
  • \$\begingroup\$ No, the input is a strictly positive integer. \$\endgroup\$ – Dennis Sep 6 '17 at 3:44
  • 1
    \$\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

287 Answers 287

2
\$\begingroup\$

Perl 6, 20 bytes

say get~~$_%%one ^$_

Try it online!

There's also the built-in is-prime, but I thought it would be more interesting to do it without it. Surprisingly, this is only 4 bytes longer.

Explanation:

    get                # Get a line of input
       ~~              # Smartmatch it by setting $_ to input
         $_%%          # Is input divisible by
             one       # Only one of
                 ^$_   # The range 0 to input-1?
say                    # And print

Note that this works because n%%0 is boolified to False.

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

05AB1E, 3 bytes

fнQ

find all factors and see if last one equals input.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Built-ins are allowed, so just p is enough. \$\endgroup\$ – Grimy Mar 29 at 13:32
2
\$\begingroup\$

Gol><>, 4 bytes

ISPh

Thanks to ASCII-only for letting me now I didn't need 2 bytes, since it was redundant.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ The ?1 is needed?????? \$\endgroup\$ – ASCII-only Feb 20 at 16:07
  • \$\begingroup\$ @ASCII-only Thank you for pointing that out, I didn't even think of that. Fixing it now! \$\endgroup\$ – KrystosTheOverlord Feb 20 at 17:23
  • 2
    \$\begingroup\$ At least in this particular implementation of Gol><>, P is implemented by the` is_probably_prime` function. Unfortunately, this challenge requires a deterministic primality test. \$\endgroup\$ – Dennis Feb 20 at 19:37
  • \$\begingroup\$ @Dennis The is_probably_prime function is a wrapper for the sympy isprime function, which is deterministic up to \$2^{64}\$. If the sympy library is not available, then it does a non-deterministic check. \$\endgroup\$ – Jo King Mar 15 at 1:58
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
    \$\begingroup\$ This fails for 1 and 2. \$\endgroup\$ – Ørjan Johansen Mar 16 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\$ – Sophia Lechner Mar 18 at 18:09
2
\$\begingroup\$

Java, 108 bytes

interface P{static void main(String[]a){long l=new Long(a[0]),i=1;for(;0<l%++i%l;);System.out.print(l==i);}}

Try it online!

Port of my Ink answer. Would beat all existing answers in C, C#, Python (2 and 3), and possibly other languages if ported.

Ungolfed

interface PrimeChecker {
    // Unlike members of classes, members of interfaces are public by default. 
    static void main(String[] args) {
        long input = new Long(args[0]),
             div = 1;
        for (; 0 < (  input % (++div) // Trial division, finish when div divides input
                    % input           /* If input is at least 2, this has no effect.
                                         But (1 % n) = 1 for any n > 1
                                         so without this, the loop would never end
                                         when the input is 1 */
                   );
            ) { /* The loop body is empty, we're just using it to set div */ }
        // div is now the lowest number greater than 1 that divides the input
        // (or 2, if the input is 1)

        // The input is prime iff that number is equal to the input
        System.out.println(input == div);
    }
}
\$\endgroup\$
  • \$\begingroup\$ Note for those who, like me, didn't understand the existence of the last %l at first, it's to shortcut the loop when the input is 1. \$\endgroup\$ – Olivier Grégoire May 16 at 15:42
1
\$\begingroup\$

Pyth, 8 bytes

&>Q1!tPQ

Alternative that doesn't support values less than 2:

!tPQ
\$\endgroup\$
  • \$\begingroup\$ Context: The 4-byte version was the only one at the time that comment was posted. \$\endgroup\$ – CalculatorFeline Mar 20 '16 at 4:18
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\$

K, 25 bytes

`0:$~x!1+*/1+!(x:. 0:`)-1
\$\endgroup\$
  • 1
    \$\begingroup\$ How should this be run? I tried kona/k program <<< input, but that doesn't seem to work. \$\endgroup\$ – Dennis Sep 11 '15 at 19:00
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\$
  • \$\begingroup\$ It's possible in 50 bytes. :) \$\endgroup\$ – Emil Lundberg Sep 24 '15 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 '15 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\$ – Emil Lundberg Sep 24 '15 at 15:47
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\$
  • \$\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 '17 at 20:42
  • \$\begingroup\$ You can save another 2 bytes by replacing a(X) with -X. \$\endgroup\$ – 0 ' Dec 23 '17 at 17:33
  • \$\begingroup\$ A bit of competition: codegolf.stackexchange.com/questions/57617/… \$\endgroup\$ – 0 ' Dec 24 '17 at 6:30
1
\$\begingroup\$

JavaScript, 57

Prime finding regex.

alert(!/^1?$|^(11+?)\1+$/.test(Array(prompt()+1).join(1)))
\$\endgroup\$
  • \$\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 '15 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 '15 at 19:59
  • 1
    \$\begingroup\$ Just adding + before the prompt() should work. \$\endgroup\$ – ETHproductions Dec 6 '15 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\$
  • 1
    \$\begingroup\$ all can take a generator, so you don't need []. Also range(a,b) already returns [a, ..., b-1]. \$\endgroup\$ – FryAmTheEggman Sep 17 '15 at 19:50
  • \$\begingroup\$ Cool, thanks for the tip :) \$\endgroup\$ – J Atkin Sep 17 '15 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\$
  • \$\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 '15 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 '15 at 6:58
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\$
  • \$\begingroup\$ p={x->!(2..<x).find{x%it==0}|x==2}, saves 2 bytes. \$\endgroup\$ – Gurupad Mamadapur Jan 17 '17 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\$
  • 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 '15 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\$
  • \$\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 '17 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\$

DStack, 66 bytes

025SSd01kKCccscS0kT0cK1kAsd34SSd1ccd0sd1ddsScsdk0cD0cS0kTcdsKkdtcK
\$\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\$
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\$
  • \$\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 '15 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\$

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\$
  • \$\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 '17 at 1:04
  • \$\begingroup\$ @kernigh print or maybe >string print? why are you asking \$\endgroup\$ – cat Nov 18 '17 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 '17 at 5:59
1
\$\begingroup\$

Pyth, 2 bytes

P_

Try it here!

Pyth now has implicit input!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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