# Is this number a prime?

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

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

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

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

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

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

### 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.

• 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.

## 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

• 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/… Dec 12 '17 at 6:21
• @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. Dec 12 '17 at 12:51
• Could a case be made for locking this challenge and posting a new, less restrictive one? Jun 25 '18 at 12:59
• @Shaggy Seems like a question for meta. Jun 25 '18 at 13:44
• Yeah, that's what I was thinking. I'll let you do the honours, seeing as it's your challenge. Jun 25 '18 at 13:45

# 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.

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

(x>1)&&/x!'2_!1+_sqrt x:0$0: Got this off Rosetta Code, so marked it as community wiki. # 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.

# XSLT 3.0, 209203 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.

# 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.

• 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 Dec 20 '17 at 20:42
• You can save another 2 bytes by replacing a(X) with -X. Dec 23 '17 at 17:33
• A bit of competition: codegolf.stackexchange.com/questions/57617/… Dec 24 '17 at 6:30

# JavaScript, 57

Prime finding regex.

alert(!/^1?$|^(11+?)\1+$/.test(Array(prompt()+1).join(1)))
• 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. Sep 17 '15 at 19:40
• Yeah, I was thinking of a way to fix it. Guess I never got around to actually fixing it...
– RK.
Sep 17 '15 at 19:59
• Just adding + before the prompt() should work. Dec 6 '15 at 18:49

# 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)

• all can take a generator, so you don't need []. Also range(a,b) already returns [a, ..., b-1]. Sep 17 '15 at 19:50
• Cool, thanks for the tip :) Sep 17 '15 at 23:37

# 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

## Scala, 50 bytes

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

In case output to STDERR is forbidden, 65 bytes:

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

# Desmos, 108104 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.

• 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? Sep 29 '15 at 4:31
• 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. Sep 29 '15 at 6:58
• 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. Aug 23 '20 at 5:15

# 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

# 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'}"})
• p={x->!(2..<x).find{x%it==0}|x==2}, saves 2 bytes. Jan 17 '17 at 9:06

# 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;} • 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". Nov 7 '15 at 10:59

# 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.

• 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. Nov 17 '17 at 0:55

# Microscript II, 2 bytes

N;

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

# 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.

# 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.

• 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. Nov 16 '15 at 3:33

# 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. :(

## JavaScript function golf, 16 13 bytes

p(pr(iai()));

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

Returns 1 if prime, else 0.

The variant with the alert costs us 15 bytes.

p2a(pr(iai()));

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

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

## Pyke, 2 bytes

_P

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

# Factor, 56 bytes

Literally ungolfable.

USING: math.primes conv io ;
• I haven't used Factor recently, so I don't remember what must be done to print the t/f result of prime? Nov 17 '17 at 1:04
• @kernigh print or maybe >string print? why are you asking
– cat
Nov 18 '17 at 18:24
• 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. Nov 20 '17 at 5:59

## Pyth, 2 bytes

P_

Try it here!

Pyth now has implicit input!

# Molecule, 3 bytes

Inp

Explanation:

Inp
n  convert to number
p primality test

## LiveCode 8, 708 bytes

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

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

# Unipants' Golfing Language, 53 47 bytes

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

Try it online!

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

# Fith, 30 bytes

*math* load line >int prime? .

This language isn't great for golfing...

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

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

Explanation:

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

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

## C, 54 bytes

i;main(j){for(scanf("%d",&i);i%++j;);putchar(49^j<i);}
• Must be run without parameters, so j is initialized to 1.
• Prints 1 for primes, 0 for composites (no newline).
• Could save 2 bytes with unprintable output - I'm not sure if \x00 and \x01 qualify as falsy/truthy.
• '\0' and '\1' are truthy and falsy according to our definition, so printing NUL or SOH should be fine. Jun 16 '16 at 22:58

# brainfuck, 208 202 bytes

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

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

[->+>+<<]++>[-<->]+<[>-<,]>[->+<]>[[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>-]<<<<<<+[<<<<<<]>>>>>>[-<+>]++[<[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>>][[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<<<<<<]>>>>>>>>[>]>[<+>,]+<[>-<-]>.

## RPN, 16 bytes

lambda x isprime

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

Call like this:

<number> lambda x isprime eval

# Python 3.5, 5852 58 bytes

import math;n=int(input());print(math.factorial(n-1)**2%n)

I unassumed. Thanks Dennis.

I assumed something about the way the input would be given. Thanks daHugLenny.

import math;lambda n:print(math.factorial(n-1)**2%n)

• You can save 13 bytes by using a lambda: import math;lambda n:math.factorial(n-1)**2%n Aug 7 '16 at 2:21
• In this particular challenge, lambdas are not allowed. The spec says Write a full program that... (CC @daHugLenny) Aug 10 '16 at 2:57