237
\$\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\$ Commented 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
    Commented 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
    Commented Jun 25, 2018 at 12:59
  • 2
    \$\begingroup\$ @Shaggy Seems like a question for meta. \$\endgroup\$
    – Dennis
    Commented 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
    Commented Jun 25, 2018 at 13:45

372 Answers 372

1
9 10 11
12
13
1
\$\begingroup\$

C (gcc), 119 71 69 bytes

p;main(a){for(scanf("%d",&p);++a<p;)p=p/a*a-p?p:1;puts(p-1?"1":"0");}
  • Thanks to ceilingcat for the reduction to 71 bytes.

  • Thanks to ceilingcat for another 2 bytes shaved off by using puts instead of printf.


Outputs 0 (falsy) when it's composite and 1 (truthy) when it's prime.

My first C answer. To me, it's just a mix of Python and Assembly. Well, at least it's probably not as long as Java...

printf("Try it online!")

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Putting headings that don’t provide semantic purpose is i usually not great for accessibility tools like screen-readers, but it’s probably not that big a deal here \$\endgroup\$ Commented Aug 1, 2023 at 23:22
1
\$\begingroup\$

Uiua, 19 bytes

=2/+⌕0◿+1⇡.parse&sc

If this was just a function, it'd be 10 bytes. But it's a full program so the parse function is needed :sob:

Thanks Dennis very cool.

Explained

=0/+¬±◿↘2⇡.parse&sc­⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢​‎⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁣​‎⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁡​‎⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌­
          .parse&sc  # ‎⁡Read the input as a number (which I wouldn't need if this was a function submission)
       ↘2⇡.          # ‎⁢Range [2, input)
      ◿              # ‎⁣input % n for each n in ^
    ¬±               # ‎⁤And invert the sign. Honestly this could just be `=0`, but where's the fun in that.
  /+                 # ‎⁢⁡Summate that 
=0                   # ‎⁢⁢Does the sum equal 0?
💎

Created with the help of Luminespire.

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

JavaScript (Node.js), 30 bytes

f=(n,i=n)=>i==2||n%--i&&f(n,i)

Attempt This Online!

2 bytes longer than this solution but uses a slightly different method so I thought I'd post it.

Returns falsey (0 or NaN) for composite, true for prime.

Pretty simple - checks n % i for all i from n down to 2, returning 1 only if 2 is reached.

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

Cabsi, 108 bytes

1PUSH 1,""
2INPUT
3DUP
4DEC
5DUP
6ROT
7DUP
8ROT
9MOD
10JNP 90
11POP
12SWAP
13GOTO 4
90POP
91POP
92EQ
93PRINT

Try it

Cabsi is Conor O’Brien’s new stack-based BASIC derivative. It has 2 stacks, but this solution only uses one of them. This is a full program, taking an integer from STDIN and outputting a zero or a one.

Explanation:

1   PUSH 1,"" REM. Stack [1 ""]
2   INPUT     REM. Stack [1 N]            Print the string, push an int from STDIN
3   DUP       REM. Stack [1 N N]

4   DEC       REM. Stack [1 N D]          D is the denominator, decremented every iteration, starts at N-1
5   DUP       REM. Stack [1 N D D]
6   ROT       REM. Stack [1 D D N]
7   DUP       REM. Stack [1 D D N N]
8   ROT       REM. Stack [1 D N D N]
9   MOD       REM. Stack [1 D N (N % D)]
10  JNP 90    REM. Stack doesn’t change.  If the result of the modulo was 0, jump to 90
11  POP       REM. Stack [1 N-1 N]
12  SWAP      REM. Stack [1 N N-1]
13  GOTO 4    REM. Stack doesn’t change.  Jump to line 4

90  POP       REM. Stack [1 D N]          At this point, N was divisible by D
91  POP       REM. Stack [1 D]
92  EQ        REM. Stack [(D == 1)]       If the denominator is 1, then N is prime, otherwise it’s composite
93  PRINT     REM. Write to STDOUT
\$\endgroup\$
1
\$\begingroup\$

Uiua, 10 bytes (SBCS)

=1⧻°/×⋕&sc

Try it in the pad!

All the other Uiua answers are from extremely old versions which use features that have since been changed.

This answer makes use of the °/× un reduce multiply function, which gets the prime factorization of a number, and then checks if the length of that is one.

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

iogii 7 bytes

(}P:*$%

Try it!

Using the formula (n-1)!^2%n

( deincrement   } countTo   P product    # take (n-1)!
: duplicate     * multiply               # take the square of that
$ argument      % modulo                 # take result % n

6 bytes is almost possible but doesn't work for 1:

:(}%tP

run it

: dup input
( deincrement   } countTo
% vectorized mod
t tail (to remove the %1)
P product (if any 0's then 0, which is falsey, 
           else it will be some >0 number, which is truthy)
