# 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/… – Lyndon White 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. – Dennis Dec 12 '17 at 12:51
• Could a case be made for locking this challenge and posting a new, less restrictive one? – Shaggy Jun 25 '18 at 12:59
• @Shaggy Seems like a question for meta. – Dennis 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. – Shaggy Jun 25 '18 at 13:45

# Swift 4, 58 bytes

let n=Int(readLine()!)!;print((1..<n).filter{n%$0<1}==[1]) Try it online! Saved a few bytes thanks to Dennis. ## Wumpus, 13 bytes I=&l2-&*=*r%O Try it online! ### Explanation Uses Wilson's theorem in the form (n-1)!2isprime(n) (mod n) (where isprime gives 0 or 1, respectively). The implementation doesn't really work the way it's supposed to for n = 1, but the result still ends up being 0. I= Read n and duplicate it. &l Push the stack depth n times. Since there's another copy of n on the stack to begin with, this pushes 1, 2, ..., n-1, n. 2- Subtract 2 from n. &* Multiply the top two numbers that many times. This essentially folds multiplication over the range [1,n-1], which computes (n-1)!. At the end of this, the stack will be [n, (n-1)!]. However, in the case of n = 1, we only ever pushed one element for the range, so there's nothing left to form the factorial and the stack contains only one copy of 1. =* Square the (n-1)!. r Reverse the stack. This is normally just used to swap n and (n-1)!², but we're using stack reversal instead of swap (~), so that the stack remains unchanged for n = 1. % Modulo. For n = 1, this computes 0 % 1 = 0 (because there's an implicit zero underneath the 1 on the stack). For all other n, this computes (n-1)!² % n, i.e. the result of the primality test. O Output the result as a decimal integer. The IP then bounces off the end of the program and starts moving left again. % tries another modulo, but there's only implicit zeros on the stack, so the program ends due to the attempted division by zero. # Stax, 2 bytes |p Run and debug online! Added for completeness. An internal. # 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.

# 05AB1E, 3 bytes

fнQ

find all factors and see if last one equals input.

Try it online!

• Built-ins are allowed, so just p is enough. – Grimmy Mar 29 '19 at 13:32

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

• The ?1 is needed?????? – ASCII-only Feb 20 '19 at 16:07
• @ASCII-only Thank you for pointing that out, I didn't even think of that. Fixing it now! – KrystosTheOverlord Feb 20 '19 at 17:23
• 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. – Dennis Feb 20 '19 at 19:37
• @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. – Jo King Mar 15 '19 at 1:58

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

• This fails for 1 and 2. – Ørjan Johansen Mar 16 '19 at 0:22
• 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) – Sophia Lechner Mar 18 '19 at 18:09

# 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);
}
}
• 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. – Olivier Grégoire May 16 '19 at 15:42

# GHC 8.2.2, 716 bytes

{-#LANGUAGE FlexibleInstances,FunctionalDependencies,UndecidableInstances,CPP#-}
#define i instance
#define c class
data F
data T
data S n
data C x s
c A p q r|p q->r
i A F q F
i A T q q
c E p x y z|p x y->z
i E F x y y
i E T x y x
c G x y b|x y->b
i G x F T
i G F(S y)F
i G x y b=>G(S x)(S y)b
c M x y z|x y->z
i M x F x
i M F(S y)F
i M x y z=>M(S x)(S y)z
c D x y b|x y->b
i D x F T
i(G(S y)x p,M(S y)x z,D x z q,A p q b)=>D x(S y)b
c K f x y|f x->y
i D m n b=>K(S n)m b
c I f s n|f s->n
i I f F F
i(K f x b,I f s m,E b(S m)m n)=>I f(C x s)n
c R n s|n->s
i R F F
i R n s=>R(S n)(C(S n)s)
c Q m n b|m n->b
i Q F F T
i Q F(S y)F
i Q(S x)F F
i Q x y b=>Q(S x)(S y)b
c P n b|n->b
i(R n s,I(S n)s m,Q m(S(S F))b)=>P n b

Try it online!

This has got to be the most beautiful code I've ever written. It's a compile-time metaprogram that determines whether a type (represented Peano-style, where F is zero and S n is n's successor) is prime.

This works in GHC 8.2.2, the version TIO currently uses. It works locally in 8.8.3 as well. I have included the language extensions in the code, all except one—the TIO example linked above has MonoLocalBinds to suppress a warning. The program works just fine without them.

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

Output has to be written to STDOUT or closest alternative.

As far as I know, metaprograms like this have no means of I/O. With FunctionalDependencies, typeclasses can act much like functions, and in this way, the typeclass P is a "function" from natural numbers to booleans (T and F—yes, the same type represents zero, false, and the empty list). I believe this to be the closest alternative to the standard streams.

The test suite I provided covers numbers from one to twenty. Try changing any T to F or vice-versa, and the program will fail to compile.

I know there are improvements that can be made, and I'll be updating this answer soonish with them.

# MAWP, 4846 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!

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

# Pyth, 8 bytes

&>Q1!tPQ

Alternative that doesn't support values less than 2:

!tPQ

# 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

0:$~x!1+*/1+!(x:. 0:)-1 • How should this be run? I tried kona/k program <<< input, but that doesn't seem to work. – Dennis Sep 11 '15 at 19:00 # 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.) # 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. :) – Emil Lundberg Sep 24 '15 at 12:07 • @EmilLundberg That code won't run. You need a main method or use the same trick I used. – Martijn 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. – Emil Lundberg Sep 24 '15 at 15:47 # K, 29 bytes (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 – 0 ' Dec 20 '17 at 20:42 • You can save another 2 bytes by replacing a(X) with -X. – 0 ' Dec 23 '17 at 17:33 • A bit of competition: codegolf.stackexchange.com/questions/57617/… – 0 ' 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. – Dennis 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. – ETHproductions 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]. – FryAmTheEggman Sep 17 '15 at 19:50 • Cool, thanks for the tip :) – J Atkin 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 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))) # 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? – lirtosiast 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. – Dennis 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. – Ethan Chapman Aug 23 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. – Gurupad Mamadapur 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". – Blackhole 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. – kernigh 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.