问:
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.

Task

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

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

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

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

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

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard 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:

```<code>## Language Name, N bytes
</code>```

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:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

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:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Stack Cats, 62 + 4 = 66 bytes

```<code>*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```

Needs to be run with the -ln command-line flags (hence +4 bytes). Prints 0 for composite numbers and 1 for primes.

Try it online!

I think this is the first non-trivial Stack Cats program.

Explanation

A quick Stack Cats introduction:

Stack Cats operates on an infinite tape of stacks, with a tape head pointing at a current stack. Every stack is initially filled with an infinite amount of zeros. I will generally ignore these zeros in my wording, so when I say "the bottom of stack" I mean the lowest non-zero value and if I say "the stack is empty" I mean there's only zeros on it.

Before the program starts, a -1 is pushed onto the initial stack, and then the entire input is pushed on top of that. In this case, due to the -n flag, the input is read as a decimal integer.

At the end of the program, the current stack is used for output. If there's a -1 at the bottom, it will be ignored. Again, due to the -n flag, the values from the stack are simply printed as linefeed-separated decimal integers.

Stack Cats is a reversible program language: every piece of code can be undone (without Stack Cats keeping track of an explicit history). More specifically, to reverse any piece of code, you simply mirror it, e.g. <<(\-_) becomes (_-/)>>. This design goal places fairly severe restrictions on what kinds of operators and control flow constructs exist in the language, and what sorts of functions you can compute on the global memory state.

To top it all off, every Stack Cats program has to be self-symmetric. You might notice that this is not the case for the above source code. This is what the -l flag is for: it implicitly mirrors the code to the left, using the first character for the centre. Hence the actual program is:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```

Programming effectively with the entire code is highly non-trivial and unintuitive and haven't really figured out yet how a human can possibly do it. We've brute forced such program for simpler tasks, but wouldn't have been able to get anywhere near that by hand. Luckily, we've found a basic pattern which allows you to ignore one half of the program. While this is certainly suboptimal, it's currently the only known way to program effectively in Stack Cats.

So in this answer, the template of said pattern is this (there's some variability in how it's executed):

```<code>[<(...)*(...)>]
</code>```

When the program starts, the stack tape looks like this (for input 4, say):

```<code>     4
... -1 ...
     0
     ^
</code>```

The [ moves the top of the stack to the left (and the tape head along) - we call this "pushing". And the < moves the tape head alone. So after the first two commands, we've got this situation:

```<code>...   4 -1 ...
    0 0  0
    ^
</code>```

Now the (...) is a loop which can be used quite easily as a conditional: the loop is entered and left only when the top of the current stack is positive. Since, it's currently zero, we skip the entire first half of the program. Now the centre command is *. This is simply XOR 1, i.e. it toggles the least significant bit of the top of the stack, and in this case turns the 0 into a 1:

```<code>... 1 4 -1 ...
    0 0  0
    ^
</code>```

Now we encounter the mirror image of the (...). This time the top of the stack is positive and we do enter the code. Before we look into what goes on inside the parentheses, let me explain how we'll wrap up at the end: we want to ensure that at the end of this block, we have the tape head on a positive value again (so that the loop terminates after a single iteration and is used simply as a linear conditional), that the stack to the right holds the output and that the stack right of that holds a -1. If that's the case, we do leave the loop, > moves onto the output value and ] pushes it onto the -1 so we have a clean stack for output.

That's that. Now inside the parentheses we can do whatever we want to check the primality as long as we ensure that we set things up as described in the previous paragraph at the end (which can easily done with some pushing and tape head moving). I first tried solving the problem with Wilson's theorem but ended up well over 100 bytes, because the squared factorial computation is actually quite expensive in Stack Cats (at least I haven't found a short way). So I went with trial division instead and that indeed turned out much simpler. Let's look at the first linear bit:

```<code>>:^]
</code>```

You've already seen two of those commands. In addition, : swaps the top two values of the current stack and ^ XORs the second value into the top value. This makes :^ a common pattern to duplicate a value on an empty stack (we pull a zero on top of the value and then turn the zero into 0 XOR x = x). So after this, section our tape looks like this:

```<code>         4
... 1 4 -1 ...
    0 0  0
         ^
</code>```

The trial division algorithm I've implemented doesn't work for input 1, so we should skip the code in that case. We can easily map 1 to 0 and everything else to positive values with *, so here's how we do that:

```<code>*(*...)
</code>```

That is we turn 1 into 0, skip a big part of the code if we get indeed 0, but inside we immediately undo the * so that we get our input value back. We just need to make sure again that we end on a positive value at the end of the parentheses so that they don't start looping. Inside the conditional, we move one stack right with the > and then start the main trial division loop:

```<code>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}
</code>```

Braces (as opposed to parentheses) define a different kind of loop: it's a do-while loop, meaning it always runs for at least one iteration. The other difference is the termination condition: when entering the loop Stack Cat remembers the top value of the current stack (0 in our case). The loop will then run until this same value is seen again at the end of an iteration. This is convenient for us: in each iteration we simply compute the remainder of the next potential divisor and move it onto this stack we're starting the loop on. When we find a divisor, the remainder is 0 and the loop stops. We will try divisors starting at n-1 and then decrement them down to 1. That means a) we know this will terminate when we reach 1 at the latest and b) we can then determine whether the number is prime or not by inspecting the last divisor we tried (if it's 1, it's a prime, otherwise it isn't).

Let's get to it. There's a short linear section at the beginning:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```0

You know what most of those things do by now. The new commands are - and !. Stack Cats does not have increment or decrement operators. However it has - (negation, i.e. multiply by -1) and ! (bitwise NOT, i.e. multiply by -1 and decrement). These can be combined into either an increment, !-, or decrement -!. So we decrement the copy of n on top of the -1, then make another copy of n on the stack to the left, then fetch the new trial divisor and put it beneath n. So on the first iteration, we get this:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```1

On further iterations, the 3 will replaced with the next test divisor and so on (whereas the two copies of n will always be the same value at this point).

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```2

This is the modulo computation. Since loops terminate on positive values, the idea is to start from -n and repeatedly add the trial divisor d to it until we get a positive value. Once we do, we subtract the result from d and this gives us the remainder. The tricky bit here is that we can't just have put a -n on top of the stack and start a loop that adds d: if the top of the stack is negative, the loop won't be entered. Such are the limitations of a reversible programming language.

So to circumvent this issue, we do start with n on top of the stack, but negate it only on the first iteration. Again, that sounds simpler than it turns out to be...

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```3

When the top of the stack is positive (i.e. only on the first iteration), we negate it with -. However, we can't just do (-) because then we wouldn't be leaving the loop until - was applied twice. So we move one cell left with < because we know there's a positive value there (the 1). Okay, so now we've reliably negated n on the first iteration. But we have a new problem: the tape head is now in a different position on the first iteration than in every other one. We need to consolidate this before we move on. The next < moves the tape head left. The situation on the first iteration:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```4