\$\endgroup\$
3
  • 1
    \$\begingroup\$ This gives the wrong output for \$1\$. By the challenge's rules, an input of 1 must yield an output of falsey. \$\endgroup\$
    – Deadcode
    Commented Nov 3 at 16:57
  • 1
    \$\begingroup\$ :}%0q_2q is a simple fix for 8, but 7 feels possible \$\endgroup\$ Commented Nov 3 at 17:16
  • \$\begingroup\$ Thanks, so annoying that 1 isn't considered prime... \$\endgroup\$ Commented Nov 3 at 18:46
1
\$\begingroup\$

BrainChild, 81 57 bytes

include*;int j=int i=getint();while(--j&&i%j)0print(j==1)

Saved 24 bytes thanks to @Deadcode

Readable

include io.bc;
int i = getint();
int j = i;
while(--j && i%j){}
print(j==1)

Try It Online!

\$\endgroup\$
1
  • \$\begingroup\$ 60 bytes: function(int i)->int{int j=i;while(--j&&i%j>0){}return j==1} and better is likely possible, perhaps with recursion. But also this breaks the rules of the challenge, which requires a full program. \$\endgroup\$
    – Deadcode
    Commented Nov 3 at 17:31
0
\$\begingroup\$

STATA, 62 bytes

di _r(a)
gl c=$a-1
forv b=2/$c{
if!mod($a,`b') gl c=0
}
di $c

Ungolfed

display _request(number)
global maxtest = $number-1
forvalues counter=2/$maxtest{
    if !mod($number,`counter') global $maxtest = 0
}
display $maxtest

This tests every integer from 2 to number-1 for divisibility. By printing number-1 as the output, it prints a 0 for an input of 1. Today I learned that STATA has truthy/falsey values. Previously I assumed I could only use (in)equalities in conditions. Note: this does not yet work in the online interpreter and is only valid in the proprietary STATA interpreter.

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

Mathematica, 33 bytes or 61 bytes

Two answers are provided:

Manipulate[PrimeQ[n],{n,1,255,1}]


<<PrimalityProving`
Manipulate[ProvablePrimeQ[n],{n,1,255,1}]

As explained in the implementation documentation, PrimeQ[] is known to produce correct output for arguments less than 10^16 (though is widely believed, on heuristic arguments, to be correct for any input). (User Charles claims this bound can be increased to 2^64 ~= 10^19 in an answer here.) It tests for small primes, uses Miller-Rabin with bases 2 and 3, then uses a Lucas test. ProvablyPrimeQ[] uses a much slower testing procedure, Atkin-Morain (reference with further citations), but is known to be correct and can produce a certificate of primality or witness of compositeness, if desired. So, PrimeQ[] meets the challenge (255 is much less than 10^16), but ProvablyPrimeQ[] meets the specification "primality test" without reservation.

These wrap the PrimeQ[] call into a widget for user interaction. See the docs for a visual example. This widget provides a slider over the range 1 to 255 with unit increments. Next to the slider is a button to provide additional controls: a textbox for direct input and "playback" controls. It's interesting (at most, three times :-) ) to watch this widget iterate through the range.

\$\endgroup\$
7
  • \$\begingroup\$ The rule for hardcoding are "If (and only if) your language is unable to accept any kind of user input" (emphasis mine). Mathematica can take user input, so I believe it needs to use that (see this answer for an example). \$\endgroup\$
    – Sp3000
    Commented Sep 13, 2015 at 12:50
  • \$\begingroup\$ @Sp3000 : Huh. Did not know about Input[]. So, ..., is the local protocol to withdraw the whole solution, or keep the documentation that the solution you cite (and many others here) do not provably test for primality? \$\endgroup\$ Commented Sep 13, 2015 at 23:55
  • \$\begingroup\$ @Sp3000 : I now also perceive a bit of a gap between the rule you reference and the other rule "If your language is able to read from STDIN or accept command-line arguments". I certainly can't make Mathematica do that (and I think this negative capability is why I went the way I did). But I agree that Mathematica meets the description you have. Yet I can imagine settings where neither clause applies. \$\endgroup\$ Commented Sep 13, 2015 at 23:59
  • \$\begingroup\$ The rule you mention was indeed badly phrased, so I've rephrased it. However, the rule Sp3000 mentioned clearly stated that hardcoding is only allowed if there are no alternatives. Since Mathematica has Input[], your three snippets are invalid in its current form. \$\endgroup\$
    – Dennis
    Commented Sep 14, 2015 at 3:59
  • \$\begingroup\$ @Dennis : The third snippet receives user input, as described. \$\endgroup\$ Commented Sep 14, 2015 at 6:33
0
\$\begingroup\$

Mumps, 29

R J F I=2:1:J W:I=J J Q:J#I=0

Output is nothing if not prime, repeat the number if prime. [[ Looks kind of ugly, but I did this to save a carriage return, as carriage returns aren't echoed on user input. It was also easier to see the number out again than just a 1 or zero, that was confusing on longer queries, especially if they contained a '1' at the end. ]]

Test runs:

USER>R J F I=2:1:J W:I=J J Q:J#I=0
1234312343
USER>R J F I=2:1:J W:I=J J Q:J#I=0
12345
USER>R J F I=2:1:J W:I=J J Q:J#I=0
11141111114111

In these three runs, 12343, 12345 and 1114111 are the inputs (the 'R J' reads standard input into the J variable - but the carriage return is not echoed to the output).

As 12343 is a prime, it's echoed directly after the input; as 12345 is not prime, it sits alone. 1114111 is prime, but if I output just a single '1' to indicate prime, it would be much more difficult to tell if it was or not. I leave it up as an exercise to the reader to remember what was entered for the input number. :-)

[[ I wanted to output a character like '*', but then I would have needed to enclose that in quotes thereby making the answer longer. As would adding my own carriage returns...]]

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

VBA, 160 bytes

For casuals only. Is MsgBox a STDOUT equivalent?

Sub p(n)
Dim t
For i = 2 To n - 1
If n / i = Int(n / i) Then t = True
Next
If t <> True Then
MsgBox n & " is truthy"
Else
MsgBox n & " is falsy"
End If
End Sub
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Your code can be significantly improved to Sub p() For j=2To n+1 t=IIf(n Mod j=0Or n<2,"falsy","truthy") Exit For Next Debug.? IIf(n=2,"truthy", t) End Sub 112 bytes \$\endgroup\$ Commented Aug 21, 2016 at 12:50
0
\$\begingroup\$

Actionscript 3, 504 bytes

There are 265 bytes for the actual code. Nearly half the bytes come from the required xml file used by Adobe Debug Launcher to run the swf.

This is run by executing adl P-app.xml -- n to test n, followed by echo %errorlevel% to see the result.

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://ns.adobe.com/air/application/18.0"><id>P</id><filename>P</filename><versionNumber>1.0</versionNumber><initialWindow><content>P.swf</content></initialWindow></application>
package{import flash.desktop.*;import flash.display.*;public class P extends Sprite{public function P(){var n=NativeApplication.nativeApplication;n.addEventListener('invoke',function(e){var p=e.arguments[0],i=2,c=p==1?0:1;while(c>0)c*=p%++i;n.exit(int(p==i));});}}}
\$\endgroup\$
0
\$\begingroup\$

C++, 96 bytes

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

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

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

Yorick, 20 characters

is_prime(read(,"i"))

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

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

VBA Excel - 53 bytes

Golfed, to run in the immediate window :

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

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

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

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

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

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

Hassium, 140 Bytes

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

Lengthy:

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

Mathcad 15, 15 bytes

valid in both Mathcad 15 and Mathcad Prime 3.1

not valid in Mathcad Prime Express (no symbolics)

n:=103   IsPrime(n)->

where -> is the symbolic evaluation operator

although

IsPrime(103)->

would be shorter still

edit 103 to taste

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

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

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

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

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

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

Burlesque, 7 bytes

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

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

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

AniRad, 30 29 bytes

Probably not the shortest program:

 #
 W
 I
 P
 v
 >~1=
 ~
 0
 =

Another possible program is, 30 bytes:

#WIP>v~0=
     ~
     1
     =

Information:

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

The following paths are executed in this program:

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

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

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

DStack, 66 bytes

025SSd01kKCccscS0kT0cK1kAsd34SSd1ccd0sd1ddsScsdk0cD0cS0kTcdsKkdtcK
\$\endgroup\$
0
\$\begingroup\$

Gogh, 1 byte

e

Run using:

$ ./gogh oi "e" <input>

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

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

Pylongolf2, 4 bytes

cnz~

Explanations:

cnz~
c    read input
 n   convert to integer
  z  primality test (beta8+)
   ~ print it.
\$\endgroup\$
0
\$\begingroup\$

Racket, 31 bytes

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

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

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

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

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

Old one, for 64:

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

Sage, 22 bytes

lambda N:N in Primes()

Try it online

\$\endgroup\$
1
  • \$\begingroup\$ (Super old but...) Submissions have to be full programs. \$\endgroup\$ Commented Sep 2, 2017 at 2:17
0
\$\begingroup\$

UGL, 26 bytes

id?u:cuul^^/_c=?_=ocd$:_u:

Try it online!

How it works:

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

reticular, 6 bytes

in@pp;

A four-byte function:

[@p]

Explanation

in@pp;
i       take input
 n      convert to number
  @p    check for primality
    p   print
     ;  terminate
\$\endgroup\$
0
0
\$\begingroup\$

R, 19 Bytes

 ->n;sum(!n%%1:n)==2

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

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

sum(!(n=scan())%%1:n)==2
or
n=scan();sum(!n%%1:n)==2

Which assigns within the operator.

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

 p=function(n)sum(!n%%1:n)==2
\$\endgroup\$
0
\$\begingroup\$

RProgN, 102 Bytes

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

Explanation

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

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

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

Pyret, 58 bytes

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

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

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

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

Yabasic, 43 bytes

Input""n
For d=2To n
p=p+!Mod(n,d)Next
?p=1

Try it online!

\$\endgroup\$
1
9 10 11
12
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.