[Question]
      [
Your task is to create the shortest infinite loop!
The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.
## Rules
* Each submission must be a full program.
* You must create the shortest infinite loop.
* Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.
* The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.
* The program must not write anything to STDERR.
* Feel free to use a language (or language version) even if it's newer than this challenge.
-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. **:D**
* Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.
* This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.
* 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 Brainf\*\*k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
* There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like `#[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes`.
* Standard loopholes are not allowed.
(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be improved.
## Catalogue
This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:
```
# Language name, X bytes
```
Obviously replacing `Language name` and `X bytes` with the proper items. If you want to link to the languages' website, use this template, as posted above:
```
#[Language name](http://link.to/the/language), X bytes
```
Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)
```
var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//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"//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,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.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())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)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<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>
```

[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 0 bytes
```
```
Alternatively, *any* single character does exactly the same.
**[Test it online!](https://ethproductions.github.io/cubix/?code=)**
Cubix is a stack-based 2D language, created by me in March 2016. Cubix differs from ordinary 2D languages in that it's not strictly 2D: the code is wrapped around a cube. Any one-byte program wraps to this cube net:
```
   ?
>. . . .
   .
```
where `?` represents the character, and the IP (instruction pointer) starts at the arrow. `.` is simply a no-op, and when the IP reaches the right side of the cube net, it simply wraps back around to the left. Thus, any 1-byte program does nothing forever, no matter what the character is (as long as it's not whitespace).
Thanks to [@ErikGolferエリックゴルファー](https://codegolf.stackexchange.com/users/41024/erikgolfer%e3%82%a8%e3%83%aa%e3%83%83%e3%82%af%e3%82%b4%e3%83%ab%e3%83%95%e3%82%a1%e3%83%bc) for reminding me that the empty program does the same. When Cubix was originally created, this didn't work, because the interpreter created a cube of size 0 and threw an error when it tried to run. This was fixed a while ago, and it is now impossible to cause an error in Cubix.
[Answer]
# Java6 : 25 Bytes
In Java 6 and previous versions you can execute `static` initialization block without having `main` in your class file.
```
class A{static{for(;;);}}
```
[Answer]
# [Processing](https://processing.org/), 8 bytes
```
for(;;);
```

This is based on Geobit's answer in Java

Although the code below is not the shortest, it is one of Processing's specialties.
```
void draw(){}
```
This `draw` statement repeats itself over and over again. It is one of the differences between Processing and Java.
[Answer]
# [CJam](http://sourceforge.net/p/cjam/wiki/Home/), 4 bytes
```
1{}h
```
Put a 1 on the stack, and loop until 1 is no longer truthy. Using `h` means that the number is never popped.
[Answer]
# [Beam](http://esolangs.org/wiki/Beam), 2 bytes
There is a few ways of doing this from the very basic
```
><
```
to the very basic
```
>?
```
and
```
>|
```
[Answer]
# C++ 11 template metaprogramming, ~~58~~ 54 bytes
```
template<int>struct I{int v=I<1>{}.v;};int a=I<1>{}.v;
```
C++ helpfully comes packaged with 2 other turing complete languages: the C preprocessor, and template metaprogramming. Note that this does reach a max recursion depth at some point, but the OP clarified that this is okay.
[Example run](http://coliru.stacked-crooked.com/a/c8fd53d5c126112b):
>
>
> ```
> g++: internal compiler error: Segmentation fault (program cc1plus)
> Please submit a full bug report,
> with preprocessed source if appropriate.
> See <http://gcc.gnu.org/bugs.html> for instructions.
>
> ```
>
>
[Answer]
# COBOL, 51 bytes
```
ID DIVISION.PROGRAM-ID.A.PROCEDURE DIVISION.B.GO B.
```
[Answer]
# Rust, 17 bytes
Didn't see one in rust so:
```
fn main(){loop{}}
```
real original and interesting and so different from all the other entries.
[Answer]
# [Half-Broken Car in Heavy Traffic](http://metanohi.name/projects/hbcht/#heading1.2.3), ~~5~~ 4 bytes
```
^ov#
```
also in 4 bytes:
```
o
 #
```
[Answer]
# [Binary Lambda Calculus](https://tromp.github.io/cl/cl.html), 3 bytes
Before I dive into the explanation, let's start with the program itself.
```
F†€
```
Trust me, it's pure luck that they're all printable, and I'll get to why it is 2 1/4 bytes instead of 3 after the explanation. I'll explain this by walking through the process I took to create this program.
To start, BLC programs are just lambda calculus programs encoded in a special way. With this in mind, let's begin with the lambda calculus program that enters an infinite loop, known as omega.
```
(λx.xx)(λx.xx)
```
This results in an infinite loop because, according to Wikipedia, it reduces to itself after a single beta-reduction. To convert this into BLC, we must first convert it to [De Bruijn indices](https://en.wikipedia.org/wiki/De_Bruijn_indices). It converts into the following:
```
.λ.11λ.11 (The dots after the λs are necessary for BLC but not part of De Bruijn indices)
```
Okay, now that it's in De Bruijin indices we can now convert it into BLC where `λ` translates to `00`, function application or `.` translates to `01`, and numbers are represented as `1^n0` where `n` is the number. Knowing this, it translates into the following binary:
```
01 00 01 10 10 00 01 10 10
```
This is why it's 2 1/4 bytes. As BLC instructions aren't full bytes (with the exception of 7), it is rare for programs to fit exactly into a certain byte count. To turn this into hex, we have to pad it in order to make it fit into 3 bytes. Doing this yields the following:
```
46 86 80
```
There we have the hex dump of our program! It runs in an infinite loop, doesn't run out of memory to my knowledge, doesn't output anything, and is a complete program that can be saved and run by piping the contents of the file to the official interpreter. You can also pipe the binary text to the interpreter and add the -b flag, to demonstrate that the non-padded version can be run.
[Answer]
# Commodore Basic, 3 bytes
```
1R╭
```
PETSCII substitution: `╭` = `SHIFT+U`, ungolfs to `1 RUN`.
Taking advantage of Commodore Basic's shortcut forms and the fact that any immediate-mode command can also be used in a program, this code simply runs itself, forever.
Alternatively, a more thoroughly infinite loop is the immediate-mode command
```
S|7
```
(PETSCII: `|` = `SHIFT+Y`, ungolfs to `SYS 7`).
This transfers execution to memory location 0x0007. The BASIC interpreter stores the current search character here; when running the above code, this character is the double-quotation mark with byte value 0x22. Opcode `0x22` is an [undocumented `HALT` opcode](http://www.pagetable.com/?p=39), which works by putting the 6510's micro-operation interpreter into an infinite loop. The only way out of this loop is to reset the computer.
[Answer]
# Tcl/Tk, 0 bytes
Execute any empty file with the `wish` interpreter instead of `tclsh`.
[Answer]
# TI-BASIC, 2 bytes
If recursion is allowed (is it a loop?)
```
prgmA
```
Runs a program named 'A', hence the program must be named the same. Some research revealed that `prgm` is 1 byte, plus 1 byte for `A`
Runs out of memory pretty quickly, but that doesn't seem to be addressed above.
[Answer]
# x86-16 Assembly, IBM PC DOS, 2 bytes
There's quite a few machine code answers, but thought I'd contribute a few different takes.
```
56    PUSH SI    ; push 100H onto stack
C3    RET        ; pop stack and jump to address (PUSH SI)
```
On DOS when a program is started the `SI` register contains the starting address of the program (generally `100H`). Push that onto the stack and execute a `RET` which will pop the stack and jump to that address. Big ol' loop.
---
### x86-16 Assembly, 1 byte
```
F4   HLT         ; halt the processor and wait for signal
```
Okay, so this may depend a little on your definition of infinite loop. The `HLT` instruction (specifically in 8086 real mode) puts the processor in HALT state and awaits a signal in the form of `BINIT#`, `INIT#`, `RESET#` or interrupt ([ref](https://www.felixcloutier.com/x86/hlt)). While it's not technically executing our code, it is in a microcode loop of sorts waiting for one of those signals.
---
### Motorola 6800, 2 bytes
```
9D DD   HCF      ; halt and catch fire
```
From [Wikipedia](https://en.wikipedia.org/wiki/Halt_and_Catch_Fire#Motorola_6800):
>
> When this instruction is run the only way to see what it is doing is with an oscilloscope. From the user's point of view the machine halts and defies most attempts to get it restarted. Those persons with indicator lamps on the address bus will see that the processor begins to read all of the memory, sequentially, very quickly. In effect, the address bus turns into a 16 bit counter. However, the processor takes no notice of what it is reading… it just reads.
>
>
>
[Answer]
# MUMPS, 1 byte
```
f
```
This is the equivalent of `for ( ; ; ) ;` in C-like languages. It runs from the prompt as is, though, and does not need to be wrapped in a function declaration or any such thing.
[Answer]
# GNU dc, 6 bytes
```
[dx]dx
```
Tail recursion FTW, which GNU dc supports. Others might not.
[Answer]
# [MSM](http://esolangs.org/wiki/MSM), 2 bytes
```
ee
```
Almost all 2 character strings will work, even two spaces, just don't use any of the following 6 commands `:,/.?'`.
[Answer]
# Javascript (8 bytes)
```
for(;;);
```
Edit courtody of @KritixiLithos
# Javascript (10 bytes)
```
while(1){}
```
[Answer]
# Scheme, 12 bytes
A tail-recursive infinite loop seems most appropriate for scheme `:-)`
```
(let l()(l))
```
even though `(do(())())` (the CL variant of which is due to [@JoshuaTaylor](https://codegolf.stackexchange.com/questions/59347/shortest-infinite-loop-producing-no-output/59378#comment143074_59375)) would be 2 bytes shorter.
[Answer]
# z80 Machine Code, 1 byte
```
c7       ; RST 00h
```
Or if assuming the code starts at `0000h` is cheating, two bytes:
```
18 fe    ; JR -2
```
These solutions make no assumptions about the rest of the environment's RAM. If it's filled with zero bytes, we are just spinning through `NOP`s forever, so we could have a 0-byte solution. (Thanks to Thomas Kwa for pointing this out.)
[Answer]
# Fortran, 11 bytes
It is not very creative, but here is the shortest I found:
```
1goto 1
end
```
I am pretty sure this is not standards compliant, but it compiles with `ifort`.
[Answer]
# [3var](http://esolangs.org/wiki/3var), 2 bytes
```
{}
```
To quote the docs:
```
{   Starts a loop which repeats forever
}   Ends a loop which repeats forever
```
[Answer]
# [R](https://en.wikipedia.org/wiki/R_(programming_language)), 8 bytes
```
repeat{}
```
I believe this is the shortest way to make a loop that won't stop. We would need an infinite length list to use a for loop and `while(T)` is longer than `repeat`.
[Answer]
# NASM/YASM x86 assembly, 4 bytes
```
ja $
```
`$` is the address of the current instruction, and `ja` jumps there if the carry and zero flags are both unset. (i.e. the Above condition is true.) This is the case in x86-64 Linux at process startup.
`ja$` just defines a symbol, instead of being an instruction, so the space is not optional. I did test that this works without a trailing newline, so it really is 4 bytes.
Assemble/link with
```
$ yasm -felf64 foo.asm && ld -o foo foo.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
```
The [x86-64 ABI](http://www.x86-64.org/documentation/abi.pdf) used by Linux doesn't guarantee anything about the state of registers at process startup, but Linux's actual implementation zeroes all the registers other than RSP for a newly-`exec`ed process. `EFLAGS=0x202 [ IF ]`, so `ja` (jump if Above) does jump, because the carry and zero flags aren't set. `jg` (ZF=0 and SF=0) would also work. Other OSes that initialize flags differently might be able to use one of the other one-letter conditions that require a flag bit to be set: `jz`, `jl`, `jc`, `jp`, `js`.
Using `ja` instead of `jmp` (unconditional jump) makes the source one byte shorter, but the binary is the same size (2 bytes: one opcode byte, one rel8 displacement, for a total size of 344 bytes for a stripped ELF64 binary. See [casey's answer](https://codegolf.stackexchange.com/a/59479/30206) for a 45 byte ELF executable if you're interested in small binary size rather than small source size.)
[Answer]
# AT&T (PDP-11) Syntax Assembly: 4 bytes
```
br .
```
# PDP-11 UNIX A.OUT binary output: ~~24~~ 18 bytes
```
0000000  000407 000002 000000 000000 000000 000000 000000 000000
0000020  000777 000000 000000 000004
0000030
```
This is the output produced by the assembler. As the sizes in the header show, the last three words are not necessary, it can be cut down to the first 18 bytes.
Some modern assemblers do not support the br instruction, so it would be **five bytes** for `jmp .`. And executable headers are generally much bigger these days.
# Linux x86-64 binary output, after strip: 336 bytes
Now, OSX's assembler is much more strict. You must have a symbol (by default `start`, but here I use `f`) for the entry point, which balloons the size of the source. It also requires a newline at the end of the file.
# Mac OS X x86-64 Assembly: 17 bytes
```
.globl f
f:jmp f
```
# Mac OS Mach-O Binary Output: 4200 bytes
[Answer]
# [pb](https://esolangs.org/wiki/Pb), 8 bytes
In pb, the shortest possible infinite loop is 8 bytes long. In fact, there are sixty 8 byte infinite loops, none of which produce output! (Unless you're running in watch mode, which is intended for debugging, no pb programs produce output until they halt. However, even if one of these did eventually halt, no output would have been produced.) Here are the sixty shortest infinite loops, in alphabetical order:
```
w[B!1]{}
w[B!2]{}
w[B!3]{}
w[B!4]{}
w[B!5]{}
w[B!6]{}
w[B!7]{}
w[B!8]{}
w[B!9]{}
w[B=0]{}
w[C!1]{}
w[C!2]{}
w[C!3]{}
w[C!4]{}
w[C!5]{}
w[C!6]{}
w[C!7]{}
w[C!8]{}
w[C!9]{}
w[C=0]{}
w[P!1]{}
w[P!2]{}
w[P!3]{}
w[P!4]{}
w[P!5]{}
w[P!6]{}
w[P!7]{}
w[P!8]{}
w[P!9]{}
w[P=0]{}
w[T!1]{}
w[T!2]{}
w[T!3]{}
w[T!4]{}
w[T!5]{}
w[T!6]{}
w[T!7]{}
w[T!8]{}
w[T!9]{}
w[T=0]{}
w[X!1]{}
w[X!2]{}
w[X!3]{}
w[X!4]{}
w[X!5]{}
w[X!6]{}
w[X!7]{}
w[X!8]{}
w[X!9]{}
w[X=0]{}
w[Y!1]{}
w[Y!2]{}
w[Y!3]{}
w[Y!4]{}
w[Y!5]{}
w[Y!6]{}
w[Y!7]{}
w[Y!8]{}
w[Y!9]{}
w[Y=0]{}
```
These all follow a simple pattern. `w` is a while loop, pb's only looping or branching instruction. Inside the square brackets is the condition, which is two expressions separated by `!` or `=`. To understand what this means, imagine an extra `=` just before the second expression. In the same way that you understand `2+2==4` to be true and `10!=5*2` to be false, `2+2=4` and `10!5*2` are true and false in pb. A while loop is executed until the condition becomes false. Finally, there is a pair of curly braces containing pb code. In this case, there's no code to be run, so they are empty.
The important thing here is the condition. pb has six variables, all for different purposes. They are:
```
B - The value of the character under the brush
C - The colour of the character under the brush (from a lookup table, the important thing being that white = 0)
P - The current colour that the brush is set to output in (same lookup table)
T - Set by the programmer, initialized to 0
X - X position of the brush
Y - Y position of the brush
```
The brush starts at (0, 0) on a canvas that is entirely initialized to white null bytes. This means that all of the variables start out being equal to 0.
These sixty programs fall into two categories: 10 loops that are executed until a variable (equivalent to 0) stops being zero, and 50 loops that are executed until a variable (equivalent to 0) becomes a specific non-zero number. An infinite number of programs can be written that fall into that second group, but only 50 are the same length as the 10 in the first one.
[Answer]
# ArnoldC, 61 bytes
```
IT'S SHOWTIME
STICK AROUND 1
CHILL
YOU HAVE BEEN TERMINATED
```
Ironic how the program never actually terminates, even though the last line says "YOU HAVE BEEN TERMINATED."
[Answer]
## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 7 bytes
```
#{?
#{?
```
The `#` could be replaced by any other characters except null-bytes or underscores.
The idea is fairly simple:
* Brian moves Chuck's instruction pointer to the start (`{`) and hands control
over to him (`?`).
* Chuck moves Brian's instruction pointer to the start (`{`) and hands control over to him (`?`).
* Repeat.
[Answer]
# [Seed](https://esolangs.org/wiki/Seed), 2 bytes
```
0
```
*(note the trailing space character)*
Any seed program consists out of 2 instructions, seperated by a space; The length of the [Befunge](https://esolangs.org/wiki/Befunge) program it will output and the seed which will generate that program.
Seeing how [we need a Befunge program of length 0](https://codegolf.stackexchange.com/a/59357/41257), we can create a Seed program with an empty 2nd instruction.
The Seed program `0` will output an empty Befunge program, which will run forever.
Interesting to note is that the Python compiler on the [Seed esolang page](https://esolangs.org/wiki/Seed) is erroneous.
To create a Befunge program of length 0, any seed will do. That includes an empty seed. To stick to the spec however, the space after `0` is not omitted.
That being said, this is the world's shortest Seed program, and also the easiest to reverse engineer :-)
[Answer]
# [Aubergine](http://esolangs.org/wiki/Aubergine), 6 bytes
```
:aa=ia
```
`:aa` is a no-op. `=ia` sets the IP to its own location.
]


[Question]
      [
Believe it or not, we do not yet have a code golf challenge for a simple [primality test](https://en.wikipedia.org/wiki/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](http://rosettacode.org/wiki/Miller-Rabin_primality_test) specifically and another using [trial division](http://rosettacode.org/wiki/Primality_by_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!"](https://codegolf.stackexchange.com/q/55422/20469) and [Golf you a quine for great good!](https://codegolf.stackexchange.com/q/69/20469).
Furthermore, the capability of implementing a primality test is part of [our definition of programming language](http://meta.codegolf.stackexchange.com/a/2073), 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](http://meta.codegolf.stackexchange.com/a/2194) 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](http://meta.codegolf.stackexchange.com/a/2194) (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](http://www.dangermouse.net/esoteric/piet.html), for example, will be scored in codels, which is the natural choice for this language.
Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/).
* 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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") 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>
```

[Answer]
# K, 29 bytes
```
(x>1)&&/x!'2_!1+_sqrt x:0$0:`
```
Got this off [Rosetta Code](http://rosettacode.org/wiki/Primality_by_trial_division#K), so marked it as community wiki.
[Answer]
# 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.
[Answer]
# 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.
[Answer]
# 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.
[Answer]
# JavaScript, 57
Prime finding regex.
```
alert(!/^1?$|^(11+?)\1+$/.test(Array(prompt()+1).join(1)))
```
[Answer]
# 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)
[Answer]
# 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
```
[Answer]
## 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)))
```
[Answer]
# [Desmos](http://desmos.com/), ~~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.
[Answer]
# [Simplex v.0.5](http://conorobrien-foxx.github.io/Simplex/), 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
```
[Answer]
# 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'}"})
```
[Answer]
# PHP, 59 bytes
Credit goes to [Geobit's answer](https://codegolf.stackexchange.com/a/57625/46623). 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;}
```
[Answer]
# 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.
[Answer]
# [Microscript II](http://esolangs.org/wiki/Microscript_II), 2 bytes
```
N;
```
Unlike the original Microscript, Microscript II provides a builtin for primality testing.
[Answer]
# 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`.
[Answer]
# 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.
[Answer]
# [Mouse-2002](https://github.com/catb0t/mouse15), 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. :(
[Answer]
## [JavaScript function golf](http://schas002.github.io/js-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](https://github.com/schas002/js-function-golf/commits/gh-pages) 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.
```
[Answer]
## [Pyke](https://github.com/muddyfish/PYKE), 2 bytes
```
_P
```
If the P function is given a negative number, it returns whether it's prime or not.
[Answer]
# Factor, 56 bytes
Literally ungolfable.
```
USING: math.primes conv io ;
readln string>number prime?
```
[Answer]
## Pyth, 2 bytes
```
P_
```
[Try it here!](http://pyth.herokuapp.com/?code=P_&input=7&debug=0)
Pyth now has implicit input!
[Answer]
# Molecule, 3 bytes
```
Inp
```
Explanation:
```
Inp
I   read input
 n  convert to number
  p primality test
```
[Answer]
## LiveCode 8, 708 bytes
```
on mouseUp
    ask ""
    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.
[Answer]
# [Unipants' Golfing Language](https://github.com/schas002/Unipants-Golfing-Language), ~~53~~ 47 bytes
```
i$cu^d^-l_u^^/%cu%?%d%:_?coc$d$$:__^d^-:_u?cuo:
```
[Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aSQKY3UgIzYgMQpeZF4tbCAjd2hpbGUgbm90IGVxdWFsCl8gIzYgMQp1ICM2IDIKXl4vJSAjNiAyIDMgMApjdSU_JWQlOl8gIzYgMiAzICJ0cnVlIgo_Y29jJGQkJDogI3ByaW50IGZhbHNlOyByZXR1cm4gLTEKX18gI2Vsc2U6IDYgMgpeZF4tOl8gI3doaWxlIG5vdCBlcXVhbAp1PyAjaWYgc3RhY2sucG9wKCkgIT0gLTE6CmN1bzogI3ByaW50IHRydWU&input=NDM)
(It has been implemented as a standard example in the interpreter.)
[Answer]
# [Fith](https://github.com/nazek42/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.
[Answer]
## 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.
* Reads from standard input.
* 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.
[Answer]
# brainfuck, ~~208~~ 202 bytes
This is the code I wrote for [my Sesos answer](https://codegolf.stackexchange.com/a/86169/34718). 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`.
```
[->+>+<<]++>[-<->]+<[>-<,]>[->+<]>[[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>-]<<<<<<+[<<<<<<]>>>>>>[-<+>]++[<[->>>+<<<]>>>[->>>+<<<<<<+>>>]>>>>][[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<<<<<<]>>>>>>>>[>]>[<+>,]+<[>-<-]>.
```
[Answer]
## [RPN](https://github.com/ConceptJunkie/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
```
[Answer]
# [Nim](http://nim-lang.org), ~~70~~ 56 bytes
```
import os,math
let x=1.paramStr.len
echo fac(x-1)^2mod x
```
Uses [Wilson's theorem](http://en.wikipedia.org/wiki/Wilson's_theorem); that is, `x` is prime if `(x - 1)!² mod x` is 1.
Takes input in unary (any character) via the first command-line argument. Outputs 1 if the input is prime, and 0 otherwise. To test:
```
$ nim c prime.nim
$ ./prime 11111111
0
$ ./prime 1111111
1
$ ./prime 1
0
```
Note that according to the [Nim `os` docs](http://nim-lang.org/docs/os.html#paramStr,int), this solution will not work on POSIX as `paramStr` isn't available for some reason.
[Answer]
# PHP, ~~70~~ 65 bytes
```
for($i=2;$i<$n=$argv[1];$i++)if(is_int($n/$i)?1:0){echo 0;break;}
```
Empty output if the number is prime, print `0` if the number is not prime.
Not very original or best answer, but this is it...
[Test online](http://sandbox.onlinephpfunctions.com/code/16aede2248614de9af496bf9721655af46e3f413)
]


[Question]
      [
This is my first challenge, so I'm keeping it fairly simple.
If you've ever typed `telnet towel.blinkenlights.nl` on your command line and pressed enter, you will have experienced the joy of asciimation. Asciimation is, quite simply, doing an animation with ascii art. Today we will be doing a very basic asciimation of a person doing jumping jacks.
There will be two ascii pictures that we will put together into one asciimation.
Number 1:
```
_o_
 0
/ \
```
Number 2:
```
\o/
_0_
<blank line>
```
Note that the second one has a blank line at the end.
So your program should do these steps:
1. Clear the console screen.
2. Print the correct ascii art image.
3. Set a flag or something so you know to do the other image next time.
4. Wait a moment (about a second).
5. Continue at 1.
# Rules
* Your program must be a (theoretically) infinite loop.
* The programming language you use must have been created before this challange was posted.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
* Standard loopholes apply.
Enjoy!

[Answer]
# CJam, ~~51~~ ~~45~~ ~~42~~ ~~38~~ 36 bytes
```
"c\o/
_0_""^[c_o_
 0
/ \^["{_o\6e4m!}g
```
The above uses caret notation; the sequence `^[` is actually the ASCII character with code point 27.
I've borrowed the escape sequence (`^[c`) from [@DomHastings' answer](https://codegolf.stackexchange.com/a/57138) ([with his permission](https://codegolf.stackexchange.com/questions/57120/asciimation-jumping-jacks/57138?noredirect=1#comment137801_57138)) to save 4 bytes.
### Verification
You can recreate the file like this:
```
base64 -d > jj.cjam <<< ImNcby8KXzBfIiIbY19vXwogMAovIFwbIntfb1w2ZTRtIX1n
```
To run the code, download the [CJam interpreter](https://sourceforge.net/p/cjam/wiki/Home/) and execute this:
```
java -jar cjam-0.6.5.jar jj.cjam
```
This will work on any terminal that supports [console\_codes](http://man7.org/linux/man-pages/man4/console_codes.4.html) or an appropriate subset.1
### How it works
```
e# Push both jumping jacks on the stack.
"c\o/
_0_"
"^[c_o_
 0
/ \^["
e# When chained together, they contain two occurrences of the string "\ec",
e# which resets the terminal. Encoding the ESC byte in the second string
e# eliminates the need two escape a backslash before the string terminator.
{         e# Do:
  _o      e#   Copy the jumping jack on top of the stack and print the copy.
  \       e#   Swap the order of the jumping jacks.
  6e4m!   e#   Calculate the factorial of 60,000 and discard the result.
          e#   This takes "about a second".
}g        e# Since the discarded factorial was non-zero, repeat the loop.
```
---
1 The jumping jacks will look better if you hide the terminal's cursor before running the program. In Konsole, e.g., you can set the cursor's color to match the background color. This has to be done via your terminal's settings, since `^[c` resets the terminal.
[Answer]
# Pyth - ~~41~~ ~~40~~ 39 bytes
```
.VZ"\x1b[H\x1b[J"@c"_o_
 0
/ \\\o/
_0_"Tb .p9
```
(I'm counting the `\x1b`'s as one byte since SO destroys special characters).
Clearly doesn't work online since its a) an infinite loop and b) uses terminal escape codes.
```
#                Infinite loop
 "..."           Print escape sequences to clear screen
 @               Modular indexing
  c     T        Chop at index ten into the constituent frames
   "..."         Frames 1 & 2 concatenated (Pyth allows literal newlines in strings)
  ~              Post assign. This is an assign that returns the old value.
   h             Increment function. Putting it after an assign makes it augmented assign.
   Z             Variable auto-initialized to zero.
 .p9             Permutations(range(9), 9). Takes about a second on my machine.
```
I was surprised to find out that augmented-assign worked with post-assign. Pyth is awesome.
[Answer]
# QBasic, ~~58~~ 54 bytes
Tested on [QB64](http://www.qb64.net) and at [Archive.org](https://archive.org/details/msdos_qbasic_megapack).
```
CLS
?"_o_
?0
?"/ \
SLEEP 1
CLS
?"\o/
?"_0_
SLEEP 1
RUN
```
The right language for the problem can be surprisingly competitive, even if it is usually verbose. The `?` shortcut for `PRINT` helps too, of course. `CLS` is **cl**ear **s**creen; `RUN` without arguments restarts the program, which is the shortest way to get an infinite loop.
The only other trick here is printing `0` for the midsection of the first picture. QBasic puts a space in front of (and after) nonnegative numeric values when it prints them, resulting in  `0` . Saved 2 characters over `" 0`.
I may also point out that the delay in this code is *literally a second*, and is not machine-dependent. ;^P
[Answer]
# Perl *(\*nix)*, 54 bytes
```
sleep print"\x1bc",$-++%2?'\o/
_0_
':'_o_
 0
/ \
'while 1
```
(`\x1b` is counted as 1 byte but escaped for easier testing.) The above has been tested with Bash and shortened by another byte thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)!
# Perl *(Windows)*, 56 bytes
```
sleep print"\x1b[2J",$-++%2?'\o/
_0_
':'_o_
 0
/ \
'while 1
```
Thanks to [@Jarmex](https://codegolf.stackexchange.com/u/26977) for his testing and advice!
[Answer]
# Javascript (ES6), ~~109~~ ~~93~~ ~~79~~ 70 bytes + HTML, ~~12~~ 10 bytes = ~~120~~ ~~106~~ ~~91~~ 80 bytes
Fairly straightforward. Uses template strings to store the images, and toggles a boolean value to determine which to use.
**NOTE:** This solution may not be valid, as it does not actually use a console. However, I don't believe it's possible to clear a browser console using JS, at least not while using Firefox.
```
a=!1,setInterval(_=>O.innerHTML=(a=!a)?`_o_
 0
/ \\`:`\\o/
_0_`,1e3)
```
```
<pre id=O>
```
[Answer]
# Bash, ~~86~~ 84 bytes
```
while sleep 1;do printf "\e[2J_o_\n 0\n/ \\";sleep 1;printf "\r\e[2J\o/\n_0_\n";done
```
[Answer]
# [Dash](https://wiki.debian.org/Shell), 67 bytes
Also `bash`, `ksh`, `zsh`, `ash`, `yash` and probably many more besides. While it apparently works in these other shells, their own features and idiosyncrasies may allow for further golfing. I'll leave that as an exercise for the reader.
Notably **not** `fish` or `tcsh`.
```
f(){ clear;echo "$1";sleep 1;f "$2" "$1";};f '_o_
 0
/ \' '\o/
_0_'
```
[Try it online!](https://tio.run/##S0kszvj/P01Ds1ohOSc1scg6NTkjX0FJxVDJujgnNbVAwdA6Dcg1UoKI1QJ56vH58VwKBlz6CjHqCuox@fpc8Qbx6v//AwA "Dash – Try It Online") (with STDERR issue -- see **Caveats**)
[Try it online!](https://tio.run/##S0kszvifWlGQX1SiEOIa5GtbVmJoYPA/TUOzWiE5JzWxyDo1OSNfQUnFUMm6OCc1tUDB0DoNyDVSgojVAnnq8fnxXAoGXPoKMeoK6jH5@lzxBvHq//8DAA "Dash – Try It Online") (with visible escape codes issue -- see **Caveats**)
# How it works
Hopefully fairly self explanatory, even so:
Set up a function `f` which
* Clears screen
* Prints contents of `$1`
* Sleeps 1 second
* Calls `f` passing `$1` and `$2` in reverse order. This means the next iteration will display the "other" glyph before flipping them again... and so on.
Outside of the function is the initial call to `f` with literal depictions of the two character glyphs as two arguments.
# Caveats
TIO's terminal implementation doesn't handle the `clear` well -- produces an error to STDOUT. If you add `export TERM=vt100` as a header the error stops and it displays the literal escape string. This is a feature/limitation of TIO, not an issue with my submission. I've included links to both for reference.
Code should work as intended in a "proper" terminal.
The recursion will eventually cause it to fail. Tried a soak test with `sleep 0` in a Docker container and it threw a Segmentation Fault within a minute. Adding a trivial counter, which may or may not have quantum implications, it managed ~15000 iterations in my environment. So like 4 hours with the `sleep` -- and who's going to watch it **that** long? :-)
But I'd still argue that this complies with "theoretically" infinite, because it could go forever if it had "theoretically" infinite resources. That's my story and I'm sticking to it.
[Answer]
# Python 2, 99 bytes
Runs on Windows
```
import os,time
g=0
while 1:os.system("cls");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g
```
For UNIX machines, add two bytes:
```
import os,time
g=0
while 1:os.system("clear");print["\\o/\n_0_","_o_\n 0 \n/ \\"][g];time.sleep(1);g=~g
```
[Answer]
# awk - 95 92 86 84 83
```
END{
    for(;++j;)
        system("clear;printf '"(j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")"';sleep 1")
}
```
Nice workout :D Just wondered if this was doable. No prices to gain though... ;)
If someone wants to test this: after you run the program you have to press Ctrl+D (end of input) to actually start the END block. To terminate it I have to use Ctrl+Z.
I also have this, which is only 74 bytes, but it starts with pausing a second which isn't the wanted behaviour I think
```
END{
    for(;1;print++j%2?"_o_\n 0\n/ \\":"\\o/\n_0_")
        system("sleep 1;clear")
}
```
[Answer]
# Batch - 82 bytes
Edit: Muted the timeout command and removed the extra newline.
```
cls&echo _o_&echo  0&echo / \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0
```
I've seen 2 other similar batch answers so I didn't really want to post this, but this is my first ever golf.
[Answer]
# BBC BASIC, 75 bytes
Note that tokenisation pulls it down to 75 bytes. The whitespace is added in by the IDE.
```
      g=0
   10 IFg=0THENPRINT"\o/":PRINT"_0_"ELSEPRINT"_o_":PRINT" 0 ":PRINT"/ \"
      g=1-g:WAIT 100CLS:GOTO10
```
[![Properties showing program size](https://i.stack.imgur.com/UIoh2.jpg)](https://i.stack.imgur.com/UIoh2.jpg)
[Answer]
# JavaScript ES6, ~~100~~ 95 bytes
```
(f=_=>{console.log(_?`_o_
 0
/ \\`:`\\o/
_0_`)
(b=setTimeout)(q=>(clear(),b(b=>f(!_))),1e3)})()
```
Logs to the console. Tested on Safari Nightly
[Answer]
# Batch, ~~151~~ ~~130~~ 118 bytes
```
cls
@echo _o_
@echo  0
@echo / \
@PING -n 2 127.0.0.1>NUL
cls
@echo \o/
@echo _0_
@PING -n 2 127.0.0.1>NUL
%0
```
[Answer]
# CBM 64 BASIC V2, ~~121~~ ~~119~~ ~~112~~ 117 bytes
```
2?CHR$(147)+"\o/":?" 0":?"/ \"
3GOSUB7
4?CHR$(147)+"_o_":?"_0_"
5GOSUB7
6RUN
7A=TI
8IFTI-A<60THENGOTO8
9RETURN
```
[Answer]
# Julia, 70 bytes
(on **Windows**, by replacing `clear` with `cls`, thanks to undergroundmonorail)
```
n(i=1)=(sleep(1);run(`cls`);print(i>0?"_o_
 0
/ \\":"\\o/
_0_");n(-i))
```
### On Linux, 72 bytes
```
n(i=1)=(sleep(1);run(`clear`);print(i>0?"_o_
 0
/ \\":"\\o/
_0_");n(-i))
```
This uses actual newlines rather than `\n` to save a byte; otherwise, the `i` is either 1 or -1 as the "flag", and it uses recursion to achieve the infinite loop. Call it as either `n(1)` or just `n()`.
Also, `run(`clear`)`/`run(`cls`)` uses a shell command to clear the window, because Julia doesn't have a built-in window-clear command.
[Answer]
# Windows Batch, 83 ~~89~~
**Edit** removed the empty line after the clarification by OP
```
@cls&echo _o_&echo  0&echo./ \&timeout>nul 1&cls&echo \o/&echo _0_&timeout>nul 1&%0
```
~~If you get rid of the empty line in the jumping man (that cannot be seen anyway), the score is 83~~
Note: `timeout` is not present in Windows XP. It works in Vista or newer versions. Moreover `timeout` is not precise to the second, so it's a perfect choice to implement step 4 (Wait a moment (*about a second*))
[Answer]
# Javascript (ES6), 82 bytes
A modification of my [previous answer](https://codegolf.stackexchange.com/a/57123/42545) that uses the console. Works partially in Firefox, but only clears the console in Chrome, AFAIK.
```
a=!0,c=console,setInterval(_=>c.log(c.clear(a=!a)|a?`_o_
 0
/ \\`:`\\o/
_0_`),1e3)
```
As always, suggestions welcome!
[Answer]
# JavaScript, ~~92~~ ~~91~~ 89 bytes
```
x=0;setInterval(function(){console.log("\033c"+["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3)
```
* No ES6 features (but would be significantly shorter with them)
* Works with Node.js on Linux (don't know about other environments)
* Partially works in Chrome's console (`c` is shown instead of clearing the console, breaking the output)
Removing `"\033c"+` from the above code, the following works in the browser, but doesn't clear the console.
```
x=0;setInterval(function(){console.log(["_o_\n 0\n/ \\","\\o/\n_0_"][x^=1])},1e3)
```
[Answer]
# CBM BASIC v2.0 (68 characters)
```
0?"S_o_q||0q||N M":goS1:?"SMoN":?"_0_":goS1:gO
1wA161,255,pE(161):reT
```
The above requires some explanation, since Stack Exchange markup doesn't properly represent PETSCII characters:
* The program is shown here for convenience in lowercase, but can and should be entered and run in uppercase mode on a Commodore 64.
* The first and third "S" characters are actually in reverse video, and produced by pressing the `CLR` key (`SHIFT`+`HOME`).
* The "q" characters are actually in reverse video, and produced by pressing the down cursor (`CRSR ⇓`).
* The "|" characters are actually in reverse video, and produced by pressing the left cursor (`SHIFT`+`CRSR ⇒`).
[Answer]
# TI-Basic, ~~58~~ 56 bytes
```
While 1
ClrHome
If not(Ans
Disp "_o_"," 0","/ \
If Ans
Disp "\o/","_0_"
not(Ans
If dim(rand(70
End
```
-2 bytes for assuming that the code is run on a fresh interpreter.
[Answer]
## Ruby, 79 bytes
```
k=!0;loop{puts((k)?"\e[H\e[2J_o_\n 0\n/ \\":"\e[H\e[2J\\o/\n_0_");k=!k;sleep 1}
```
Requires escape codes.
[Answer]
# Forth, 86 bytes
Requires GNU Forth for the escaped strings. To run in a non-GNU Forth, just change `S\"` to `S"`, and the escaped characters won't print correctly.
```
: P PAGE TYPE CR 999 MS ;
: R BEGIN S\" \\o/\n_0_" P S\" _o_\n 0 \n/ \\" P 0 UNTIL ; R
```
[Answer]
# [beeswax](http://rosettacode.org/wiki/Category:Beeswax), ~~119~~ 113 bytes
```
ph0`J2[`}ghq'-<gh0N}`0`}gN`/o\`Ngh0`J`<
>g}`o`}N` `0>'d`0 `N`/ \`0hg>-'phg}`[2`b
dF1f+5~Zzf(.FP9f..F3_#     d   <
```
Explanation of the important parts of the program:
```
left to right  right to left
3FBf   or       fBF3          27       ASCII code for (esc)
3             [x,x,3]•        set lstack 1st to 3
 F            [3,3,3]•        set lstack to 1st
  B           [3,3,27]•       1st=1st^2nd
   f                          push lstack 1st on gstack
——————
9PF.(f   or    f(.FP9         102400   counter to roughly match a wait time
                                       of 1 s on my i5 2410M Laptop
9             [x,x,9]•        set lstack 1st to 9
 P            [x,x,10]•       increment 1st
  F           [10,10,10]•     set lstack to 1st
   .          [10,10,100]•    1st=1st*2nd
    (         [10,10,102400]• 1st=1st<<2nd (100<<10=102400, arithmetic shift left)
     f                        push lstack 1st on gstack
——————
zZ~5+f   or    f+5~Zz         95       ASCII for '_'
z             [0,0,0]•        initialize lstack to zero
 Z            [0,0,90]•       get value from relative coordinate (0,0),
                              which is the location of `Z` itself, ASCII(Z)=90
  ~           [0,90,0]•       flip 1st and 2nd lstack values
   5          [0,90,5]•       set lstack 1st to 5
    +         [0,90,95]•      1st = 1st+2nd
     f                        push lstack 1st on gstack
```
The `f`’s push the values on the gstack (global stack) for later use. These values are accessed by the `0gh` (or the mirrored `hg0`) and `hg` (`gh`) instructions. `h` rotates the gstack upwards, `g` reads the top value of gstack and pushes it onto the lstack (local stack) of the bee (instruction pointer).
```
}`o`}N` 0 `N`/ \`                      sequence to print the standing man
N`\o/`Ng}`0`}N                         sequence to print the jumping man
}`[2J`                        equivalent to the ANSI escape sequence (esc)[2J
                              to clear the screen
>-'p  or >-'q  or >  p        loop for counting down (wait 1 s)
d  <      b  <    d'-<
```
In-depth explanation follows later, if needed. Maybe with animation.
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), noncompeting 24 bytes
Noncompeting because *Noodel* was born after the challenge was created:)
```
”ṛ|ọBCḊCBCḣ“\o/¶_0_ḷėçḍs
```
[Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%E2%80%9D%E1%B9%9B%7C%E1%BB%8DBC%E1%B8%8ACBC%E1%B8%A3%E2%80%9C%5Co%2F%C2%B6_0_%E1%B8%B7%C4%97%C3%A7%E1%B8%8Ds&input=&run=true)
### How it works
```
”ṛ|ọBCḊCBCḣ              # Creates a string that gets decompressed into "_o_¶¤0¤¶/¤\" and places it into the pipe.
           “\o/¶_0_      # Creates a string and places it into the pipe.
                   ḷ     # Unconditionally loop the code up to a new line or end of program.
                    ė    # Takes what is in the front of the pipe and puts it into the back.
                     ç   # Clears the screen and prints.
                      ḍs # Delays for one second.
```
---
There currently is not a version of *Noodel* that supports the syntax used in this challenge. Here is a version that does:
**24 bytes**
```
\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs
```
```
<div id="noodel" code="\o/¶_0_ _o_¶¤0¤¶/¤\ḷçėḍs" input="" cols="5" rows="5"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# [Nim](http://nim-lang.org/), 107 bytes
```
import os,terminal
var f=0
while 0<1:eraseScreen();sleep 999;echo ["_o_\n 0 \n/ \\","\\o/\n_0_\n"][f];f=1-f
```
Don't [Try it online!](https://tio.run/##DcjBCsMgDADQe78ieNqgo/boXL9ix6aIlEgFTUos2@e7vePjXHvP9RS9QNp4kdbMsQyfqJAWO3yPXAjsa36SxkbvXYn4dvetEJ3gnPO0HwKrCRKQwQLyBIhmNIgyIQf7b7OtafNpmR@p9x8 "Nim – Try It Online")
]


[Question]
      [
You must evaluate a string written in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation) and output the result.
The program must accept an input and return the output. For programming languages that do not have functions to receive input/output, you can assume functions like readLine/print.
You are not allowed to use any kind of "eval" in the program.
Numbers and operators are separated by one **or more** spaces.
You must support at least the +, -, \* and / operators.
You need to add support to negative numbers (for example, `-4` is not the same thing as `0 4 -`) and floating point numbers.
**You can assume the input is valid and follows the rules above**

## Test Cases
Input:
```
-4 5 +
```
Output:
```
1
```
---
Input:
```
5 2 /
```
Output:
```
2.5
```
---
Input:
```
5 2.5 /
```
Output:
```
2
```
---
Input:
```
5 1 2 + 4 * 3 - +
```
Output:
```
14
```
---
Input:
```
4 2 5 * + 1 3 2 * + /
```
Output:
```
2
```

[Answer]
## Ruby - 95 77 characters
```
a=[]
gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))}
p a[0]
```
Takes input on stdin.
### Testing code
```
[
  "-4 5 +",
  "5 2 /",
  "5 2.5 /",
  "5 1 2 + 4 * 3 - +",
  "4 2 5 * + 1 3 2 * + /",
  "12 8 3 * 6 / - 2 + -20.5 "
].each do |test|
  puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}"
end
```
gives
```
[-4 5 +] gives 1.0
[5 2 /] gives 2.5
[5 2.5 /] gives 2.0
[5 1 2 + 4 * 3 - +] gives 14.0
[4 2 5 * + 1 3 2 * + /] gives 2.0
[12 8 3 * 6 / - 2 + -20.5 ] gives 10.0
```
Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems.
[Answer]
## Python - 124 chars
```
s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s[:2]=[[a+b],[a-b],[a*b],[a/b],[i,b,a]]["+-*/".find(i)]
print s[0]
```
**Python - 133 chars**
```
s=[1,1]
for i in raw_input().split():b,a=map(float,s[:2]);s={'+':[a+b],'-':[a-b],'*':[a*b],'/':[a/b]}.get(i,[i,b,a])+s[2:]
print s[0]
```
[Answer]
## Scheme, 162 chars
(Line breaks added for clarity—all are optional.)
```
(let l((s'()))(let((t(read)))(cond((number? t)(l`(,t,@s)))((assq t
`((+,+)(-,-)(*,*)(/,/)))=>(lambda(a)(l`(,((cadr a)(cadr s)(car s))
,@(cddr s)))))(else(car s)))))
```
Fully-formatted (ungolfed) version:
```
(let loop ((stack '()))
  (let ((token (read)))
    (cond ((number? token) (loop `(,token ,@stack)))
          ((assq token `((+ ,+) (- ,-) (* ,*) (/ ,/)))
           => (lambda (ass) (loop `(,((cadr ass) (cadr stack) (car stack))
                                    ,@(cddr stack)))))
          (else (car stack)))))
```
---
**Selected commentary**
``(,foo ,@bar)` is the same as `(cons foo bar)` (i.e., it (effectively†) returns a new list with `foo` prepended to `bar`), except it's one character shorter if you compress all the spaces out.
Thus, you can read the iteration clauses as `(loop (cons token stack))` and `(loop (cons ((cadr ass) (cadr stack) (car stack)) (cddr stack)))` if that's easier on your eyes.
``((+ ,+) (- ,-) (* ,*) (/ ,/))` creates an association list with the *symbol* `+` paired with the *procedure* `+`, and likewise with the other operators. Thus it's a simple symbol lookup table (bare words are `(read)` in as symbols, which is why no further processing on `token` is necessary). Association lists have O(n) lookup, and thus are only suitable for short lists, as is the case here. :-P
† This is not technically accurate, but, for non-Lisp programmers, it gets a right-enough idea across.
[Answer]
# MATLAB – 158, 147
```
C=strsplit(input('','s'));D=str2double(C);q=[];for i=1:numel(D),if isnan(D(i)),f=str2func(C{i});q=[f(q(2),q(1)) q(3:end)];else q=[D(i) q];end,end,q
```
(input is read from user input, output printed out).
---
Below is the code prettified and commented, it pretty much implements the [postfix algorithm](https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm) described (with the assumption that expressions are valid):
```
C = strsplit(input('','s'));         % prompt user for input and split string by spaces
D = str2double(C);                   % convert to numbers, non-numeric are set to NaN
q = [];                              % initialize stack (array)
for i=1:numel(D)                     % for each value
    if isnan(D(i))                   % if it is an operator
        f = str2func(C{i});          % convert op to a function
        q = [f(q(2),q(1)) q(3:end)]; % pop top two values, apply op and push result
    else
        q = [D(i) q];                % else push value on stack
    end
end
q                                    % show result
```
---
## Bonus:
In the code above, we assume operators are always binary (`+`, `-`, `*`, `/`). We can generalize it by using `nargin(f)` to determine the number of arguments the operand/function requires, and pop the right amount of values from the stack accordingly, as in:
```
f = str2func(C{i});
n = nargin(f);
args = num2cell(q(n:-1:1));
q = [f(args{:}) q(n+1:end)];
```
That way we can evaluate expressions like:
```
str = '6 5 1 2 mean_of_three 1 + 4 * +'
```
where `mean_of_three` is a user-defined function with three inputs:
```
function d = mean_of_three(a,b,c)
    d = (a+b+c)/3;
end
```
[Answer]
## c -- 424 necessary character
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define O(X) g=o();g=o() X g;u(g);break;
char*p=NULL,*b;size_t a,n=0;float g,s[99];float o(){return s[--n];};
void u(float v){s[n++]=v;};int main(){getdelim(&p,&a,EOF,stdin);for(;;){
b=strsep(&p," \n\t");if(3>p-b){if(*b>='0'&&*b<='9')goto n;switch(*b){case 0:
case EOF:printf("%f\n",o());return 0;case'+':O(+)case'-':O(-)case'*':O(*)
case'/':O(/)}}else n:u(atof(b));}}
```
Assumes that you have a new enough libc to include `getdelim` in stdio.h. The approach is straight ahead, the whole input is read into a buffer, then we tokenize with `strsep` and use length and initial character to determine the class of each. There is no protection against bad input. Feed it "+ - \* / + - ...", and it will happily pop stuff off the memory "below" the stack until it seg faults. All non-operators are interpreted as floats by `atof` which means zero value if they don't look like numbers.
**Readable and commented:**
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *p=NULL,*b;
size_t a,n=0;
float g,s[99];
float o(){        /* pOp */
  //printf("\tpoping '%f'\n",s[n-1]);
  return s[--n];
};
void u(float v){  /* pUsh */
  //printf("\tpushing '%f'\n",v);
  s[n++]=v;
};
int main(){
  getdelim(&p,&a,EOF,stdin); /* get all the input */
  for(;;){
    b=strsep(&p," \n\t"); /* now *b though *(p-1) is a token and p
                 points at the rest of the input */
    if(3>p-b){
      if (*b>='0'&&*b<='9') goto n;
      //printf("Got 1 char token '%c'\n",*b);
      switch (*b) {
      case 0:
      case EOF: printf("%f\n",o()); return 0;
      case '+': g=o(); g=o()+g; u(g); break;
      case '-': g=o(); g=o()-g; u(g); break;
      case '*': g=o(); g=o()*g; u(g); break;
      case '/': g=o(); g=o()/g; u(g); break;
    /* all other cases viciously ignored */
      }
    } else { n:
      //printf("Got token '%s' (%f)\n",b,atof(b));
      u(atof(b));
    }
  }
}
```
**Validation:**
```
 $ gcc -c99 rpn_golf.c
 $ wc rpn_golf.c
  9  34 433 rpn_golf.c
 $ echo -4 5 + | ./a.out
1.000000
 $ echo 5 2 / | ./a.out
2.500000
 $ echo 5 2.5 / | ./a.out
2.000000
```
Heh! Gotta quote anything with `*` in it...
```
 $ echo "5 1 2 + 4 * 3 - +" | ./a.out
14.000000
 $ echo "4 2 5 * + 1 3 2 * + /" | ./a.out
2.000000
```
and my own test case
```
 $ echo "12 8 3 * 6 / - 2 + -20.5 " | ./a.out
-20.500000
```
[Answer]
## Haskell (155)
```
f#(a:b:c)=b`f`a:c
(s:_)![]=print s
s!("+":v)=(+)#s!v
s!("-":v)=(-)#s!v
s!("*":v)=(*)#s!v
s!("/":v)=(/)#s!v
s!(n:v)=(read n:s)!v
main=getLine>>=([]!).words
```
[Answer]
## Perl (134)
```
@a=split/\s/,<>;/\d/?push@s,$_:($x=pop@s,$y=pop@s,push@s,('+'eq$_?$x+$y:'-'eq$_?$y-$x:'*'eq$_?$x*$y:'/'eq$_?$y/$x:0))for@a;print pop@s
```
Next time, I'm going to use the recursive regexp thing.
Ungolfed:
```
@a = split /\s/, <>;
for (@a) {
    /\d/
  ? (push @s, $_)
  : ( $x = pop @s,
      $y = pop @s,
      push @s , ( '+' eq $_ ? $x + $y
                : '-' eq $_ ? $y - $x
                : '*' eq $_ ? $x * $y
                : '/' eq $_ ? $y / $x
                : 0 )
      )
}
print(pop @s);
```
I though F# is my only dream programming language...
[Answer]
### Windows PowerShell, 152 ~~181~~ ~~192~~
In readable form, because by now it's only two lines with no chance of breaking them up:
```
$s=@()
switch -r(-split$input){
  '\+'        {$s[1]+=$s[0]}
  '-'         {$s[1]-=$s[0]}
  '\*'        {$s[1]*=$s[0]}
  '/'         {$s[1]/=$s[0]}
  '-?[\d.]+'  {$s=0,+$_+$s}
  '.'         {$s=$s[1..($s.count)]}}
$s
```
**2010-01-30 11:07** (192) – First attempt.
**2010-01-30 11:09** (170) – Turning the function into a scriptblock solves the scope issues. Just makes each invocation two bytes longer.
**2010-01-30 11:19** (188) – Didn't solve the scope issue, the test case just masked it. Removed the index from the final output and removed a superfluous line break, though. And changed double to `float`.
**2010-01-30 11:19** (181) – Can't even remember my own advice. Casting to a numeric type can be done in a single char.
**2010-01-30 11:39** (152) – Greatly reduced by using regex matching in the `switch`. Completely solves the previous scope issues with accessing the stack to pop it.
[Answer]
**[Racket](http://racket-lang.org) 131:**
```
(let l((s 0))(define t(read))(cond[(real? t)
(l`(,t,@s))][(memq t'(+ - * /))(l`(,((eval t)(cadr s)
(car s)),@(cddr s)))][0(car s)]))
```
Line breaks optional.
Based on Chris Jester-Young's solution for Scheme.
[Answer]
## Python, 166 characters
```
import os,operator as o
S=[]
for i in os.read(0,99).split():
 try:S=[float(i)]+S
 except:S=[{'+':o.add,'-':o.sub,'/':o.div,'*':o.mul}[i](S[1],S[0])]+S[2:]
print S[0]
```
[Answer]
# Python 3, 119 bytes
```
s=[]
for x in input().split():
 try:s+=float(x),
 except:o='-*+'.find(x);*s,a,b=s;s+=(a+b*~-o,a*b**o)[o%2],
print(s[0])
```
Input: `5 1 1 - -7 0 * + - 2 /`
Output: `2.5`
(You can find a 128-character Python 2 version in the edit history.)
[Answer]
# JavaScript (157)
This code assumes there are these two functions: readLine and print
```
a=readLine().split(/ +/g);s=[];for(i in a){v=a[i];if(isNaN(+v)){f=s.pop();p=s.pop();s.push([p+f,p-f,p*f,p/f]['+-*/'.indexOf(v)])}else{s.push(+v)}}print(s[0])
```
[Answer]
## Perl, 128
This isn't really competitive next to the other Perl answer, but explores a different (suboptimal) path.
```
perl -plE '@_=split" ";$_=$_[$i],/\d||
do{($a,$b)=splice@_,$i-=2,2;$_[$i--]=
"+"eq$_?$a+$b:"-"eq$_?$a-$b:"*"eq$_?
$a*$b:$a/$b;}while++$i<@_'
```
Characters counted as diff to a simple `perl -e ''` invocation.
[Answer]
# flex - 157
```
%{
float b[100],*s=b;
#define O(o) s--;*(s-1)=*(s-1)o*s;
%}
%%
-?[0-9.]+ *s++=strtof(yytext,0);
\+ O(+)
- O(-)
\* O(*)
\/ O(/)
\n printf("%g\n",*--s);
.
%%
```
If you aren't familiar, compile with `flex rpn.l && gcc -lfl lex.yy.c`
[Answer]
Python, 161 characters:
```
from operator import*;s=[];i=raw_input().split(' ')
q="*+-/";o=[mul,add,0,sub,0,div]
for c in i:
 if c in q:s=[o[ord(c)-42](*s[1::-1])]+s
 else:s=[float(c)]+s
print(s[0])
```
[Answer]
## PHP, ~~439~~ ~~265~~ ~~263~~ ~~262~~ ~~244~~ 240 characters
```
<? $c=fgets(STDIN);$a=array_values(array_filter(explode(" ",$c)));$s[]=0;foreach($a as$b){if(floatval($b)){$s[]=$b;continue;}$d=array_pop($s);$e=array_pop($s);$s[]=$b=="+"?$e+$d:($b=="-"?$e-$d:($b=="*"?$e*$d:($b=="/"?$e/$d:"")));}echo$s[1];
```
This code should work with stdin, though it is not tested with stdin.

It has been tested on all of the cases, the output (and code) for the last one is here:

<http://codepad.viper-7.com/fGbnv6>
**Ungolfed, ~~314~~ ~~330~~ 326 characters**
```
<?php
$c = fgets(STDIN);
$a = array_values(array_filter(explode(" ", $c)));
$s[] = 0;
foreach($a as $b){
    if(floatval($b)){
        $s[] = $b;
        continue;
    }
    $d = array_pop($s);
    $e = array_pop($s);
    $s[] = $b == "+" ? $e + $d : ($b == "-" ? $e - $d : ($b == "*" ? $e * $d : ($b == "/" ? $e / $d :"")));
}
echo $s[1];
```
[Answer]
## Python, 130 characters
Would be 124 characters if we dropped `b and` (which some of the Python answers are missing). And it incorporates 42!
```
s=[]
for x in raw_input().split():
 try:s=[float(x)]+s
 except:b,a=s[:2];s[:2]=[[a*b,a+b,0,a-b,0,b and a/b][ord(x)-42]]
print s[0]
```
[Answer]
# Python 3, ~~126~~ 132 chars
```
s=[2,2]
for c in input().split():
    a,b=s[:2]
    try:s[:2]=[[a+b,b-a,a*b,a and b/a]["+-*/".index(c)]]
    except:s=[float(c)]+s
print(s[0])
```
There have been better solutions already, but now that I had written it (without having read the prior submissions, of course - even though I have to admit that my code looks as if I had copypasted them together), I wanted to share it, too.
[Answer]
# C, 232 229 bytes
Fun with recursion.
```
#include <stdlib.h>
#define b *p>47|*(p+1)>47
char*p;float a(float m){float n=strtof(p,&p);b?n=a(n):0;for(;*++p==32;);m=*p%43?*p%45?*p%42?m/n:m*n:m-n:m+n;return*++p&&b?a(m):m;}main(c,v)char**v;{printf("%f\n",a(strtof(v[1],&p)));}
```
## Ungolfed:
```
#include <stdlib.h>
/* Detect if next char in buffer is a number */
#define b *p > 47 | *(p+1) > 47
char*p; /* the buffer */
float a(float m)
{
    float n = strtof(p, &p); /* parse the next number */
    /* if the next thing is another number, recursively evaluate */
    b ? n = a(n) : 0;
    for(;*++p==32;); /* skip spaces */
    /* Perform the arithmetic operation */
    m = *p%'+' ? *p%'-' ? *p%'*' ? m/n : m*n : m-n : m+n;
    /* If there's more stuff, recursively parse that, otherwise return the current computed value */
    return *++p && b ? a(m) : m;
}
int main(int c, char **v)
{
    printf("%f\n", a(strtof(v[1], &p)));
}
```
## Test Cases:
```
$ ./a.out "-4 5 +"
1.000000
$ ./a.out "5 2 /"
2.500000
$ ./a.out "5 2.5 /"
2.000000
$ ./a.out "5 1 2 + 4 * 3 - +"
14.000000
$ ./a.out "4 2 5 * + 1 3 2 * + /"
2.000000
```
[Answer]
# JavaScript ES7, 119 bytes
I'm getting a bug with array comprehensions so I've used `.map`
```
(s,t=[])=>(s.split` `.map(i=>+i?t.unshift(+i):t.unshift((r=t.pop(),o=t.pop(),[r+o,r-o,r*o,r/o]['+-*/'.indexOf(i)]))),t)
```
[Try it online at ESFiddle](http://server.vihan.ml/p/esfiddle/?code=f%3D(s%2Ct%3D%5B%5D)%3D%3E(s.split%60%20%60.map(i%3D%3E%2Bi%3Ft.unshift(%2Bi)%3At.unshift((r%3Dt.pop()%2Co%3Dt.pop()%2C%5Br%2Bo%2Cr-o%2Cr*o%2Cr%2Fo%5D%5B'%2B-*%2F'.indexOf(i)%5D)))%2Ct)%3B%0A%0Af(%2211%203%20%2B%22))
[Answer]
# C 153
Sometimes a program can be made a bit shorter with more golfing and sometimes you just take completely the wrong route and the much better version is found by someone else.
**Thanks to @ceilingcat for finding a much better (and shorter) version**
```
double atof(),s[99],*p=s;y,z;main(c,v)char**v;{for(;--c;*p=z?z-2?~z?z-4?p+=2,atof(*v):*p/y:*p*y:*p-y:*p+y)z=1[*++v]?9:**v-43,y=*p--;printf("%f\n",s[1]);}
```
[Try it online!](https://tio.run/##HY7RCoIwGIVfJYRg@7chml3oGHsQ88JWK6F0qA1m1Kv/bd1858A5HI4RN2MQL9Pr/Lju@nWyhPKlreuOg1OLDHyTz34YieGemns/A3j5ttNMpBBGxs6mN1Hqb5JKO6ZK/l8BTxtweYiABJHAAt1U0QJjvtN1E7dEdeBBxVhINw/jakm2t6cxix@KjsoPIlZY4hEBGRZ4iD65/Ac "C (gcc) – Try It Online")
My original version:
```
#include <stdlib.h>
#define O(x):--d;s[d]=s[d]x s[d+1];break;
float s[99];main(c,v)char**v;{for(int i=1,d=0;i<c;i++)switch(!v[i][1]?*v[i]:' '){case'+'O(+)case'-'O(-)case'*'O(*)case'/'O(/)default:s[++d]=atof(v[i]);}printf("%f\n",s[1]);}
```
If you are compiling it with mingw32 you need to turn off globbing (see <https://www.cygwin.com/ml/cygwin/1999-11/msg00052.html>) by compiling like this:
```
gcc -std=c99 x.c C:\Applications\mingw32\i686-w64-mingw32\lib\CRT_noglob.o
```
If you don't \* is automatically expanded by the mingw32 CRT into filenames.
[Answer]
## PHP - 259 characters
```
$n=explode(" ",$_POST["i"]);$s=array();for($i=0;$i<count($n);$s=$d-->0?array_merge($s,!$p?array($b,$a,$c):array($p)):$s){if($c=$n[$i++]){$d=1;$a=array_pop($s);$b=array_pop($s);$p=$c=="+"?$b+$a:($c=="-"?$b-$a:($c=="*"?$b*$a:($c=="/"?$b/$a:false)));}}echo$s[2];
```
Assuming input in POST variable *i*.
[Answer]
## C# - 392 characters
```
namespace System.Collections.Generic{class P{static void Main(){var i=Console.ReadLine().Split(' ');var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}
```
However, if arguments can be used instead of standard input, we can bring it down to
## C# - 366 characters
```
namespace System.Collections.Generic{class P{static void Main(string[] i){var k=new Stack<float>();float o;foreach(var s in i)switch (s){case "+":k.Push(k.Pop()+k.Pop());break;case "-":o=k.Pop();k.Push(k.Pop()-o);break;case "*":k.Push(k.Pop()*k.Pop());break;case "/":o=k.Pop();k.Push(k.Pop()/o);break;default:k.Push(float.Parse(s));break;}Console.Write(k.Pop());}}}
```
[Answer]
### Scala 412 376 349 335 312:
```
object P extends App{
def p(t:List[String],u:List[Double]):Double={
def a=u drop 2
t match{
case Nil=>u.head
case x::y=>x match{
case"+"=>p(y,u(1)+u(0)::a)
case"-"=>p(y,u(1)-u(0)::a)
case"*"=>p(y,u(1)*u(0)::a)
case"/"=>p(y,u(1)/u(0)::a)
case d=>p(y,d.toDouble::u)}}}
println(p((readLine()split " ").toList,Nil))}
```
[Answer]
# Python - 206
```
import sys;i=sys.argv[1].split();s=[];a=s.append;b=s.pop
for t in i:
 if t=="+":a(b()+b())
 elif t=="-":m=b();a(b()-m)
 elif t=="*":a(b()*b())
 elif t=="/":m=b();a(b()/m)
 else:a(float(t))
print(b())
```
Ungolfed version:
```
# RPN
import sys
input = sys.argv[1].split()
stack = []
# Eval postfix notation
for tkn in input:
    if tkn == "+":
        stack.append(stack.pop() + stack.pop())
    elif tkn == "-":
        tmp = stack.pop()
        stack.append(stack.pop() - tmp)
    elif tkn == "*":
        stack.append(stack.pop() * stack.pop())
    elif tkn == "/":
        tmp = stack.pop()
        stack.append(stack.pop()/tmp)
    else:
        stack.append(float(tkn))
print(stack.pop())
```
Input from command-line argument; output on standard output.
[Answer]
# ECMAScript 6 (131)
Just typed together in a few seconds, so it can probably be golfed further or maybe even approached better. I might revisit it tomorrow:
```
f=s=>(p=[],s.split(/\s+/).forEach(t=>+t==t?p.push(t):(b=+p.pop(),a=+p.pop(),p.push(t=='+'?a+b:t=='-'?a-b:t=='*'?a*b:a/b))),p.pop())
```
[Answer]
## C# - 323 284 241
```
class P{static void Main(string[] i){int x=0;var a=new float[i.Length];foreach(var s in i){var o="+-*/".IndexOf(s);if(o>-1){float y=a[--x],z=a[--x];a[x++]=o>3?z/y:o>2?z*y:o>1?z-y:y+z;}else a[x++]=float.Parse(s);}System.Console.Write(a[0]);}}
```
Edit: Replacing the Stack with an Array is way shorter
Edit2: Replaced the ifs with a ternary expression
[Answer]
# Python 2
I've tried out some different approaches to the ones published so far. None of these is quite as short as the best Python solutions, but they might still be interesting to some of you.
## Using recursion, 146
```
def f(s):
 try:x=s.pop();r=float(x)
 except:b,s=f(s);a,s=f(s);r=[a+b,a-b,a*b,b and a/b]['+-*'.find(x)]
 return r,s
print f(raw_input().split())[0]
```
## Using list manipulation, 149
```
s=raw_input().split()
i=0
while s[1:]:
 o='+-*/'.find(s[i])
 if~o:i-=2;a,b=map(float,s[i:i+2]);s[i:i+3]=[[a+b,a-b,a*b,b and a/b][o]]
 i+=1
print s[0]
```
## Using `reduce()`, 145
```
print reduce(lambda s,x:x in'+-*/'and[(lambda b,a:[a+b,a-b,a*b,b and a/b])(*s[:2])['+-*'.find(x)]]+s[2:]or[float(x)]+s,raw_input().split(),[])[0]
```
[Answer]
## Matlab, 228
```
F='+-/*';f={@plus,@minus,@rdivide,@times};t=strsplit(input('','s'),' ');i=str2double(t);j=~isnan(i);t(j)=num2cell(i(j));while numel(t)>1
n=find(cellfun(@(x)isstr(x),t),1);t{n}=bsxfun(f{t{n}==F},t{n-2:n-1});t(n-2:n-1)=[];end
t{1}
```
Ungolfed:
```
F = '+-/*'; %// possible operators
f = {@plus,@minus,@rdivide,@times}; %// to be used with bsxfun
t = strsplit(input('','s'),' '); %// input string and split by one or multiple spaces
i = str2double(t); %// convert each split string to number
j =~ isnan(i); %// these were operators, not numbers ...
t(j) = num2cell(i(j)); %// ... so restore them
while numel(t)>1
    n = find(cellfun(@(x)isstr(x),t),1); %// find left-most operator
    t{n} = bsxfun(f{t{n}==F}, t{n-2:n-1}); %// apply it to preceding numbers and replace
    t(n-2:n-1)=[]; %// remove used numbers
end
t{1} %// display result
```
[Answer]
# K5, 70 bytes
```
`0:*{$[-9=@*x;((*(+;-;*;%)@"+-*/"?y).-2#x;x,.y)@47<y;(.x;.y)]}/" "\0:`
```
I'm not sure when K5 was released, so this *might* not count. Still awesome!
]