And on the second iteration (remember we've added d once into -n now):

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```5

The next conditional merges these paths again:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```6

On the first iteration the tape head points at a zero, so this is skipped entirely. On further iterations, the tape head points at a one though, so we do execute this, move to the left and increment the cell there. Since we know the cell starts from zero, it will now always be positive so we can leave the loop. This ensures we always end up two stack left of the main stack and can now move back with >>. Then at the end of the modulo loop we do -_. You already know -. _ is to subtraction what ^ is to XOR: if the top of the stack is a and the value underneath is b it replaces a with b-a. Since we first negated a though, -_ replaces a with b+a, thereby adding d into our running total.

After the loop ends (we've reached a positive) value, the tape looks like this:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```7

The left-most value could be any positive number. In fact, it's the number of iterations minus one. There's another short linear bit now:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```8

Like I said earlier we need to subtract the result from d to obtain the actual remainder (3-2 = 1 = 4 % 3), so we just do _ once more. Next, we need to clean up the stack that we've been incrementing on the left: when we try the next divisor, it needs to be zero again, for the first iteration to work. So we move there and push that positive value onto the other helper stack with <<] and then move back onto our operational stack with another >. We pull up d with : and push it back onto the -1 with ] and then we move the remainder onto our conditional stack with <]]. That's the end of the trial division loop: this continues until we get a zero remainder, in which case the stack to the left contains n's greatest divisor (other than n).

After the loop ends, there's just *< before we join paths with the input 1 again. The * simply turns the zero into a 1, which we'll need in a bit, and then we move to the divisor with < (so that we're on the same stack as for input 1).

At this point it helps to compare three different kinds of inputs. First, the special case n = 1 where we haven't done any of that trial division stuff:

```<code>[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]
</code>```9

Then, our previous example n = 4, a composite number:

```<code>[<(...)*(...)>]
</code>```0

And finally, n = 3, a prime number:

```<code>[<(...)*(...)>]
</code>```1

So for prime numbers, we have a 1 on this stack, and for composite numbers we either have a 0 or a positive number greater than 2. We turn this situation into the 0 or 1 we need with the following final piece of code:

```<code>[<(...)*(...)>]
</code>```2

] just pushes this value to the right. Then * is used to simplify the conditional situation greatly: by toggling the least significant bit, we turn 1 (prime) into 0, 0 (composite) into the positive value 1, and all other positive values will still remain positive. Now we just need to distinguish between 0 and positive. That's where we use another (:). If the top of the stack is 0 (and the input was a prime), this is simply skipped. But if the top of the stack is positive (and the input was a composite number) this swaps it with the 1, so that we now have 0 for composite and 1 for primes - only two distinct values. Of course, they are the opposite of what we want to output, but that is easily fixed with another *.

Now all that's left is to restore the pattern of stacks expected by our surrounding framework: tape head on a positive value, result on top of the stack to the right, and a single -1 on the stack right of that. This is what =<* is for. = swaps the tops of the two adjacent stacks, thereby moving the -1 to the right of the result, e.g. for input 4 again:

```<code>    2     0
    1     3
... 1 4   1 -1 ...
    0 0 0 0  0
          ^
</code>```

Then we just move left with < and turn that zero into a one with *. And that's that.

If you want to dig deeper into how the program works, you can make use of the debug options. Either add the -d flag and insert " wherever you want to see the current memory state, e.g. like this, or use the -D flag to get a complete trace of the entire program. Alternatively, you can use Timwi's EsotericIDE which includes a Stack Cats interpreter with a step-by-step debugger.

Title: Is this number a prime?

Body:
Stack Cats, 62 + 4 = 66 bytes

*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]

Needs to be run with the -ln command-line flags (hence +4 bytes). Prints 0 for composite numbers and 1 for primes.

Try it online!

I think this is the first non-trivial Stack Cats program.

Explanation

A quick Stack Cats introduction:

Stack Cats operates on an infinite tape of stacks, with a tape head pointing at a current stack. Every stack is initially filled with an infinite amount of zeros. I will generally ignore these zeros in my wording, so when I say "the bottom of stack" I mean the lowest non-zero value and if I say "the stack is empty" I mean there's only zeros on it.

Before the program starts, a -1 is pushed onto the initial stack, and then the entire input is pushed on top of that. In this case, due to the -n flag, the input is read as a decimal integer.

At the end of the program, the current stack is used for output. If there's a -1 at the bottom, it will be ignored. Again, due to the -n flag, the values from the stack are simply printed as linefeed-separated decimal integers.

Stack Cats is a reversible program language: every piece of code can be undone (without Stack Cats keeping track of an explicit history). More specifically, to reverse any piece of code, you simply mirror it, e.g. <<(\-_) becomes (_-/)>>. This design goal places fairly severe restrictions on what kinds of operators and control flow constructs exist in the language, and what sorts of functions you can compute on the global memory state.

To top it all off, every Stack Cats program has to be self-symmetric. You might notice that this is not the case for the above source code. This is what the -l flag is for: it implicitly mirrors the code to the left, using the first character for the centre. Hence the actual program is:

[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]

Programming effectively with the entire code is highly non-trivial and unintuitive and haven't really figured out yet how a human can possibly do it. We've brute forced such program for simpler tasks, but wouldn't have been able to get anywhere near that by hand. Luckily, we've found a basic pattern which allows you to ignore one half of the program. While this is certainly suboptimal, it's currently the only known way to program effectively in Stack Cats.

So in this answer, the template of said pattern is this (there's some variability in how it's executed):

[<(...)*(...)>]

When the program starts, the stack tape looks like this (for input 4, say):

     4
... -1 ...
     0
     ^

The [ moves the top of the stack to the left (and the tape head along) - we call this "pushing". And the < moves the tape head alone. So after the first two commands, we've got this situation:

...   4 -1 ...
    0 0  0
    ^

Now the (...) is a loop which can be used quite easily as a conditional: the loop is entered and left only when the top of the current stack is positive. Since, it's currently zero, we skip the entire first half of the program. Now the centre command is *. This is simply XOR 1, i.e. it toggles the least significant bit of the top of the stack, and in this case turns the 0 into a 1:

... 1 4 -1 ...
    0 0  0
    ^

Now we encounter the mirror image of the (...). This time the top of the stack is positive and we do enter the code. Before we look into what goes on inside the parentheses, let me explain how we'll wrap up at the end: we want to ensure that at the end of this block, we have the tape head on a positive value again (so that the loop terminates after a single iteration and is used simply as a linear conditional), that the stack to the right holds the output and that the stack right of that holds a -1. If that's the case, we do leave the loop, > moves onto the output value and ] pushes it onto the -1 so we have a clean stack for output.

That's that. Now inside the parentheses we can do whatever we want to check the primality as long as we ensure that we set things up as described in the previous paragraph at the end (which can easily done with some pushing and tape head moving). I first tried solving the problem with Wilson's theorem but ended up well over 100 bytes, because the squared factorial computation is actually quite expensive in Stack Cats (at least I haven't found a short way). So I went with trial division instead and that indeed turned out much simpler. Let's look at the first linear bit:

>:^]

You've already seen two of those commands. In addition, : swaps the top two values of the current stack and ^ XORs the second value into the top value. This makes :^ a common pattern to duplicate a value on an empty stack (we pull a zero on top of the value and then turn the zero into 0 XOR x = x). So after this, section our tape looks like this:

         4
... 1 4 -1 ...
    0 0  0
         ^

The trial division algorithm I've implemented doesn't work for input 1, so we should skip the code in that case. We can easily map 1 to 0 and everything else to positive values with *, so here's how we do that:

*(*...)

That is we turn 1 into 0, skip a big part of the code if we get indeed 0, but inside we immediately undo the * so that we get our input value back. We just need to make sure again that we end on a positive value at the end of the parentheses so that they don't start looping. Inside the conditional, we move one stack right with the > and then start the main trial division loop:

{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}

Braces (as opposed to parentheses) define a different kind of loop: it's a do-while loop, meaning it always runs for at least one iteration. The other difference is the termination condition: when entering the loop Stack Cat remembers the top value of the current stack (0 in our case). The loop will then run until this same value is seen again at the end of an iteration. This is convenient for us: in each iteration we simply compute the remainder of the next potential divisor and move it onto this stack we're starting the loop on. When we find a divisor, the remainder is 0 and the loop stops. We will try divisors starting at n-1 and then decrement them down to 1. That means a) we know this will terminate when we reach 1 at the latest and b) we can then determine whether the number is prime or not by inspecting the last divisor we tried (if it's 1, it's a prime, otherwise it isn't).

Let's get to it. There's a short linear section at the beginning:

<-!<:^>[:

You know what most of those things do by now. The new commands are - and !. Stack Cats does not have increment or decrement operators. However it has - (negation, i.e. multiply by -1) and ! (bitwise NOT, i.e. multiply by -1 and decrement). These can be combined into either an increment, !-, or decrement -!. So we decrement the copy of n on top of the -1, then make another copy of n on the stack to the left, then fetch the new trial divisor and put it beneath n. So on the first iteration, we get this:

      4
      3
... 1 4 -1 ...
    0 0  0
      ^

On further iterations, the 3 will replaced with the next test divisor and so on (whereas the two copies of n will always be the same value at this point).

((-<)<(<!-)>>-_)

This is the modulo computation. Since loops terminate on positive values, the idea is to start from -n and repeatedly add the trial divisor d to it until we get a positive value. Once we do, we subtract the result from d and this gives us the remainder. The tricky bit here is that we can't just have put a -n on top of the stack and start a loop that adds d: if the top of the stack is negative, the loop won't be entered. Such are the limitations of a reversible programming language.

So to circumvent this issue, we do start with n on top of the stack, but negate it only on the first iteration. Again, that sounds simpler than it turns out to be...

(-<)

When the top of the stack is positive (i.e. only on the first iteration), we negate it with -. However, we can't just do (-) because then we wouldn't be leaving the loop until - was applied twice. So we move one cell left with < because we know there's a positive value there (the 1). Okay, so now we've reliably negated n on the first iteration. But we have a new problem: the tape head is now in a different position on the first iteration than in every other one. We need to consolidate this before we move on. The next < moves the tape head left. The situation on the first iteration:

        -4
         3
...   1  4 -1 ...
    0 0  0  0
    ^

And on the second iteration (remember we've added d once into -n now):

      -1
       3
... 1  4 -1 ...
    0  0  0
    ^

The next conditional merges these paths again:

(<!-)

On the first iteration the tape head points at a zero, so this is skipped entirely. On further iterations, the tape head points at a one though, so we do execute this, move to the left and increment the cell there. Since we know the cell starts from zero, it will now always be positive so we can leave the loop. This ensures we always end up two stack left of the main stack and can now move back with >>. Then at the end of the modulo loop we do -_. You already know -. _ is to subtraction what ^ is to XOR: if the top of the stack is a and the value underneath is b it replaces a with b-a. Since we first negated a though, -_ replaces a with b+a, thereby adding d into our running total.

After the loop ends (we've reached a positive) value, the tape looks like this:

        2
        3
... 1 1 4 -1 ...
    0 0 0  0
        ^

The left-most value could be any positive number. In fact, it's the number of iterations minus one. There's another short linear bit now:

_<<]>:]<]]

Like I said earlier we need to subtract the result from d to obtain the actual remainder (3-2 = 1 = 4 % 3), so we just do _ once more. Next, we need to clean up the stack that we've been incrementing on the left: when we try the next divisor, it needs to be zero again, for the first iteration to work. So we move there and push that positive value onto the other helper stack with <<] and then move back onto our operational stack with another >. We pull up d with : and push it back onto the -1 with ] and then we move the remainder onto our conditional stack with <]]. That's the end of the trial division loop: this continues until we get a zero remainder, in which case the stack to the left contains n's greatest divisor (other than n).

After the loop ends, there's just *< before we join paths with the input 1 again. The * simply turns the zero into a 1, which we'll need in a bit, and then we move to the divisor with < (so that we're on the same stack as for input 1).

At this point it helps to compare three different kinds of inputs. First, the special case n = 1 where we haven't done any of that trial division stuff:

         0
... 1 1 -1 ...
    0 0  0
         ^

Then, our previous example n = 4, a composite number:

    2
    1    2 1
... 1 4 -1 1 ...
    0 0  0 0
         ^

And finally, n = 3, a prime number:

    3
    1    1 1
... 1 3 -1 1 ...
    0 0  0 0
         ^

So for prime numbers, we have a 1 on this stack, and for composite numbers we either have a 0 or a positive number greater than 2. We turn this situation into the 0 or 1 we need with the following final piece of code:

]*(:)*=<*

] just pushes this value to the right. Then * is used to simplify the conditional situation greatly: by toggling the least significant bit, we turn 1 (prime) into 0, 0 (composite) into the positive value 1, and all other positive values will still remain positive. Now we just need to distinguish between 0 and positive. That's where we use another (:). If the top of the stack is 0 (and the input was a prime), this is simply skipped. But if the top of the stack is positive (and the input was a composite number) this swaps it with the 1, so that we now have 0 for composite and 1 for primes - only two distinct values. Of course, they are the opposite of what we want to output, but that is easily fixed with another *.

Now all that's left is to restore the pattern of stacks expected by our surrounding framework: tape head on a positive value, result on top of the stack to the right, and a single -1 on the stack right of that. This is what =<* is for. = swaps the tops of the two adjacent stacks, thereby moving the -1 to the right of the result, e.g. for input 4 again:

    2     0
    1     3
... 1 4   1 -1 ...
    0 0 0 0  0
          ^

Then we just move left with < and turn that zero into a one with *. And that's that.

If you want to dig deeper into how the program works, you can make use of the debug options. Either add the -d flag and insert " wherever you want to see the current memory state, e.g. like this, or use the -D flag to get a complete trace of the entire program. Alternatively, you can use Timwi's EsotericIDE which includes a Stack Cats interpreter with a step-by-step debugger.


问:
Decode a Microsoft MS-DOS 5.0 FAT directory entry
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as big endian, and we're calling byte 0x00 as the left-most, and byte 0x1F as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in bold).

The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be output as ASCII with a period (.) between.

Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should ignore spaces (i.e., don't output them).

The file extension may be empty (i.e., all spaces), in which case the output should not output the dot.

Since ASCII only uses the lower 7 bits, the bytes will all have a leading 0.

The next byte (0x0b) is a bitmask of the following:

0x01 Read Only - output RO

0x02 Hidden - output H

0x04 System - output S

0x08 Volume Label - output VL. File size (below) should be output as 0, regardless of its actual entry.

0x10 Subdirectory - output SD. File size (below) should be output as 0, regardless of its actual entry.

0x20 Archive - output A

0x40 Device - ignored for this challenge.

0x80 Reserved - ignored for this challenge.

Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, 0xff could be ROHSVLSDA (or any other combination).

The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.

The next two bytes (0x0e and 0x0f) are the creation time as follows:

Bits 15 to 11 are the hours in 24-hour format - output 00 to 23

Bits 10 to 5 are the minutes - output 00 to 59

Bits 4 to 0 are the seconds/2 - output 00 to 58 (note that seconds are only in two-second resolution)

For clarification: hhhhhmmmmmmsssss when written big-endian.

The next two bytes (0x10 and 0x11) are the creation date as follows:

Bits 15 to 9 are the year - output 1980 for 0 up to 2107 for 127

Bits 8 to 5 are the months - output 1 to 12 (with or without leading zero)

Bits 4 to 0 are the day - output 0 to 31 (with or without leading zero)

For clarification: yyyyyyymmmmddddd when written big-endian.

The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.

The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.

The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.

The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.

The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.

The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an unsigned integer, unless the VL or SD flags are set (above), in which case output 0.

Visual representation

```<code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
</code>```

Input

A single 32-byte word (i.e., 256 bits), in whatever format is convenient.

This could be as a string of 1 and 0, as several unsigned ints, an array of Boolean values, etc.

Please specify in your answer what format you're using for input.

You cannot take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the only way for your language to take input. Parsing the input is part of the challenge.

You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).

Bytes that are unused can be all 0, all 1, etc., just so long as they are present. In the below examples, I used all 0 for the unused bytes.

Output

Either printed to screen or returned, the following:

The filename as an ASCII string

The file attributes as an ASCII string

The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)

The modified time and modified date, again with appropriate separators

The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

Rules

Standard I/O formats are acceptable.

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Built-ins that perform exactly this function are forbidden.

Examples

```<code>0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
</code>```

答:
Java, <s>1721</s> <s>1587</s> <s>1573</s> <s>1560</s> 1511 bytes:

```<code>import java.util.*;class A{int Q(String a,int b){return Integer.parseInt(a,b);}String P(int a){return Integer.toString(a);}ArrayList<String>B=new ArrayList<String>();void J(String O){B.add(O);}String TD(String l,String p,int a,int c,int d){String X,Y,Z;X=Y=Z=new String();int i=0;for(char F:l.toCharArray()){if(i<a){X+=F;}if(a<=i&i<c){Y+=F;}if(c<=i){Z+=F;}i++;}String[]H=new String[3];H[0]=P(d+Q(X,2));H[1]=P(Q(Y,2));H[2]=(p==":")?P(Q(Z,2)*2):P(Q(Z,2));int T=0;for(String A:H){H[T]=(A.length()<2)?"0"+A:A;T++;}return H[0]+p+H[1]+p+H[2];}String D(String i){String K=new String();int L=0;for(char Y:i.toCharArray()){if(L%8<1){K+=" ";}K+=Y;L++;}String[]C=K.split(" ");String[]z={"RO","H","S","VL","SD","A"};int[]l={1,2,4,8,16,32};Map<Integer,String>U=new HashMap<Integer,String>();for (int e=0;e<l.length;e++){U.put(l[e],z[e]);}String[]N={":","/",":","/"};int[]M={15,17,23,25};int[]O={5,7,5,7};int[]P={0,1980,0,1980};for(int y=1;y<9;y++){if((char)Q(C[y],2)!=' '){J(Character.toString((char)Q(C[y],2)));}}for(int v=9;v<12;v++){if((char)Q(C[v],2)!=' '){if(!B.contains(".")){J(".");}J(Character.toString((char)Q(C[v],2)));}}J(" ");int T=(char)Q(C[12],2);while(T>0){int H=l[0];for(int V:l){if(V<=T){H=V;}}J(U.get(H));T-=H;}for(int w=0;w<4;w++){J(" ");J(TD(C[M[w]]+C[M[w]+1],N[w],O[w],11,P[w]));}J(" ");if(B.contains("SD")||B.contains("VL")){J("0");}else{J(P(Q(C[29]+C[30]+C[31]+C[32],2)));}return String.join("",B);}public static void main(String[]a){A H=new A();System.out.print(H.D(new Scanner(System.in).next()));}}
</code>```

Takes input in the format of 32 byte binary string. Outputs in the format of a space separated string. This may be a very very long answer, but I'm still not disappointed. I'm just happy I was able to implement this in Java. I will still try to golf this as much as I can, though.

Try It Online! (Ideone)

ContentLicense: CC BY-SA 3.0

Body:
Java, <s>1721</s> <s>1587</s> <s>1573</s> <s>1560</s> 1511 bytes:

import java.util.*;class A{int Q(String a,int b){return Integer.parseInt(a,b);}String P(int a){return Integer.toString(a);}ArrayList<String>B=new ArrayList<String>();void J(String O){B.add(O);}String TD(String l,String p,int a,int c,int d){String X,Y,Z;X=Y=Z=new String();int i=0;for(char F:l.toCharArray()){if(i<a){X+=F;}if(a<=i&i<c){Y+=F;}if(c<=i){Z+=F;}i++;}String[]H=new String[3];H[0]=P(d+Q(X,2));H[1]=P(Q(Y,2));H[2]=(p==":")?P(Q(Z,2)*2):P(Q(Z,2));int T=0;for(String A:H){H[T]=(A.length()<2)?"0"+A:A;T++;}return H[0]+p+H[1]+p+H[2];}String D(String i){String K=new String();int L=0;for(char Y:i.toCharArray()){if(L%8<1){K+=" ";}K+=Y;L++;}String[]C=K.split(" ");String[]z={"RO","H","S","VL","SD","A"};int[]l={1,2,4,8,16,32};Map<Integer,String>U=new HashMap<Integer,String>();for (int e=0;e<l.length;e++){U.put(l[e],z[e]);}String[]N={":","/",":","/"};int[]M={15,17,23,25};int[]O={5,7,5,7};int[]P={0,1980,0,1980};for(int y=1;y<9;y++){if((char)Q(C[y],2)!=' '){J(Character.toString((char)Q(C[y],2)));}}for(int v=9;v<12;v++){if((char)Q(C[v],2)!=' '){if(!B.contains(".")){J(".");}J(Character.toString((char)Q(C[v],2)));}}J(" ");int T=(char)Q(C[12],2);while(T>0){int H=l[0];for(int V:l){if(V<=T){H=V;}}J(U.get(H));T-=H;}for(int w=0;w<4;w++){J(" ");J(TD(C[M[w]]+C[M[w]+1],N[w],O[w],11,P[w]));}J(" ");if(B.contains("SD")||B.contains("VL")){J("0");}else{J(P(Q(C[29]+C[30]+C[31]+C[32],2)));}return String.join("",B);}public static void main(String[]a){A H=new A();System.out.print(H.D(new Scanner(System.in).next()));}}

Takes input in the format of 32 byte binary string. Outputs in the format of a space separated string. This may be a very very long answer, but I'm still not disappointed. I'm just happy I was able to implement this in Java. I will still try to golf this as much as I can, though.

Try It Online! (Ideone)


问:
Alternating Sign Sequence

Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

```<code>1, 0, -1
</code>```

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
Java, 19 bytes

Using lambda expressions.

```<code>i->(1+i/3)*(1-i%3);
</code>```

Try it here!

Title: Alternating Sign Sequence

Body:
Java, 19 bytes

Using lambda expressions.

i->(1+i/3)*(1-i%3);

Try it here!


问:
Index sum and strip my matrix

Index sum and strip my matrix

Given a matrix/2d array in your preferable language

Input:

The matrix will always have an odd length

The matrix will always be perfectly square

The matrix values can be any integer in your language (positive or negative)

Example:

```<code>1  2  3  4  5  6  7
2  3  4  5  6  7  8
3  4  50 6  7  8  9
4  5  6 100 8  9  10
5  6  7  8 -9  10 11
6  7  8  9  10 11 12
7  8 900 10 11 12 0
</code>```

Definitions:

The "central number" is defined as the number that has the same amount of numbers to the left,right,up and down

In this case its middlemost 100

The "outer shell" is the collection of numbers which their x and y index is or 0 or the matrix size

```<code>1  2  3  4  5  6  7
2                 8
3                 9
4                 10
5                 11
6                 12
7  8 900 10 11 12 0
</code>```

Your task:

Add to the central number the sum of each row and column after multiplying the values in each by their 1-based index

A single row for example

```<code>4  5  6  7  8
</code>```

for each number

```<code>number * index + number * index.....

4*1 + 5*2 + 6*3 + 7*4 + 8*5 => 100
</code>```

example:

```<code> 2 -3 -9  4  7  1  5  => 61
-2  0 -2 -7 -7 -7 -4  => -141
 6 -3 -2 -2 -3  2  1  => -10
 8 -8  4  1 -8  2  0  => -20
-5  6  7 -1  8  4  8  => 144
 1  5  7  8  7 -9 -5  => 10
 7  7 -2  2 -7 -8  0  => -60
                         |
78 65 60 45 -15 -89 10   => 154
                     |
                     => -16
</code>```

For all rows and columns you combine these values..

Now you sum these too => 154-16 = 138

You add that number to the "central number" and remove the "outer shell" of the matrix

```<code> 0 -2 -7 -7 -7     => -88
-3 -2 -2 -3  2     => -15
-8  4 1+138 -8  2  => 395
 6  7 -1  8  4     => 69
 5  7  8  7 -9     => 26

19 69 442 30 -26
</code>```

do this untill you end up with a single number

```<code>-2 -2 -3     => -15
 4  1060 -8  => 2100
 7 -1  8     => 29

27 2115 5
</code>```

Add 2114+2147 to 1060

Remove the "outer shell" and get 5321

Now we have a single number left

this is the output!

test cases:

```<code>-6

-6
</code>```

```<code>-7 -1  8
-4 -6  7
-3 -6  6

2
</code>```

```<code> 6  7 -2  5  1
-2  6 -4 -2  3
-1 -4  0 -2 -7
 0  1  4 -4  8
-8 -6 -5  0  2

-365
</code>```

```<code> 8  3  5  6  6 -7  5
 6  2  4 -2 -1  8  3
 2  1 -5  3  8  2 -3
 3 -1  0  7 -6  7 -5
 0 -8 -4 -9 -4  2 -8
 8 -9 -3  5  7  8  5
 8 -1  4  5  1 -4  8

17611
</code>```

```<code>-9 -7  2  1  1 -2  3 -7 -3  6  7  1  0
-7 -8 -9 -2  7 -2  5  4  7 -7  8 -9  8
-4  4 -1  0  1  5 -3  7  1 -2 -9  4  8
 4  8  1 -1  0  7  4  6 -9  3 -9  3 -9
-6 -8 -4 -8 -9  2  1  1 -8  8  2  6 -4
-8 -5  1  1  2 -9  3  7  2  5 -6 -1  2
-8 -5 -7 -4 -9 -2  5  0  2 -4  2  0 -2
-3 -6 -3  2 -9  8  1 -5  5  0 -4 -1 -9
-9 -9 -8  0 -5 -7  1 -2  1 -4 -1  5  7
-6 -9  4 -2  8  7 -9 -5  3 -1  1  8  4
-6  6 -3 -4  3  5  6  8 -2  5 -1 -7 -9
-1  7 -9  4  6  7  6 -8  5  1  0 -3  0
-3 -2  5 -4  0  0  0 -1  7  4 -9 -4  2

-28473770
</code>```

This is a codegolf challenge so the program with the lowest bytecount wins

Title: Index sum and strip my matrix

Body:
J, 66 bytes

([:}:@}."1@}:@}.]+(i.@,~=](]+*)<.@-:)@#*[:+/^:2#\*]+|:)^:(<.@-:@#)

Straight-forward approach based on the process described in the challenge.

[:+/^:2#\*]+|: gets the sum. ]+(i.@,~=](]+*)<.@-:)@#* is a particularly ugly way to increment the center by the sum. [:}:@}."1@}:@}. removes the outer shell. There probably is a better way to do this.

Usage

   f =: ([:}:@}."1@}:@}.]+(i.@,~=](]+*)<.@-:)@#*[:+/^:2#\*]+|:)^:(<.@-:@#)
   f _6
_6
   f _7 _1 8 , _4 _6 7 ,: _3 _6 6
2
   f 6 7 _2 5 1 , _2 6 _4 _2 3 , _1 _4 0 _2 _7 , 0 1 4 _4 8 ,: _8 _6 _5 0 2
_365
   f 8 3 5 6 6 _7 5 , 6 2 4 _2 _1 8 3 , 2 1 _5 3 8 2 _3 , 3 _1 0 7 _6 7 _5 , 0 _8 _4 _9 _4 2 _8 ,8 _9 _3 5 7 8 5 ,: 8 _1 4 5 1 _4 8
17611
   f (13 13 $ _9 _7 2 1 1 _2 3 _7 _3 6 7 1 0 _7 _8 _9 _2 7 _2 5 4 7 _7 8 _9 8 _4 4 _1 0 1 5 _3 7 1 _2 _9 4 8 4 8 1 _1 0 7 4 6 _9 3 _9 3 _9 _6 _8 _4 _8 _9 2 1 1 _8 8 2 6 _4 _8 _5 1 1 2 _9 3 7 2 5 _6 _1 2 _8 _5 _7 _4 _9 _2 5 0 2 _4 2 0 _2 _3 _6 _3 2 _9 8 1 _5 5 0 _4 _1 _9 _9 _9 _8 0 _5 _7 1 _2 1 _4 _1 5 7 _6 _9 4 _2 8 7 _9 _5 3 _1 1 8 4 _6 6 _3 _4 3 5 6 8 _2 5 _1 _7 _9 _1 7 _9 4 6 7 6 _8 5 1 0 _3 0 _3 _2 5 _4 0 0 0 _1 7 4 _9 _4 2)
_28473770


问:
Tips for golfing in Factor
What general tips do you have for golfing in Factor? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Factor (e.g. "remove comments" is not an answer).</p>

答:
The following are equivalent:

```<code>1 '[ _ blah ]
1 [ blah ] curry
</code>```

It's just that the top one is shorter by three bytes.

Title: Tips for golfing in Factor

Body:
The following are equivalent:

1 '[ _ blah ]
1 [ blah ] curry

It's just that the top one is shorter by three bytes.


问:
Calculate Euler's totient function

Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

答:
Factor, 50 bytes

```<code>[ dup iota swap '[ _ gcd nip 1 = ] filter length ]
</code>```

Makes a range (iota) n, and curries n into a function which gets gcd x n for all values of 0 <= x <= n, tests if the result is 1. Filter the original range on whether the result of gcd x n was 1, and take its length.

Title: Calculate Euler's totient function

Body:
Factor, 50 bytes

[ dup iota swap '[ _ gcd nip 1 = ] filter length ]

Makes a range (iota) n, and curries n into a function which gets gcd x n for all values of 0 <= x <= n, tests if the result is 1. Filter the original range on whether the result of gcd x n was 1, and take its length.


问:
Find the Factorial!
Create the shortest program or function that finds the factorial of a non-negative integer.

The factorial, represented with ! is defined as such

$$n!:=\begin{cases}1 & n=0\\n\cdot(n-1)!&n>0\end{cases}$$

In plain English the factorial of 0 is 1 and the factorial of n, where n is larger than 0 is n times the factorial of one less than n.

Your code should perform input and output using a standard methods.

Requirements:

Does not use any built-in libraries that can calculate the factorial (this includes any form of eval)

Can calculate factorials for numbers up to 125

Can calculate the factorial for the number 0 (equal to 1)

Completes in under a minute for numbers up to 125

The shortest submission wins, in the case of a tie the answer with the most votes at the time wins.

答:
Java, 51 bytes

```<code>class a{double A(double b){return b<1?1:b*A(b-1);}}
</code>```

I'm actually glad Coding Ground can handle more stack frames than what is needed to overflow a double with this.

ContentLicense: CC BY-SA 4.0

Title: Find the Factorial!

Body:
Java, 51 bytes

class a{double A(double b){return b<1?1:b*A(b-1);}}

I'm actually glad Coding Ground can handle more stack frames than what is needed to overflow a double with this.


问:
Bytes/Character

Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

答:
Ruby, 33 bytes

Barely edges out Python, yay! Try it online.

```<code>->s{s.chars.map{|c|c.bytes.size}}
</code>```

Title: Bytes/Character

Body:
Ruby, 33 bytes

Barely edges out Python, yay! Try it online.

->s{s.chars.map{|c|c.bytes.size}}


答:
F#, <s>59</s> <s>54</s> 66 bytes

```<code>(s)=seq{for c in s->System.Text.Encoding.UTF8.GetByteCount([|c|])}
</code>```

Technically, s is a char sequence, but it turns out there's an implicit conversion that allows a string to be passed in.

When testing this in the console with !±≡, it splits the kanji into two characters, each 3 bytes long. All the other test cases work fine.

Edit: It turns out common namespace imports are not implicit. Up another 12 chars.

Title: Bytes/Character

Body:
Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

Body:
F#, <s>59</s> <s>54</s> 66 bytes

(s)=seq{for c in s->System.Text.Encoding.UTF8.GetByteCount([|c|])}

Technically, s is a char sequence, but it turns out there's an implicit conversion that allows a string to be passed in.

When testing this in the console with !±≡, it splits the kanji into two characters, each 3 bytes long. All the other test cases work fine.

Edit: It turns out common namespace imports are not implicit. Up another 12 chars.


问:
Display number of occurrences for every character in an input string
The code should take a string as input from keyboard:

```<code>The definition of insanity is quoting the same phrase again and again and not expect despair.
</code>```

The output should be like this(not sorted in any particular order):

```<code>  :  15
. :  1
T :  1
a :  10
c :  1
e :  8
d :  4
g :  3
f :  2
i :  10
h :  3
m :  1
o :  4
n :  10
q :  1
p :  3
s :  5
r :  2
u :  1
t :  6
y :  1
x :  1
</code>```

All ASCII characters count unicode is not a requirement, spaces, quotes,etc and input should come from keyboard / not constants, attributes, output should be printed with new line after each character like in the above example, it should not be returned as string or dumped as hashmap/dictionary etc, so x :  1 and x: 1 are ok, but  {'x':1,... and x:1 are not.

Q: Function or complete program taking stdin and writing stdout?

A: Code needs to be a program taking input using standard in and display the result via standard out.

Scoreboard:

Shortest overall: 5 bytes

<s>Shortest overall: 7 bytes</s>

答:
Java 8, <s>273</s> <s>253</s> <s>249</s> <s>246</s> <s>239</s> 200 bytes

interface I{static void main(String[]a){int m[]=new int[999],i=0;for(int c:new java.util.Scanner(System.in).nextLine().getBytes())m[c]++;for(;++i<999;)if(m[i]>0)System.out.printf("%c: %d%n",i,m[i]);}}
```
<p>-24 bytes thanks to <em>@Poke</em>.<br />
-7 bytes thanks to <em>@OlivierGrégoire</em>.</p>
<p><strong>Explanation:</strong></p>
<p>Try it here.</p>
<pre class="lang-java prettyprint-override"><code>interface I{                        // Class
  static void main(String[]a){      //  Mandatory main-method
    int m[]=new int[999],           //  Integer-array to count the occurrences
        i=0;                        //  Index-integer, starting at 0
    for(int c:new java.util.Scanner(System.in).nextLine().getBytes())
                                    //   Loop over the input as bytes:
      m[c]++;                       //    Increase the occurrence-counter of the char by 1
    for(;++i<999;)                  //   Loop over the array:
      if(m[i]>0)                    //    If the current character occurred at least once:
        System.out.print("%c: %d%n",//     Print with proper formatting:
         i,                         //      The character
         m[i]);}}                   //      and the occurrence-count
</code>```

Body:
Java 8, <s>273</s> <s>253</s> <s>249</s> <s>246</s> <s>239</s> 200 bytes

interface I{static void main(String[]a){int m[]=new int[999],i=0;for(int c:new java.util.Scanner(System.in).nextLine().getBytes())m[c]++;for(;++i<999;)if(m[i]>0)System.out.printf("%c: %d%n",i,m[i]);}}

-24 bytes thanks to @Poke.

-7 bytes thanks to @OlivierGrégoire.

Explanation:

Try it here.

interface I{                        // Class
  static void main(String[]a){      //  Mandatory main-method
    int m[]=new int[999],           //  Integer-array to count the occurrences
        i=0;                        //  Index-integer, starting at 0
    for(int c:new java.util.Scanner(System.in).nextLine().getBytes())
                                    //   Loop over the input as bytes:
      m[c]++;                       //    Increase the occurrence-counter of the char by 1
    for(;++i<999;)                  //   Loop over the array:
      if(m[i]>0)                    //    If the current character occurred at least once:
        System.out.print("%c: %d%n",//     Print with proper formatting:
         i,                         //      The character
         m[i]);}}                   //      and the occurrence-count


问:
Forecast Palindromic Dates
Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:

02/02/2020

12/02/2021

03/02/2030

The Challenge

Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (edit: including the range itself).

Rules

To qualify as a palindrome, only the numeric characters of the date should be
checked.

The date can be in any common format (MM/DD/YYYY, DD-MM-YYYY), as
long as it uses two digits for both the month and day and four for
the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (/, -, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer.

If there are more than one dates returned, they should be comma or
new-line separated.

Shortest answer wins!

Example

```<code>date_palindrome('05/02/2050', '12/12/2060')
>>>['05/02/2050', '06/02/2060']
</code>```

答:
Java 7, <s>436</s> <s>435</s> 416 bytes *sigh..*

```<code>import java.text.*;import java.util.*;void c(String...a)throws Exception{DateFormat f=new SimpleDateFormat("dd-MM-yyyy");Calendar s=Calendar.getInstance(),e=Calendar.getInstance();s.setTime(f.parse(a[0]));e.setTime(f.parse(a[1]));for(Date d=s.getTime();s.before(e);s.add(5,1),d=s.getTime()){String o=f.format(d),x=o.replaceAll("\\W|_",""),w="";for(char c:x.toCharArray())w=c+w;if(x.equals(w))System.out.println(o);}}
</code>```

Input & Output format: dd-MM-yyyy

Ungolfed & test code:

Try it here.

```<code>import java.text.*;
import java.util.*;

class Main{
  static void c(String... a) throws Exception{
    DateFormat f = new SimpleDateFormat("dd-MM-yyyy");
    Calendar s = Calendar.getInstance(),
             e = Calendar.getInstance();
    s.setTime(f.parse(a[0]));
    e.setTime(f.parse(a[1]));
    for(Date d = s.getTime(); s.before(e); s.add(Calendar.DATE, 1), d = s.getTime()){
      String o = f.format(d),
             x = o.replaceAll("\\W|_", ""),
             w = "";
      for(char c : x.toCharArray()){
        w = c + w;
      }
      if(x.equals(w)){
        System.out.println(o);
      }
    }
  }

  public static void main(String[] a){
    try{
      c("05-02-2050", "12-12-2060");
    } catch (Exception e){}
  }
}
</code>```

Output:

```<code>05-02-2050
15-02-2051
25-02-2052
06-02-2060
</code>```

Title: Forecast Palindromic Dates

Body:
Java 7, <s>436</s> <s>435</s> 416 bytes *sigh..*

import java.text.*;import java.util.*;void c(String...a)throws Exception{DateFormat f=new SimpleDateFormat("dd-MM-yyyy");Calendar s=Calendar.getInstance(),e=Calendar.getInstance();s.setTime(f.parse(a[0]));e.setTime(f.parse(a[1]));for(Date d=s.getTime();s.before(e);s.add(5,1),d=s.getTime()){String o=f.format(d),x=o.replaceAll("\\W|_",""),w="";for(char c:x.toCharArray())w=c+w;if(x.equals(w))System.out.println(o);}}

Input & Output format: dd-MM-yyyy

Ungolfed & test code:

Try it here.

import java.text.*;
import java.util.*;

class Main{
  static void c(String... a) throws Exception{
    DateFormat f = new SimpleDateFormat("dd-MM-yyyy");
    Calendar s = Calendar.getInstance(),
             e = Calendar.getInstance();
    s.setTime(f.parse(a[0]));
    e.setTime(f.parse(a[1]));
    for(Date d = s.getTime(); s.before(e); s.add(Calendar.DATE, 1), d = s.getTime()){
      String o = f.format(d),
             x = o.replaceAll("\\W|_", ""),
             w = "";
      for(char c : x.toCharArray()){
        w = c + w;
      }
      if(x.equals(w)){
        System.out.println(o);
      }
    }
  }

  public static void main(String[] a){
    try{
      c("05-02-2050", "12-12-2060");
    } catch (Exception e){}
  }
}

Output:

05-02-2050
15-02-2051
25-02-2052
06-02-2060


答:
C#, 257 bytes

here is a non esolang answer

```<code>void f(int[][]p){while(p.Length>1){int a=p.Length;int r=0;for(int i=0;i<a;i++)for(int j=0;j<a;j++)r+=(i+j+2)*p[i][j];p[a/2][a/2]+=r;p=p.Where((i,n)=>n>0&&n<p.Length-1).Select(k=>k.Where((i,n)=>n>0&&n<p.Length-1).ToArray()).ToArray();}Console.Write(p[0][0]);
</code>```

ungolfed:

```<code>void f(int[][]p)
    {
        while (p.Length>1)
        {
            int a=p.Length;
            int r=0; //integer for number to add to middle
            for (int i = 0; i < a; i++)
                for (int j = 0; j < a; j++)
                    r +=(i+j+2)*p[i][j]; //add each element to counter according to their 1 based index
            p[a / 2][a / 2] += r; //add counter to middle
            p = p.Where((i, n) => n > 0 && n < p.Length - 1).Select(k => k.Where((i, n) => n > 0 && n < p.Length - 1).ToArray()).ToArray(); //strip outer shell from array
        }
        Console.Write(p[0][0]); //print last and only value in array
    }
</code>```

Title: Index sum and strip my matrix

Body:
Index sum and strip my matrix

Given a matrix/2d array in your preferable language

Input:

The matrix will always have an odd length

The matrix will always be perfectly square

The matrix values can be any integer in your language (positive or negative)

Example:

```<code>1  2  3  4  5  6  7
2  3  4  5  6  7  8
3  4  50 6  7  8  9
4  5  6 100 8  9  10
5  6  7  8 -9  10 11
6  7  8  9  10 11 12
7  8 900 10 11 12 0
</code>```

Definitions:

The "central number" is defined as the number that has the same amount of numbers to the left,right,up and down

In this case its middlemost 100

The "outer shell" is the collection of numbers which their x and y index is or 0 or the matrix size

```<code>1  2  3  4  5  6  7
2                 8
3                 9
4                 10
5                 11
6                 12
7  8 900 10 11 12 0
</code>```

Your task:

Add to the central number the sum of each row and column after multiplying the values in each by their 1-based index

A single row for example

```<code>4  5  6  7  8
</code>```

for each number

```<code>number * index + number * index.....

4*1 + 5*2 + 6*3 + 7*4 + 8*5 => 100
</code>```

example:

```<code> 2 -3 -9  4  7  1  5  => 61
-2  0 -2 -7 -7 -7 -4  => -141
 6 -3 -2 -2 -3  2  1  => -10
 8 -8  4  1 -8  2  0  => -20
-5  6  7 -1  8  4  8  => 144
 1  5  7  8  7 -9 -5  => 10
 7  7 -2  2 -7 -8  0  => -60
                         |
78 65 60 45 -15 -89 10   => 154
                     |
                     => -16
</code>```

For all rows and columns you combine these values..

Now you sum these too => 154-16 = 138

You add that number to the "central number" and remove the "outer shell" of the matrix

```<code> 0 -2 -7 -7 -7     => -88
-3 -2 -2 -3  2     => -15
-8  4 1+138 -8  2  => 395
 6  7 -1  8  4     => 69
 5  7  8  7 -9     => 26

19 69 442 30 -26
</code>```

do this untill you end up with a single number

```<code>-2 -2 -3     => -15
 4  1060 -8  => 2100
 7 -1  8     => 29

27 2115 5
</code>```

Add 2114+2147 to 1060

Remove the "outer shell" and get 5321

Now we have a single number left

this is the output!

test cases:

```<code>-6

-6
</code>```

```<code>-7 -1  8
-4 -6  7
-3 -6  6

2
</code>```

```<code> 6  7 -2  5  1
-2  6 -4 -2  3
-1 -4  0 -2 -7
 0  1  4 -4  8
-8 -6 -5  0  2

-365
</code>```

```<code> 8  3  5  6  6 -7  5
 6  2  4 -2 -1  8  3
 2  1 -5  3  8  2 -3
 3 -1  0  7 -6  7 -5
 0 -8 -4 -9 -4  2 -8
 8 -9 -3  5  7  8  5
 8 -1  4  5  1 -4  8

17611
</code>```

```<code>-9 -7  2  1  1 -2  3 -7 -3  6  7  1  0
-7 -8 -9 -2  7 -2  5  4  7 -7  8 -9  8
-4  4 -1  0  1  5 -3  7  1 -2 -9  4  8
 4  8  1 -1  0  7  4  6 -9  3 -9  3 -9
-6 -8 -4 -8 -9  2  1  1 -8  8  2  6 -4
-8 -5  1  1  2 -9  3  7  2  5 -6 -1  2
-8 -5 -7 -4 -9 -2  5  0  2 -4  2  0 -2
-3 -6 -3  2 -9  8  1 -5  5  0 -4 -1 -9
-9 -9 -8  0 -5 -7  1 -2  1 -4 -1  5  7
-6 -9  4 -2  8  7 -9 -5  3 -1  1  8  4
-6  6 -3 -4  3  5  6  8 -2  5 -1 -7 -9
-1  7 -9  4  6  7  6 -8  5  1  0 -3  0
-3 -2  5 -4  0  0  0 -1  7  4 -9 -4  2

-28473770
</code>```

This is a codegolf challenge so the program with the lowest bytecount wins

Body:
C#, 257 bytes

here is a non esolang answer

void f(int[][]p){while(p.Length>1){int a=p.Length;int r=0;for(int i=0;i<a;i++)for(int j=0;j<a;j++)r+=(i+j+2)*p[i][j];p[a/2][a/2]+=r;p=p.Where((i,n)=>n>0&&n<p.Length-1).Select(k=>k.Where((i,n)=>n>0&&n<p.Length-1).ToArray()).ToArray();}Console.Write(p[0][0]);

ungolfed:

void f(int[][]p)
    {
        while (p.Length>1)
        {
            int a=p.Length;
            int r=0; //integer for number to add to middle
            for (int i = 0; i < a; i++)
                for (int j = 0; j < a; j++)
                    r +=(i+j+2)*p[i][j]; //add each element to counter according to their 1 based index
            p[a / 2][a / 2] += r; //add counter to middle
            p = p.Where((i, n) => n > 0 && n < p.Length - 1).Select(k => k.Where((i, n) => n > 0 && n < p.Length - 1).ToArray()).ToArray(); //strip outer shell from array
        }
        Console.Write(p[0][0]); //print last and only value in array
    }


答:
Brachylog, 114 bytes

```<code>{l1,?hh.|:{:Im:I:?:{[L:I:M]h:JmN,Ll:2/D(IJ,M{$\:?c:{:{:ImN,I:1+:N*.}f+.}a+.}:N+.;'(DIJ),N.)}f.}f:7a$\:7a&.}.
brbr.
</code>```

I'm suprised this even works to be honest. At least I realized that Brachylog really needs a "change value of that element" as a built-in though…

Usage example:

```<code>?- run_from_file('code.brachylog', '[[0:_2:_7:_7:_7]:[_3:_2:_2:_3:2]:[_8:4:139:_8:2]:[6:7:_1:8:4]:[5:7:8:7:_9]]', Z).
Z = 5321 .
</code>```

Explanation

More readable (and longer) version:

```<code>{l1,?hh.|:2f:7a$\:7a&.}.
:Im:I:?:3f.
[L:I:M]h:JmN,Ll:2/D(IJ,M:4&:N+.;'(DIJ),N.)
$\:?c:5a+.
:6f+.
:ImN,I:1+:N*.
brbr.
</code>```

I'm just gonna explain roughly what each predicate (i.e each line except the first one which is Main Predicate + predicate 1) does:

Main predicate + predicate 1 {l1,?hh.|:2f:7a$\:7a&.}. : If the input has only one row, then end the algorithm and return the only value. Else find all rows which satisfy predicate 2, then apply predicate 7 on the resulting matrix, then predicate 7 on the transposition, then call recursively.

Predicate 2 :Im:I:?:3f. :Take the Ith row of the matrix, find all values of that row which satisfy predicate 3 with I and the matrix as additional inputs.

Predicate 3 [L:I:M]h:JmN,Ll:2/D(IJ,M:4&:N+.;'(DIJ),N.) : L is the row, I is the index of the row, M is the matrix. N is the Jth element of L. If the length of L divided by 2 is equal to both I and J, then the output is the sum of N with the result of predicate 4 on the matrix. Otherwise the output is just N. This predicate essentialy recreates the matrix with the exception that the center element gets added to the sum.

Predicate 4 $\:?c:5a+. : Apply predicate 5 on each row and column of the matrix, unify the output with the sum of the results.

Predicate 5 :6f+. : Find all valid outputs of predicate 6 on the row, unify the output with the sum of the resulting list.

Predicate 6 :ImN,I:1+:N*. : N is the Ith value of the row, unify the output with N * (I+1).

Predicate 7 brbr. : Remove the first and last row of the matrix.

Title: Index sum and strip my matrix

Body:
Brachylog, 114 bytes

{l1,?hh.|:{:Im:I:?:{[L:I:M]h:JmN,Ll:2/D(IJ,M{$\:?c:{:{:ImN,I:1+:N*.}f+.}a+.}:N+.;'(DIJ),N.)}f.}f:7a$\:7a&.}.
brbr.

I'm suprised this even works to be honest. At least I realized that Brachylog really needs a "change value of that element" as a built-in though…

Usage example:

?- run_from_file('code.brachylog', '[[0:_2:_7:_7:_7]:[_3:_2:_2:_3:2]:[_8:4:139:_8:2]:[6:7:_1:8:4]:[5:7:8:7:_9]]', Z).
Z = 5321 .

Explanation

More readable (and longer) version:

{l1,?hh.|:2f:7a$\:7a&.}.
:Im:I:?:3f.
[L:I:M]h:JmN,Ll:2/D(IJ,M:4&:N+.;'(DIJ),N.)
$\:?c:5a+.
:6f+.
:ImN,I:1+:N*.
brbr.

I'm just gonna explain roughly what each predicate (i.e each line except the first one which is Main Predicate + predicate 1) does:

Main predicate + predicate 1 {l1,?hh.|:2f:7a$\:7a&.}. : If the input has only one row, then end the algorithm and return the only value. Else find all rows which satisfy predicate 2, then apply predicate 7 on the resulting matrix, then predicate 7 on the transposition, then call recursively.

Predicate 2 :Im:I:?:3f. :Take the Ith row of the matrix, find all values of that row which satisfy predicate 3 with I and the matrix as additional inputs.

Predicate 3 [L:I:M]h:JmN,Ll:2/D(IJ,M:4&:N+.;'(DIJ),N.) : L is the row, I is the index of the row, M is the matrix. N is the Jth element of L. If the length of L divided by 2 is equal to both I and J, then the output is the sum of N with the result of predicate 4 on the matrix. Otherwise the output is just N. This predicate essentialy recreates the matrix with the exception that the center element gets added to the sum.

Predicate 4 $\:?c:5a+. : Apply predicate 5 on each row and column of the matrix, unify the output with the sum of the results.

Predicate 5 :6f+. : Find all valid outputs of predicate 6 on the row, unify the output with the sum of the resulting list.

Predicate 6 :ImN,I:1+:N*. : N is the Ith value of the row, unify the output with N * (I+1).

Predicate 7 brbr. : Remove the first and last row of the matrix.


问:
Rube Goldberg Hello World
For this golf, you will need to use more than one language.

The task

A Rube Goldberg machine is a contraption that takes an enormous number of complicated steps in order to execute a very simple task. The goal of this golf is to output Rube Goldberg... but not directly.

The machine

Your "machine" is the source code that, once executed, will give another source code in another language that will output Rube Goldberg upon execution. Got it?

I rephrase: your initial code must give another code, that other code must output Rube Goldberg. Both codes must be written in different languages.

The bonus which is more like the only fun way to do it

There is a bonus if your code outputs a code that will output a code that will ... that will output Rube Goldberg.

NOTE: any sort of output can be used (stdout, stderr, dialog box, ...)

The points

The number of points is equal to the number of bytes used in your code, divided by the number of distinct, extra languages that you used.

NOTE: different languages use different encodings. The number of bytes is counted in the initial language with its own encoding.

Examples

Pyth -> J -> Javascript -> output in 30 bytes = 30/2 = 15 points (J and Javascript are the extra languages)

Java -> C# -> C++ -> PHP -> output in 36 bytes = 36/3 = 12 points (More bytes and more languages can win over fewer bytes and fewer languages (I know there is no way that these languages do it in 36 bytes))

C -> output in 10 bytes = 10/0 = Infinity points (No extra languages)

Python -> Perl -> Ruby -> Python -> Ruby in 44 bytes = 44/2 = 22 points (Perl and Ruby are the extra languages, the second Python is not counted as it is not an extra language, the second Ruby is not counted as it has already been used)

NOTE: Languages that output their input can't be used. That would be an extra language with absolutely no additional bytes.

The answer

Please provide an answer that clearly states which languages you used and shows us the code at each step (i.e.: in each language).

The winner

Of course, like usual, the lowest score wins.

NOTE: As usual, standard loopholes and "cheats" are not allowed.

答:
Sprects → /// → itflabtijtslwi → Python 2 → Pyth, 24 / 4 = 6

Sprects

```<code>$print'"Rube Goldberg'\/
</code>```

///

```<code>print'"Rube Goldberg'\/
</code>```

itflabtijtslwi

```<code>print'"Rube Goldberg'/
</code>```

Python 2

```<code>print'"Rube Goldberg'
</code>```

Pyth

```<code>"Rube Goldberg
</code>```

Output

```<code>Rube Goldberg
</code>```

Title: Rube Goldberg Hello World

Body:
Sprects → /// → itflabtijtslwi → Python 2 → Pyth, 24 / 4 = 6

Sprects

$print'"Rube Goldberg'\/

///

print'"Rube Goldberg'\/

itflabtijtslwi

print'"Rube Goldberg'/

Python 2

print'"Rube Goldberg'

Pyth

"Rube Goldberg

Output

Rube Goldberg


问:
Exploded substrings

Introduction

Let's observe the string abc. The substrings that can be made from this are:

```<code>a, ab, abc, b, bc, c
</code>```

We now need to align them under the initial string, like this:

```<code>abc
a
 b
  c
ab
 bc
abc
</code>```

The order of the string doesn't matter, so this is also perfectly valid:

```<code>abc
a
ab
abc
 b
 bc
  c
</code>```

So, the substring is positioned under the location of the substring in the initial string. So for abcdef and the substring cde, it would look like this:

```<code>abcdef
  cde
</code>```

The Task

The task is to align all substrings with a length greater than 0, like shown above. You can assume that the string itself will only contain alphabetic characters and has at least 1 character. For the padding, you can use a space or some other non-alphabetic printable ASCII character (32 - 127). Maybe not necessary to mention, but the string itself will only contain unique characters, so not like aba, since the a occurs twice.

Test cases

Input: abcde

Possible output:

```<code>a
ab
abc
abcd
abcde
 b
 bc
 bcd
 bcde
  c
  cd
  cde
   d
   de
    e
</code>```

Input: abcdefghij

Possible output:

```<code>a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
 b
 bc
 bcd
 bcde
 bcdef
 bcdefg
 bcdefgh
 bcdefghi
 bcdefghij
  c
  cd
  cde
  cdef
  cdefg
  cdefgh
  cdefghi
  cdefghij
   d
   de
   def
   defg
   defgh
   defghi
   defghij
    e
    ef
    efg
    efgh
    efghi
    efghij
     f
     fg
     fgh
     fghi
     fghij
      g
      gh
      ghi
      ghij
       h
       hi
       hij
        i
        ij
         j
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
Python 2 (Ungolfed) 99 Bytes

```<code>t=raw_input()
l=len(t)
for j in range(l):
 for i in range(l):
  if i>=j:print j*' '+t[j:i+1]
</code>```

Result:

```<code>>>python codegolf.py
abc
a
ab
abc
 b
 bc
  c

>>python codegolf.py
abcdef
a
ab
abc
abcd
abcde
abcdef
 b
 bc
 bcd
 bcde
 bcdef
  c
  cd
  cde
  cdef
   d
   de
   def
    e
    ef
     f

>>python codegolf.py
lmnopqrst
l
lm
lmn
lmno
lmnop
lmnopq
lmnopqr
lmnopqrs
lmnopqrst
 m
 mn
 mno
 mnop
 mnopq
 mnopqr
 mnopqrs
 mnopqrst
  n
  no
  nop
  nopq
  nopqr
  nopqrs
  nopqrst
   o
   op
   opq
   opqr
   opqrs
   opqrst
    p
    pq
    pqr
    pqrs
    pqrst
     q
     qr
     qrs
     qrst
      r
      rs
      rst
       s
       st
        t
</code>```

Title: Exploded substrings

Body:
Python 2 (Ungolfed) 99 Bytes

t=raw_input()
l=len(t)
for j in range(l):
 for i in range(l):
  if i>=j:print j*' '+t[j:i+1]

Result:

>>python codegolf.py
abc
a
ab
abc
 b
 bc
  c

>>python codegolf.py
abcdef
a
ab
abc
abcd
abcde
abcdef
 b
 bc
 bcd
 bcde
 bcdef
  c
  cd
  cde
  cdef
   d
   de
   def
    e
    ef
     f

>>python codegolf.py
lmnopqrst
l
lm
lmn
lmno
lmnop
lmnopq
lmnopqr
lmnopqrs
lmnopqrst
 m
 mn
 mno
 mnop
 mnopq
 mnopqr
 mnopqrs
 mnopqrst
  n
  no
  nop
  nopq
  nopqr
  nopqrs
  nopqrst
   o
   op
   opq
   opqr
   opqrs
   opqrst
    p
    pq
    pqr
    pqrs
    pqrst
     q
     qr
     qrs
     qrst
      r
      rs
      rst
       s
       st
        t


答:
TSQL, 88 bytes

Using ISO8601 format for date(yyyy-mm-dd)

```<code>DECLARE @ date='2050-05-02',@t date='2060-12-12'

a:IF stuff(reverse(@),3,1,'')=stuff(@,8,1,'')PRINT @
SET @=dateadd(d,1,@)IF @<=@t GOTO a
</code>```

Fiddle

Title: Forecast Palindromic Dates

Body:
Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:

02/02/2020

12/02/2021

03/02/2030

The Challenge

Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (edit: including the range itself).

Rules

To qualify as a palindrome, only the numeric characters of the date should be
checked.

The date can be in any common format (MM/DD/YYYY, DD-MM-YYYY), as
long as it uses two digits for both the month and day and four for
the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (/, -, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer.

If there are more than one dates returned, they should be comma or
new-line separated.

Shortest answer wins!

Example

```<code>date_palindrome('05/02/2050', '12/12/2060')
>>>['05/02/2050', '06/02/2060']
</code>```

Body:
TSQL, 88 bytes

Using ISO8601 format for date(yyyy-mm-dd)

DECLARE @ date='2050-05-02',@t date='2060-12-12'

a:IF stuff(reverse(@),3,1,'')=stuff(@,8,1,'')PRINT @
SET @=dateadd(d,1,@)IF @<=@t GOTO a

Fiddle


答:
PHP, <s>92</s> 57 bytes

On second thought you can do this with much less faffing around:

```<code><?php for(;$a=strlen(mb_substr($argv[1],$i++,1));)echo$a;
</code>```

Try it online note that this is slightly longer as it uses stdin rather than a program argument.

This version requires you to ignore notices sent to stderr but that's fine.

old version:

Uses a rather different approach to the other php answer.
Relies on the lack of native support for multi-byte strings in php.

```<code><?php for($l=strlen($a=$argv[1]);$a=mb_substr($a,1);$l=$v)echo$l-($v=strlen($a));echo$l?:'';
</code>```

Title: Bytes/Character

Body:
PHP, <s>92</s> 57 bytes

On second thought you can do this with much less faffing around:

<?php for(;$a=strlen(mb_substr($argv[1],$i++,1));)echo$a;

Try it online note that this is slightly longer as it uses stdin rather than a program argument.

This version requires you to ignore notices sent to stderr but that's fine.

old version:

Uses a rather different approach to the other php answer.
Relies on the lack of native support for multi-byte strings in php.

<?php for($l=strlen($a=$argv[1]);$a=mb_substr($a,1);$l=$v)echo$l-($v=strlen($a));echo$l?:'';


问:
Play scrabble with the periodic table
You've got a set of tiles with the symbols from the periodic table. Each symbol appears once. You're thinking up words to make but you want to know if it's possible or not.

The Challenge

Write a program in your favourite language that will take in a string as an input parameter. You may assume that input is not null, has no spaces and consists of ASCII characters.

Your program should take that string and output a truthy value if that word can made up of symbols from the periodic table of elements, and a falsey value if the word cannot.

To make this challenge more difficult, you may not use a symbol twice. So if you use Nitrogen N you may not use N again in the same word.

Rules

Standard loopholes are not allowed. You may use symbols from elements 1-118 (Hydrogen to Ununoctium). You can find a list of all the elements here. You may read the list of symbols in from a file or input arguments if you wish.

Test Cases:

```<code>Laos - true (LaOs)
Amputation - true (AmPuTaTiON)
Heinous - true (HeINoUS)
Hypothalamus - true (HYPoThAlAmUS)
Singapore - true (SiNGaPoRe)
Brainfuck - true (BRaInFUCK)
Candycane - false
</code>```

This is a code golf challenge, shortest code wins.

BEFORE YOU CLOSE AS DUPLICATE: While this may seem similar to this challenge, I feel it is different because it is not 'Generate a list of all words that are possible from the periodic table', it is 'Take in arbitrary input and determine if it can be made from the periodic table'

答:
Pyth, 11 bytes

```<code>s}RySQSM./z
</code>```

Try it online. Test suite.

Written on my phone, but should work. Very slow for a large number of elements or a long string.

Explanation

Take all partitions (./) of the input (z).

Sort (S) each partition (M).

For each partition (R), see if it is in (}) the list of all subsets (y) of the sorted (S) periodic table given as input (Q).

Sum (s) the resulting list of booleans.

Title: Play scrabble with the periodic table

Body:
Pyth, 11 bytes

s}RySQSM./z

Try it online. Test suite.

Written on my phone, but should work. Very slow for a large number of elements or a long string.

Explanation

Take all partitions (./) of the input (z).

Sort (S) each partition (M).

For each partition (R), see if it is in (}) the list of all subsets (y) of the sorted (S) periodic table given as input (Q).

Sum (s) the resulting list of booleans.


问:
When does (x == x+2)?
The challenge: Define x in such a way that the expression (x == x+2) would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming int is 32bit 2's complement) is OK.

Simple - should be small, use basic language features.

Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. Update: Avoiding the preprocessor is interesting.

Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

The C preprocessor. #define x 2|0 was suggested, but there are many other possibilities.

Floating point. Large numbers, infinity or NaN all work.

Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:

Operator overloading - A + that doesn't add or a == that always returns true.

Making x a function call (some languages allow it without the x() syntax). Then it can return something else each time.

A one-bit data type. Then x == x+2 (mod 2).

Changing 2 - some language let you assign 0 to it.

答:
C (GCC at least)

Using pointer arithmetic on an struct of size 0

```<code>#include <stdio.h>
typedef struct {} empty;

main(){
    empty *x;
    printf("%d\n", x==x+2);
}
</code>```

Title: When does (x == x+2)?

Body:
C (GCC at least)

Using pointer arithmetic on an struct of size 0

#include <stdio.h>
typedef struct {} empty;

main(){
    empty *x;
    printf("%d\n", x==x+2);
}


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Pascal

Factoid : Pascal programming language is a very old programming language
which is invented in 1970 (2 years older than C) by Professor Niklaus Wirth .
Original Pascal is procedural .

Because of its easy syntax and perfect efficiency , many programs have been made using Pascal . some examples are :TeX - Apple Lisa - Total Commender - Skype

Major Implementations are : Gnu Pascal - Free Pascal - Turbo Pascal - Borland Pascal

Length 1 snippet :

.
```
<p>This is a dot ! Any pascal program must end with "." even if it is possible to be terminated in the middle . This dot is usually written after an <code>end</code> .
To terminate the program somewhere at the middle of execution , you need to use <code>halt</code> command</p>
<pre class="lang-pascal prettyprint-override"><code>;
</code>```

This is not a snippet  , I've just mentioned it for its importance . this is an empty statement . It is so important to use it in right place . You must put this at the end of almost "every" command . but there are some execptions too . for example :

...
IF (x<=y) THEN HALT
...
```
<p>is different from :</p>
<pre class="lang-pascal prettyprint-override"><code>...
IF (x<=y) THEN HALT ;
...
</code>```

We'll see this difference later .

Length 3 snippet :

END
```
<p>This is a reserved word in Pascal . Pascal is a block-structured language - like C - which means a program is separated to blocks , and each block may be separated to some smaller blocks and so on . each block contains some statements . In Pascal , Blocks start with <code>BEGIN</code> and end with <code>END</code> (like <code>{</code> and <code>}</code> in C) .
Main program is ended with <code>END.</code> and all the sub-programs (like functions , programmer-made procedure etc) are ended with <code>END;</code>.</p>
<hr />
<h2>Length 7 snippet:</h2>
<pre class="lang-pascal prettyprint-override"><code>PROGRAM
</code>```

Sorry for the delay, fans! So, this is a PROGRAM! Every program must start with PROGRAM <name>;, where <name> is your program's name. Every program must have a "main block", which is a part of code between BEGIN & END which is not related to any other parts of code (e.g. it's not a function's definition) & program's execution starts from there.

Title: Showcase of Languages

Body:
Pascal

Factoid : Pascal programming language is a very old programming language
which is invented in 1970 (2 years older than C) by Professor Niklaus Wirth .
Original Pascal is procedural .

Because of its easy syntax and perfect efficiency , many programs have been made using Pascal . some examples are :TeX - Apple Lisa - Total Commender - Skype

Major Implementations are : Gnu Pascal - Free Pascal - Turbo Pascal - Borland Pascal

Length 1 snippet :

.

This is a dot ! Any pascal program must end with "." even if it is possible to be terminated in the middle . This dot is usually written after an end .
To terminate the program somewhere at the middle of execution , you need to use halt command

;

This is not a snippet  , I've just mentioned it for its importance . this is an empty statement . It is so important to use it in right place . You must put this at the end of almost "every" command . but there are some execptions too . for example :

...
IF (x<=y) THEN HALT
...

is different from :

...
IF (x<=y) THEN HALT ;
...

We'll see this difference later .

Length 3 snippet :

END

This is a reserved word in Pascal . Pascal is a block-structured language - like C - which means a program is separated to blocks , and each block may be separated to some smaller blocks and so on . each block contains some statements . In Pascal , Blocks start with BEGIN and end with END (like { and } in C) .
Main program is ended with END. and all the sub-programs (like functions , programmer-made procedure etc) are ended with END;.

Length 7 snippet:

PROGRAM

Sorry for the delay, fans! So, this is a PROGRAM! Every program must start with PROGRAM <name>;, where <name> is your program's name. Every program must have a "main block", which is a part of code between BEGIN & END which is not related to any other parts of code (e.g. it's not a function's definition) & program's execution starts from there.


答:
APL, 56 chars

```<code>{{1 1↓¯1 ¯1↓⍵+(-⍴⍵)↑(⌈.5×⍴⍵)↑+/(⍵⍪⍉⍵)+.×⍳≢⍵}⍣(⌊.5×≢⍵)⊣⍵}
</code>```

In English:

⍣(⌊.5×≢⍵) repeat "half the size of a dimension rounded"-times

(⍵⍪⍉⍵)+.×⍳≢⍵ inner product of the matrix and its transpose with the index vector

(-⍴⍵)↑(⌈.5×⍴⍵)↑ transform result in matrix padded with 0s

1 1↓¯1 ¯1↓ removes outer shell

Title: Index sum and strip my matrix

Body:
APL, 56 chars

{{1 1↓¯1 ¯1↓⍵+(-⍴⍵)↑(⌈.5×⍴⍵)↑+/(⍵⍪⍉⍵)+.×⍳≢⍵}⍣(⌊.5×≢⍵)⊣⍵}

In English:

⍣(⌊.5×≢⍵) repeat "half the size of a dimension rounded"-times

(⍵⍪⍉⍵)+.×⍳≢⍵ inner product of the matrix and its transpose with the index vector

(-⍴⍵)↑(⌈.5×⍴⍵)↑ transform result in matrix padded with 0s

1 1↓¯1 ¯1↓ removes outer shell


问:
Smallest groups in an array

Introduction

Let's observe the following array:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
</code>```

A group consists of the same digits next to each other. In the above array, there are 5 different groups:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]

 1, 1, 1
          2, 2
                1, 1, 1, 1
                            2, 2, 2
                                     1, 1, 1
</code>```

The smallest group of these is [2, 2], so we output [2, 2].

Let's take another example:

```<code>[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]

 3, 3, 3
          4, 4, 4, 4
                      5, 5
                            4, 4
                                  3, 3
                                        4, 4
</code>```

You can see that there are multiple groups with the same length. The smallest groups are:

```<code>[3, 3], [4, 4], [4, 4] and [5, 5].
</code>```

So we just output [3, 3], [4, 4], [4, 4], [5, 5] in any reasonable format. You may output these in any order.

The Task

Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.

Test cases

```<code>Input: [1, 1, 2, 2, 3, 3, 4]
Output: [4]

Input: [1]
Output: [1]

Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
APL, 25 chars

```<code>{z/⍨(⊢=⌊/)≢¨z←(1,2≠/⍵)⊂⍵}
</code>```

In English:

put in z the argument split where a number is different than the one preceding;

compute the length of each subarray

compare the minimum with each of the lengths producing a boolean...

... that is used to reduce z

Title: Smallest groups in an array

Body:
APL, 25 chars

{z/⍨(⊢=⌊/)≢¨z←(1,2≠/⍵)⊂⍵}

In English:

put in z the argument split where a number is different than the one preceding;

compute the length of each subarray

compare the minimum with each of the lengths producing a boolean...

... that is used to reduce z