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

```

答:
Fuzzy Octo Guacamole, 21 bytes

```<code>^-!.1C[d2ss.p*.+]s.Zm
</code>```

Outputs 0 for false, 1 for true.  Thanks to @xnor for the algorithm.

Explanation:

```<code>^-!.1C[d2ss.p*.+]s.Zm
^                      # Get Input
 -                     # Decrement
  !                    # Set for-loop counter
   .                   # Swap stacks
    1C                 # Set both stacks to [1].  (push 1 and copy to other stack)
      [         ]      # For loop for duration of input - 1
       d2              # Duplicate the top of stack and push 2 after
         ss            # Put them on the other stack, in reverse order.
           .           # Switches stacks
            p          # Power function. x^y (ToS^2)
             *         # Multiply
              .+       # Move back to the other stack and increment
                ]      # (repeat)
                 s.    # Move the ToS over and go with it
                   Z   # Reverse the stack.
                    m  # Modulus, x%y.
                       # (implicit output)
</code>```

We start with each stack having 1.  Let the bottom of one stack be n, the other bottom be P.  We multiply P by n^2, and then increment n. Do this n-1 times.  Then take P%n.

Title: Is this number a prime?

Body:
Fuzzy Octo Guacamole, 21 bytes

^-!.1C[d2ss.p*.+]s.Zm

Outputs 0 for false, 1 for true.  Thanks to @xnor for the algorithm.

Explanation:

^-!.1C[d2ss.p*.+]s.Zm
^                      # Get Input
 -                     # Decrement
  !                    # Set for-loop counter
   .                   # Swap stacks
    1C                 # Set both stacks to [1].  (push 1 and copy to other stack)
      [         ]      # For loop for duration of input - 1
       d2              # Duplicate the top of stack and push 2 after
         ss            # Put them on the other stack, in reverse order.
           .           # Switches stacks
            p          # Power function. x^y (ToS^2)
             *         # Multiply
              .+       # Move back to the other stack and increment
                ]      # (repeat)
                 s.    # Move the ToS over and go with it
                   Z   # Reverse the stack.
                    m  # Modulus, x%y.
                       # (implicit output)

We start with each stack having 1.  Let the bottom of one stack be n, the other bottom be P.  We multiply P by n^2, and then increment n. Do this n-1 times.  Then take P%n.


问:
Symme-Try This Triangle Trial
A string whose length is a positive triangular number (1, 3, 6, 10, 15...) can be arranged into an "equilateral text triangle" by adding some spaces and newlines (and keeping it in the same reading order).

For example, the length 10 string ABCDEFGHIJ becomes:

```<code>   A
  B C
 D E F
G H I J
</code>```

Write a program or function that takes in such a string, except it will only contains the characters 0 and 1. (You may assume the input is valid.)

For the resulting "equilateral text triangle", output (print or return) one of four numbers that denotes the type of symmetry exhibited:

Output 2 if the triangle has bilateral symmetry. i.e. it has a line of symmetry from any one corner to the opposite side's midpoint.

Examples:

```<code> 0
1 1

 1
0 1

  0
 0 1
0 1 0

   1
  1 1
 1 0 1
0 1 1 1
</code>```

Output 3 if the triangle has rotational symmetry. i.e. it could be rotated 120° with no visual change.

Examples:

```<code>   0
  1 0
 0 1 1
0 1 0 0

   0
  0 1
 1 0 0
0 0 1 0

    1
   0 1
  1 1 1
 1 1 1 0
1 0 1 1 1

     1
    0 1
   0 0 1
  1 0 0 0
 1 0 0 0 0
1 0 0 1 1 1
</code>```

Output 6 if the triangle has both bilateral and rotational symmetry. i.e. it matches the conditions for outputting both 2 and 3.

Examples:

```<code>0

1

 0
0 0

  1
 0 0
1 0 1

   0
  0 0
 0 1 0
0 0 0 0
</code>```

Output 1 if the triangle has neither bilateral nor rotational symmetry.

Examples:

```<code>  1
 1 0
0 0 0

  0
 0 1
1 0 1

   1
  1 0
 1 1 1
1 1 1 1

    1
   1 1
  1 1 1
 0 0 0 1
1 1 1 1 1
</code>```

The shortest code in bytes wins. Tiebreaker is earlier answer.

Aside from an optional trailing newline, the input string may not have space/newline padding or structure - it should be plain 0's and 1's.

If desired you may use any two distinct printable ASCII characters in place of 0 and 1.

Test Cases

Taken direct from examples.

```<code>011 -> 2
101 -> 2
001010 -> 2
1111010111 -> 2
0100110100 -> 3
0011000010 -> 3
101111111010111 -> 3
101001100010000100111 -> 3
0 -> 6
1 -> 6
000 -> 6
100101 -> 6
0000100000 -> 6
110000 -> 1
001101 -> 1
1101111111 -> 1
111111000111111 -> 1
</code>```

"Rotating" any input by 120° will of course result in the same output.

答:
CJam, <s>37</s> <s>29</s> <s>28</s> 27 bytes

Thanks to Sp3000 for saving 3 bytes.

```<code>q{T):T/(\s}h]{z_Wf%_}3*])e=
</code>```

Test suite.

This reuses some triangle rotation tricks from this challenge.

This also works for the same byte count:

```<code>q{T):T/(\s}h]3{;z_Wf%_}%)e=
</code>```

Explanation

First, a quick recap from the triangle post I linked to above. We represent a triangle as a 2D (ragged) list, e.g.

```<code>[[0 1 1]
 [0 0]
 [0]]
</code>```

The symmetry group of the triangle has 6 elements. There are cycles of length 3 by rotating the triangle and cycles of 2 by mirroring it along some axis. Conveniently, the rotations correspond to perform to two different reflections. We will use the following reflections to do this:

Transpose the list means reflecting it along the main diagonal, so we'd get:

```<code>[[0 0 0]
 [1 0]
 [1]]
</code>```

Reversing each row represents a reflection which swaps the top two corners. Applying this to the result of the transposition we get:

```<code>[[0 0 0]
 [0 1]
 [1]]
</code>```

Using these two transformations, and keeping the intermediate result, we can generate all six symmetries of the input.

A further point of note is the behaviour of transposition on a list like this:

```<code>[[0]
 [1 0]
 [1 0 0]
 []]
</code>```

Because that's what we'll end up with after splitting up the input. Conveniently, after transposing, CJam flushes all lines to the left, which means this actually gets rid of the extraneous [] and brings it into a form that's useful for the above two transformations (all without changing the actual layout of the triangle beyond reflectional symmetry):

```<code>[[0 1 1]
 [0 0]
 [0]]
</code>```

With that out of the way, here's the code:

```<code>q       e# Read input.
{       e# While the input string isn't empty yet...
  T):T  e#   Increment T (initially 0) and store it back in T.
  /     e#   Split input into chunks of that size.
  (     e#   Pull off the first chunk.
  \s    e#   Swap with remaining chunks and join them back together
        e#   into a single string.
}h
]       e# The stack now has chunks of increasing length and an empty string
        e# as I mentioned above. Wrap all of that in an array.
{       e# Execute this block 3 times...
  z_    e#   Transpose and duplicate. Remember that on the first iteration
        e#   this gets us a triangle of the desired form and on subsequent
        e#   iterations it adds one additional symmetry to the stack.
  Wf%_  e#   Reverse each row and duplicate.
}3*
        e# The stack now has all 6 symmetries as well as a copy of the
        e# last symmetry.
]       e# Wrap all of them in a list.
)       e# Pull off the copy of the last symmetry.
e=      e# Count how often it appears in the list of symmetries.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Symme-Try This Triangle Trial

Body:
CJam, <s>37</s> <s>29</s> <s>28</s> 27 bytes

Thanks to Sp3000 for saving 3 bytes.

q{T):T/(\s}h]{z_Wf%_}3*])e=

<a href="http://cjam.aditsu.net/#code=qN%2F%7B%22%20%22%2F0%3D%3AQ%3B0%3AT%3B%0A%0AQ%7BT)%3AT%2F(%5Cs%7Dh%5D%7Bz_Wf%25_%7D3*%5D)e%3D%0A%0A%5DoNo%7D%2F&input=011%20-%3E%202%0A101%20-%3E%202%0A001010%20-%3E%202%0A1111010111%20-%3E%202%0A0100110100%20-%3E%203%0A0011000010%20-%3E%203%0A101111111010111%20-%3E%203%0A101001100010000100111%20-%3E%203%0A0%20-%3E%206%0A1%20-%3E%206%0A000%20-%3E%206%0A100101%20-%3E%206%0A0000100000%20-%3E%206%0A110000%20-%3E%201%0A001101%20-%3E%201%0A1101111111%20-%3E%201%0A111111000111111%20-%3E%201" rel="nofollow noreferrer">Test suite.

This reuses some triangle rotation tricks from this challenge.

This also works for the same byte count:

q{T):T/(\s}h]3{;z_Wf%_}%)e=

Explanation

First, a quick recap from the triangle post I linked to above. We represent a triangle as a 2D (ragged) list, e.g.

[[0 1 1]
 [0 0]
 [0]]

The symmetry group of the triangle has 6 elements. There are cycles of length 3 by rotating the triangle and cycles of 2 by mirroring it along some axis. Conveniently, the rotations correspond to perform to two different reflections. We will use the following reflections to do this:

Transpose the list means reflecting it along the main diagonal, so we'd get:

[[0 0 0]
 [1 0]
 [1]]

Reversing each row represents a reflection which swaps the top two corners. Applying this to the result of the transposition we get:

[[0 0 0]
 [0 1]
 [1]]

Using these two transformations, and keeping the intermediate result, we can generate all six symmetries of the input.

A further point of note is the behaviour of transposition on a list like this:

[[0]
 [1 0]
 [1 0 0]
 []]

Because that's what we'll end up with after splitting up the input. Conveniently, after transposing, CJam flushes all lines to the left, which means this actually gets rid of the extraneous [] and brings it into a form that's useful for the above two transformations (all without changing the actual layout of the triangle beyond reflectional symmetry):

[[0 1 1]
 [0 0]
 [0]]

With that out of the way, here's the code:

q       e# Read input.
{       e# While the input string isn't empty yet...
  T):T  e#   Increment T (initially 0) and store it back in T.
  /     e#   Split input into chunks of that size.
  (     e#   Pull off the first chunk.
  \s    e#   Swap with remaining chunks and join them back together
        e#   into a single string.
}h
]       e# The stack now has chunks of increasing length and an empty string
        e# as I mentioned above. Wrap all of that in an array.
{       e# Execute this block 3 times...
  z_    e#   Transpose and duplicate. Remember that on the first iteration
        e#   this gets us a triangle of the desired form and on subsequent
        e#   iterations it adds one additional symmetry to the stack.
  Wf%_  e#   Reverse each row and duplicate.
}3*
        e# The stack now has all 6 symmetries as well as a copy of the
        e# last symmetry.
]       e# Wrap all of them in a list.
)       e# Pull off the copy of the last symmetry.
e=      e# Count how often it appears in the list of symmetries.


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

答:
QBasic, 75 bytes

```<code>INPUT s$
FOR i=1TO LEN(s$)
FOR j=1TO i
LOCATE,j
?MID$(s$,j,i+1-j)
NEXT
NEXT
</code>```

The basic double-FOR-loop strategy, modified a bit for QBasic's 1-based indexing. The main trick is LOCATE,j, which moves the cursor over to column j of the current line before printing. Since column 1 is the first column, this is equivalent to printing j-1 leading spaces.

Title: Exploded substrings

Body:
QBasic, 75 bytes

INPUT s$
FOR i=1TO LEN(s$)
FOR j=1TO i
LOCATE,j
?MID$(s$,j,i+1-j)
NEXT
NEXT

The basic double-FOR-loop strategy, modified a bit for QBasic's 1-based indexing. The main trick is LOCATE,j, which moves the cursor over to column j of the current line before printing. Since column 1 is the first column, this is equivalent to printing j-1 leading spaces.


答:
Perl, <s>32</s> <s>28</s> 24 bytes

Includes +1 for -n

Code:

```<code>/.+(??{say$"x"@-".$&})/
</code>```

Run with the string on STDIN:

```<code>perl -nE '/.+(??{say$"x"@-".$&})/' <<< abcd
</code>```

The golfing languages are so close and yet so far away...

Explanation

/.+/ matches a substring. Unfortunately it stops once it matched one. So I use the runtime regex construct (??{}) to extend the regex so it fails and backtracking will try the following substring, in the end trying them all before giving up in disgust.

Inside the (??{}) I print the current substring prefixed by as many spaces as the offset of the substring using $"x"@-"

So the output neatly documents how regex backtracking works:

```<code>abcd
abc
ab
a
 bcd
 bc
 b
  cd
  c
   d
</code>```

Title: Exploded substrings

Body:
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!

Body:
Perl, <s>32</s> <s>28</s> 24 bytes

Includes +1 for -n

Code:

/.+(??{say$"x"@-".$&})/

Run with the string on STDIN:

perl -nE '/.+(??{say$"x"@-".$&})/' <<< abcd

The golfing languages are so close and yet so far away...

Explanation

/.+/ matches a substring. Unfortunately it stops once it matched one. So I use the runtime regex construct (??{}) to extend the regex so it fails and backtracking will try the following substring, in the end trying them all before giving up in disgust.

Inside the (??{}) I print the current substring prefixed by as many spaces as the offset of the substring using $"x"@-"

So the output neatly documents how regex backtracking works:

abcd
abc
ab
a
 bcd
 bc
 b
  cd
  c
   d


问:
QWERTY Quine Creation

Challenge

Create a quine, that instead of outputting it's source, output's it's source QWERTY-sorted.

What is QWERTY sorting?

QWERTY sorting is sorting code by the QWERTY keyboard. Anything higher or more left is greater (q > Q, \ > /) with presedence on higher. To check, find the locations of the two characters to compare. Find which character occurs first in the following table (left to right, up to down). The first character is the smaller one.

```<code>qwertyuiop[]\
asdfghjkl;'
zxcvbnm,./
QWERTYUIOP{}|
ASDFGHJKL:"
ZXCVBNM<>?
1234567890-=!@#$%^&*()_+~`
</code>```

(there is a trailing space and linefeed)

Examples:

```<code>Code Golf -> eoodflGC
Programming -> rroiagnmmP
</code>```

(note trailing space on Code Golf)

Specifications

Only characters in the above list are allowed in the source code!

This is code-golf.

Only Proper Quines are allowed (adapted to QWERTY sort).

Output must be in increasing QWERTY order.

答:
CJam, <s>25</s> 23 bytes

```<code>{`"_~"+{"#$_+~`"`#}$}_~
</code>```

Thanks to @MartinBüttner for golfing off 2 bytes!

Try it online!

How it works

```<code>{                   }_~  Define, copy and execute a code block.

   `                       Create a string representation of the code block.
  "_~"+                    Append that string.
       {          }$       Sort the characters by the following:
        "#$_+~`"`#           Compute the 0-based index of the character in that
                             string. Returns -1 if not found.
                           Since `$' is stable, all characters with tied index -1
                           will appear at the beginning, in their original order.
                           This places {{}} at the beginning, followed by
                           """"##$$___++~~~```.
```

Title: QWERTY Quine Creation

Body:
CJam, <s>25</s> 23 bytes

{`"_~"+{"#$_+~`"`#}$}_~

Thanks to @MartinBüttner for golfing off 2 bytes!

Try it online!

How it works

{                   }_~  Define, copy and execute a code block.

   `                       Create a string representation of the code block.
  "_~"+                    Append that string.
       {          }$       Sort the characters by the following:
        "#$_+~`"`#           Compute the 0-based index of the character in that
                             string. Returns -1 if not found.
                           Since `$' is stable, all characters with tied index -1
                           will appear at the beginning, in their original order.
                           This places {{}} at the beginning, followed by
                           """"##$$___++~~~```.


问:
How compatible are my strings?

Introduction

Consider two strings A and B of the same length L, and an integer K ≥ 0.
For the purposes of this challenge, we say that the strings are K-compatible, if there exists a string C of length K such that A is a contiguous substring of the concatenation BCB.
Note that A is a substring of BAB, so A and B are always L-compatible (but may also be K-compatible for some other K < L).

Input

Your inputs are two strings of the same positive length, consisting of upper- and lowercase ASCII letters.

Output

Your output shall be the lowest non-negative integer K such that the inputs are K-compatible.

Example

Consider the inputs

```<code>A = HHHHHH
B = HHttHH
</code>```

They are not 0-compatible, because A is not a substring of HHttHHHHttHH.
They are also not 1-compatible, because A is not a substring of HHttHH#HHttHH no matter which letter is placed on the #.
However, A is a substring of HHttHHHHHHttHH, where C is the two-letter string HH.
Thus the inputs are 2-compatible, and the correct output is 2.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

The compatibility condition is symmetric, so swapping the two inputs should not change the output.

```<code>E G -> 1
E E -> 0
aB Bc -> 1
YY tY -> 1
abcd bcda -> 0
abcXd bxcda -> 4
Hello Hello -> 0
Hello olHel -> 1
aBaXYa aXYaBa -> 1
aXYaBa aBaXYa -> 1
HHHHHH HHttHH -> 2
abcdab cdabcd -> 2
XRRXXXXR XRXXRXXR -> 4
evveeetev tetevevev -> 7
vzzvzJvJJz vJJvzJJvJz -> 10
JJfcfJJcfJfb JcfJfbbJJJfJ -> 5
GhhaaHHbbhGGH HHaaHHbbGGGhh -> 9
OyDGqyDGDOGOGyG yDGqOGqDyyyyOyD -> 12
ffKKBBpGfGKpfGpbKb fGpbKbpBBBffbbbffK -> 9
UZuPPZuPdVdtuDdDiuddUPtUidtVVV dtUPtUidtVVVtDZbZZPuiUZuPPZuPd -> 21
</code>```

Leaderboard

Here's a Stack Snippet to generate a leaderboard and list of winners by language.
To make sure your answer shows up, start it with a header of the form

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

You can keep old scores in the header by using the strikethrough tags: <s>57</s> will appear as <s>57</s>.

/* Configuration */

var QUESTION_ID = 78736; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 32014; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (! /<a/.test(lang)) lang = '' + lang + '';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Pyth, 16

```<code>lhf}QjT,vzvz+k.:
</code>```

Find the shortest substring of A that when inserted between two copies of B results in a string that contains A.

This could be two bytes shorter if the second line didn't have quotes, but that feels weird?

Test Suite

Title: How compatible are my strings?

Body:
Pyth, 16

lhf}QjT,vzvz+k.:

Find the shortest substring of A that when inserted between two copies of B results in a string that contains A.

This could be two bytes shorter if the second line didn't have quotes, but that feels weird?

<a href="http://pyth.herokuapp.com/?code=lhf%7DQjT%2Cvzvz%2Bk.%3A&input=%22ffKKBBpGfGKpfGpbKb%22%0A%22fGpbKbpBBBffbbbffK%22&test_suite=1&test_suite_input=%22E%22%0A%22G%22%0A%22E%22%0A%22E%22%0A%22aB%22%0A%22Bc%22%0A%22YY%22%0A%22tY%22%0A%22abcd%22%0A%22bcda%22%0A%22abcXd%22%0A%22bxcda%22%0A%22Hello%22%0A%22Hello%22%0A%22Hello%22%0A%22olHel%22%0A%22HHHHHH%22%0A%22HHttHH%22%0A%22XRRXXXXR%22%0A%22XRXXRXXR%22%0A%22evveeetev%22%0A%22tetevevev%22%0A%22vzzvzJvJJz%22%0A%22vJJvzJJvJz%22%0A%22JJfcfJJcfJfb%22%0A%22JcfJfbbJJJfJ%22%0A%22GhhaaHHbbhGGH%22%0A%22HHaaHHbbGGGhh%22%0A%22OyDGqyDGDOGOGyG%22%0A%22yDGqOGqDyyyyOyD%22%0A%22ffKKBBpGfGKpfGpbKb%22%0A%22fGpbKbpBBBffbbbffK%22%0A%22UZuPPZuPdVdtuDdDiuddUPtUidtVVV%22%0A%22dtUPtUidtVVVtDZbZZPuiUZuPPZuPd%22&debug=0&input_size=2">Test Suite


答:
05AB1E, 20 bytes

Code:

```<code>õ)²Œ«v¹y¹««²åiyg}})ß
</code>```

Uses CP-1252 encoding. Try it online!.

Title: How compatible are my strings?

Body:
Introduction

Consider two strings A and B of the same length L, and an integer K ≥ 0.
For the purposes of this challenge, we say that the strings are K-compatible, if there exists a string C of length K such that A is a contiguous substring of the concatenation BCB.
Note that A is a substring of BAB, so A and B are always L-compatible (but may also be K-compatible for some other K < L).

Input

Your inputs are two strings of the same positive length, consisting of upper- and lowercase ASCII letters.

Output

Your output shall be the lowest non-negative integer K such that the inputs are K-compatible.

Example

Consider the inputs

```<code>A = HHHHHH
B = HHttHH
</code>```

They are not 0-compatible, because A is not a substring of HHttHHHHttHH.
They are also not 1-compatible, because A is not a substring of HHttHH#HHttHH no matter which letter is placed on the #.
However, A is a substring of HHttHHHHHHttHH, where C is the two-letter string HH.
Thus the inputs are 2-compatible, and the correct output is 2.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

The compatibility condition is symmetric, so swapping the two inputs should not change the output.

```<code>E G -> 1
E E -> 0
aB Bc -> 1
YY tY -> 1
abcd bcda -> 0
abcXd bxcda -> 4
Hello Hello -> 0
Hello olHel -> 1
aBaXYa aXYaBa -> 1
aXYaBa aBaXYa -> 1
HHHHHH HHttHH -> 2
abcdab cdabcd -> 2
XRRXXXXR XRXXRXXR -> 4
evveeetev tetevevev -> 7
vzzvzJvJJz vJJvzJJvJz -> 10
JJfcfJJcfJfb JcfJfbbJJJfJ -> 5
GhhaaHHbbhGGH HHaaHHbbGGGhh -> 9
OyDGqyDGDOGOGyG yDGqOGqDyyyyOyD -> 12
ffKKBBpGfGKpfGpbKb fGpbKbpBBBffbbbffK -> 9
UZuPPZuPdVdtuDdDiuddUPtUidtVVV dtUPtUidtVVVtDZbZZPuiUZuPPZuPd -> 21
</code>```

Leaderboard

Here's a Stack Snippet to generate a leaderboard and list of winners by language.
To make sure your answer shows up, start it with a header of the form

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

You can keep old scores in the header by using the strikethrough tags: <s>57</s> will appear as <s>57</s>.

/* Configuration */

var QUESTION_ID = 78736; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 32014; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (! /<a/.test(lang)) lang = '' + lang + '';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
05AB1E, 20 bytes

Code:

õ)²Œ«v¹y¹««²åiyg}})ß

Uses CP-1252 encoding. Try it online!.


答:
J, <s>32 29</s> 28 bytes

```<code>(-@{.@i.|.])"1 a:>@-.~&,<\\.
</code>```

This evaluates to a monadic verb. Try it here. Usage:

```<code>   f =: (-@{.@i.|.])"1 a:>@-.~&,<\\.
   f 'abe'
a
ab
abe
 b
 be
  e
</code>```

Explanation

As some other answers, I compute the index of occurrence of the first character of each substring.
The substrings are stored in a matrix with trailing spaces, so I rotate them to the right by their index to get the right amount of padding.
That one piece of whitespace between "1 and a: is really annoying...

```<code>(-@{.@i.|.])"1 a:>@-.~&,<\\.  Input is y
                        <\\.  Compute suffixes of prefixes of y, and put them in boxes.
                              This gives a 2D array of substrings in boxes.
                      &,      Flatten the array of boxes,
               a:  -.~        remove all empty strings, and
                 >@           open each box. This places the strings in a 2D matrix of
                              characters, with trailing spaces to make it rectangular.
(          )"1                Do this for each line x in the matrix:
      i.                        The index of every character of x in y.
 -@{.@                          Take the first one and negate it.
        |.]                     Rotate x to the left by that amount.
                                Since we negated the index, this rotates to the right.
</code>```

Title: Exploded substrings

Body:
J, <s>32 29</s> 28 bytes

(-@{.@i.|.])"1 a:>@-.~&,<\\.

This evaluates to a monadic verb. Try it here. Usage:

   f =: (-@{.@i.|.])"1 a:>@-.~&,<\\.
   f 'abe'
a
ab
abe
 b
 be
  e

Explanation

As some other answers, I compute the index of occurrence of the first character of each substring.
The substrings are stored in a matrix with trailing spaces, so I rotate them to the right by their index to get the right amount of padding.
That one piece of whitespace between "1 and a: is really annoying...

(-@{.@i.|.])"1 a:>@-.~&,<\\.  Input is y
                        <\\.  Compute suffixes of prefixes of y, and put them in boxes.
                              This gives a 2D array of substrings in boxes.
                      &,      Flatten the array of boxes,
               a:  -.~        remove all empty strings, and
                 >@           open each box. This places the strings in a 2D matrix of
                              characters, with trailing spaces to make it rectangular.
(          )"1                Do this for each line x in the matrix:
      i.                        The index of every character of x in y.
 -@{.@                          Take the first one and negate it.
        |.]                     Rotate x to the left by that amount.
                                Since we negated the index, this rotates to the right.


答:
Retina, 49 bytes

```<code>.*?(?<=^(?=(.*)(?<4-3>.)*(.*) \2.*\1$)(.)*).+
$#4
</code>```

Try it online! (Slightly modified to run all tests at once.)

The trick is that we need to backtrack over the part of A that we don't find in B, and so far I haven't found a way to do this without rather annoying lookarounds and balancing groups.

Title: How compatible are my strings?

Body:
Retina, 49 bytes

.*?(?<=^(?=(.*)(?<4-3>.)*(.*) \2.*\1$)(.)*).+
$#4

<a href="http://retina.tryitonline.net/#code=JShHYAouKj8oPzw9Xig_PSguKikoPzw0LTM-LikqKC4qKSBcMi4qXDEkKSguKSopLisKJCM0&input=RSBHCkUgRQphQiBCYwpZWSB0WQphYmNkIGJjZGEKYWJjWGQgYnhjZGEKSGVsbG8gSGVsbG8KSGVsbG8gb2xIZWwKYUJhWFlhIGFYWWFCYQpISEhISEggSEh0dEhIClhSUlhYWFhSIFhSWFhSWFhSCmV2dmVlZXRldiB0ZXRldmV2ZXYKdnp6dnpKdkpKeiB2Skp2ekpKdkp6CkpKZmNmSkpjZkpmYiBKY2ZKZmJiSkpKZkoKR2hoYWFISGJiaEdHSCBISGFhSEhiYkdHR2hoCk95REdxeURHRE9HT0d5RyB5REdxT0dxRHl5eXlPeUQKZmZLS0JCcEdmR0twZkdwYktiIGZHcGJLYnBCQkJmZmJiYmZmSwpVWnVQUFp1UGRWZHR1RGREaXVkZFVQdFVpZHRWVlYgZHRVUHRVaWR0VlZWdERaYlpaUHVpVVp1UFBadVBk" rel="nofollow">Try it online! (Slightly modified to run all tests at once.)

The trick is that we need to backtrack over the part of A that we don't find in B, and so far I haven't found a way to do this without rather annoying lookarounds and balancing groups.


问:
List of primes under a million
This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.

The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.

The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective.

答:
Sage, 28 bytes

for i in primes(1e6):print i
```

Try it online

Title: List of primes under a million

Body:
Sage, 28 bytes

for i in primes(1e6):print i

Try it online


答:
Sage, 22 bytes

lambda N:N in Primes()
```

Try it online

Title: Is this number a prime?

Body:
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

```

Body:
Sage, 22 bytes

lambda N:N in Primes()

Try it online


答:
Python 3, <s>155</s> <s>168</s> 157 bytes

Total is the length of A. Compare the beginning of A to the end of B and subtract that from total. Compare the beginning of B to the end of A and subtract that from total. Return the absolute value of total unless total is equal to the length, in which case return 0.

```<code>def f(A,B):
    T=L=len(A)
    C=D=1
    for i in range(L,0,-1):
        if A[:i]==B[-i:]and C:
            T,C=T-i,0
        if A[-i:]==B[:i]and D:
            T,D=T-i,0
    return (0,abs(T))[T!=-L]
</code>```

Edit: Handle the f("abcdab","cdabcd")==2 case

Title: How compatible are my strings?

Body:
Python 3, <s>155</s> <s>168</s> 157 bytes

Total is the length of A. Compare the beginning of A to the end of B and subtract that from total. Compare the beginning of B to the end of A and subtract that from total. Return the absolute value of total unless total is equal to the length, in which case return 0.

def f(A,B):
    T=L=len(A)
    C=D=1
    for i in range(L,0,-1):
        if A[:i]==B[-i:]and C:
            T,C=T-i,0
        if A[-i:]==B[:i]and D:
            T,D=T-i,0
    return (0,abs(T))[T!=-L]

Edit: Handle the f("abcdab","cdabcd")==2 case


答:
Pyke, 15 bytes

```<code>QlFUQRd:DlRF2h<
</code>```

Try it here!

Assumes array of padded strings is acceptable

Pads first and then chops.

Title: Exploded substrings

Body:
Pyke, 15 bytes

QlFUQRd:DlRF2h<

Try it here!

Assumes array of padded strings is acceptable

Pads first and then chops.


问:
The Back-and-Forth Sequence
Imagine a path made up of < and > and ending in a @, e.g.

```<code>><>@
</code>```

A walker starts on the left-most cell. He will traverse the path as follows:

If the walker is on a @ cell, he's reached the goal and is done.

If the walker is on a > cell, the entire path shifts one step to the right, cyclically, taking the walker with it.

If the walker is on a < cell, the entire path shifts one step to the left, cyclically, taking the walker with it.

Afterwards, the walker takes a single step. If he's at either end of the path, he moves away from the end. Otherwise he keeps moving in the direction he moved on the last step (ignoring the rotation), walking right initially.

Let's work through the above example. The walker's position is marked with ^:

```<code>><>@   --rotate-->  @><>
^                    ^
step right (first step):
@><>   --rotate-->  ><>@
  ^                  ^
step right:
><>@   --rotate-->  @><>
  ^                    ^
step left (dead end):
@><>   --rotate-->  ><>@
  ^                  ^
step left:
><>@   --rotate-->  @><>
^                    ^
step left:
@><>   Goal reached!
^
</code>```

The walker visited 6 cells in the process (including the starting cell as well as the @, and counting each cell as often as it's visited).

Here is a small example, where the walker is transported across the edges by a rotation:

```<code>>>@   --rotate-->  @>>
^                   ^
step right (first step):
@>>   --rotate-->  >@>
  ^                ^
step right (dead end):
>@>   Goal reached!
 ^
</code>```

This time the walker visited 3 cells.

We can easily turn this into an integer sequence:

You're given a positive integer N, e.g. 9.

You compute the the binary representation of this integer, e.g. 1001.

Then turn 1 into > and 0 into < and append a @: ><<>@.

We associate with N the number of cells visited by the walker in the number constructed this way.

The first few elements of the resulting sequence are:

```<code>2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6,
6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7
</code>```

This may seem quite arbitrary, but the resulting sequence actually turns out to have a lot of structure:

For reference, you can find the first 2048 numbers of the sequence in this pastebin.

The Challenge

You guessed it: you're to compute the above sequence. You can do that one of three ways:

You can produce an infinite sequence (while memory permits), either by continuously outputting (separated by non-numeric characters) values or by using some form of infinite generator in languages that support them. If you print an infinite stream to STDOUT, you don't have to print the numbers one by one, but make sure that every number would be printed after a finite amount of time (and in order). If you use this option, you should not take any input.

You can take an integer N as input and produce the Nth term of the sequence.

You can take an integer N as input and produce everything up to the Nth term of the sequence, either as a list or string using an unambiguous separator.

Since I don't want to penalise languages which can't easily convert between bases, instead of the integer N you may instead take the binary representation of N, using 0s and 1s as usual (as a list or string), with the most-significant bit first.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard code-golf rules apply.

Background

This actually computes the number of "ticks" a straight-forward interpreter of my esoteric programming language Labyrinth would need to interpret the "path" as source code. In that case, the "walker" is simply the instruction pointer (which has a position and a direction), the @ command terminates the program and < and > are source-code modification commands.

答:
Python, 122 119 113 110 108 107 103 bytes

```<code>def l(b):
 p=e=w=len(b);d=i=1
 while e:p+=1-2*b[w-e];d*=2*(1!=d-p>~w)-1;p-=d;e=(e-d)%-~w;i+=1
 return i
</code>```

Takes input as a list of binary digits. Helper function to test:

```<code>b = lambda n: [int(d) for d in bin(n)[2:]]
</code>```

Credit to Lynn for saving 7 bytes.

Title: The Back-and-Forth Sequence

Body:
Python, 122 119 113 110 108 107 103 bytes

def l(b):
 p=e=w=len(b);d=i=1
 while e:p+=1-2*b[w-e];d*=2*(1!=d-p>~w)-1;p-=d;e=(e-d)%-~w;i+=1
 return i

Takes input as a list of binary digits. Helper function to test:

b = lambda n: [int(d) for d in bin(n)[2:]]

Credit to Lynn for saving 7 bytes.


问:
Count how many characters are in the program's source
Write a program that counts and prints the number of characters in it's own source code to standard output.

The number must be generated from counting the characters.

This Ruby solution would not be allowed:

```<code>puts 6
</code>```

because it is not calculated. Spaces, tabs, new lines, etc should be counted.

The program must be smallest possible in any programming language.

答:
Python 3, <s>28</s> 27 bytes

I got 2̶8̶ 27 characters, plus file name and extension (4 in this case for 'f.py') The minimum value for this is 3̶2̶ 31, if there was a 1 letter file name and the .py exension:

```<code>print(len(open("f.py").read()))
</code>```

EDIT:
The bite count is actually 27 rather than 28, thanks @mbomb007 for pointing that out

Body:
Python 3, <s>28</s> 27 bytes

I got 2̶8̶ 27 characters, plus file name and extension (4 in this case for 'f.py') The minimum value for this is 3̶2̶ 31, if there was a 1 letter file name and the .py exension:

print(len(open("f.py").read()))

EDIT:
The bite count is actually 27 rather than 28, thanks @mbomb007 for pointing that out


答:
Javascript (pure - no HTML nor JQuery) 41 bytes

```<code>function f() {alert((f+"f()").length)}f()
</code>```

Title: Count how many characters are in the program's source

Body:
Write a program that counts and prints the number of characters in it's own source code to standard output.

The number must be generated from counting the characters.

This Ruby solution would not be allowed:

```<code>puts 6
</code>```

because it is not calculated. Spaces, tabs, new lines, etc should be counted.

The program must be smallest possible in any programming language.

Body:
Javascript (pure - no HTML nor JQuery) 41 bytes

function f() {alert((f+"f()").length)}f()


Title: The Back-and-Forth Sequence

Body:
Imagine a path made up of < and > and ending in a @, e.g.

```<code>><>@
</code>```

A walker starts on the left-most cell. He will traverse the path as follows:

If the walker is on a @ cell, he's reached the goal and is done.

If the walker is on a > cell, the entire path shifts one step to the right, cyclically, taking the walker with it.

If the walker is on a < cell, the entire path shifts one step to the left, cyclically, taking the walker with it.

Afterwards, the walker takes a single step. If he's at either end of the path, he moves away from the end. Otherwise he keeps moving in the direction he moved on the last step (ignoring the rotation), walking right initially.

Let's work through the above example. The walker's position is marked with ^:

```<code>><>@   --rotate-->  @><>
^                    ^
step right (first step):
@><>   --rotate-->  ><>@
  ^                  ^
step right:
><>@   --rotate-->  @><>
  ^                    ^
step left (dead end):
@><>   --rotate-->  ><>@
  ^                  ^
step left:
><>@   --rotate-->  @><>
^                    ^
step left:
@><>   Goal reached!
^
</code>```

The walker visited 6 cells in the process (including the starting cell as well as the @, and counting each cell as often as it's visited).

Here is a small example, where the walker is transported across the edges by a rotation:

```<code>>>@   --rotate-->  @>>
^                   ^
step right (first step):
@>>   --rotate-->  >@>
  ^                ^
step right (dead end):
>@>   Goal reached!
 ^
</code>```

This time the walker visited 3 cells.

We can easily turn this into an integer sequence:

You're given a positive integer N, e.g. 9.

You compute the the binary representation of this integer, e.g. 1001.

Then turn 1 into > and 0 into < and append a @: ><<>@.

We associate with N the number of cells visited by the walker in the number constructed this way.

The first few elements of the resulting sequence are:

```<code>2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6,
6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7
</code>```

This may seem quite arbitrary, but the resulting sequence actually turns out to have a lot of structure:

For reference, you can find the first 2048 numbers of the sequence in this pastebin.

The Challenge

You guessed it: you're to compute the above sequence. You can do that one of three ways:

You can produce an infinite sequence (while memory permits), either by continuously outputting (separated by non-numeric characters) values or by using some form of infinite generator in languages that support them. If you print an infinite stream to STDOUT, you don't have to print the numbers one by one, but make sure that every number would be printed after a finite amount of time (and in order). If you use this option, you should not take any input.

You can take an integer N as input and produce the Nth term of the sequence.

You can take an integer N as input and produce everything up to the Nth term of the sequence, either as a list or string using an unambiguous separator.

Since I don't want to penalise languages which can't easily convert between bases, instead of the integer N you may instead take the binary representation of N, using 0s and 1s as usual (as a list or string), with the most-significant bit first.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard code-golf rules apply.

Background

This actually computes the number of "ticks" a straight-forward interpreter of my esoteric programming language Labyrinth would need to interpret the "path" as source code. In that case, the "walker" is simply the instruction pointer (which has a position and a direction), the @ command terminates the program and < and > are source-code modification commands.

Body:
Matlab (score=230,n=inf)

function w(s,f),b=[];e=0;for i=s:f,a=dec2bin(i);c=find(a=='1');g=numel(a)+1;if numel(c)>=g/2;if mod(g,2)==1,fprintf('%d ',g);else,d=c(g/2);fprintf('%d ',2*d);end,else,fprintf('%d ',g);end,e=e+1;if(e==100),e=0;fprintf('\n');end;end

The function takes s as starting index and f as ending (type inf if you want to keep on to infinite).

The function can go forever without any remarkable time-lag between any two outputs type h=1000000000000000000000000000000000000000000000000000;w(h,h+1) to make sure.

The algorithm follows a mathematical approach that i will explain later, and it does confirm Martin's referenced list, basing on this program:

stored=[2, 3, 3, 4, 6, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 10, 6, 10, 8, 8, 6, 10, 8, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 14, 8, 8, 8, 14, 8, 14, 12, 12, 8, 8, 8, 14, 8, 14, 12, 12, 8, 14, 12, 12, 10, 10, 10, 10, 8, 8, 8, 14, 8, 14, 12, 12, 8, 14, 12, 12, 10, 10, 10, 10, 8, 14, 12, 12, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 18, 10, 10, 10, 18, 10, 18, 16, 16, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 18, 10, 18, 16, 16, 10, 18, 16, 16, 14, 14, 14, 14, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 18, 16, 16, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 22, 12, 12, 12, 22, 12, 22, 20, 20, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 22, 12, 22, 20, 20, 12, 22, 20, 20, 18, 18, 18, 18, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 22, 20, 20, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13];
b=[];for i=1:numel(stored)
a=dec2bin(i);
c=find(a=='1');
if numel(c)>=(numel(a)+1)/2
if mod(numel(a)+1,2)==1
b=[b numel(a)+1];
else
d=c((numel(a)+1)/2);
b=[b 2*d];
end
else
b=[b numel(a)+1];
end
end
for i=1:numel(stored)
if (b(i))
if b(i)~=stored(i)
'error',
end
end
end

Since the algorithm verifies 2048 first testcases, I will blindly assume it would for any test case, so my algorithm works regarding few properties i discovered in this process without the pain of shifting and moving pointer:

1- if the twice the number of 1's in binary translation doesnt exceed the length of the sequnce L so the output isL+1

2- if the sequence length is even and the previous condition isnt set so the output is same L+1

3- otherwise, the output is twice the L/2th index of 1.


问:
Compute the histogram entropy estimation of a string
Write a program or function that estimates the Shannon entropy of a given string.

If a string has n characters, d distinct characters, xi is the i th distinct character, and P(xi) is the probability of that character occuring in the string, then our Shannon entropy estimate for that string is given by:

For the estimation in this challenge we assume that the probability of a character occurring in a string is simply the number of times it occurs divided by the total number of characters.

Your answer must be accurate to at least 3 digits after the period.

Test cases:

```<code>"This is a test.", 45.094
"00001111", 8.000
"cwmfjordbankglyphsvextquiz", 122.211
"             ", 0.0
</code>```

答:
Factor, 98 bytes

```<code>[ [ length ] [ dup [ [ = ] curry dupd count ] { } map-as nip ] bi [ / log 2 log / ] with map sum ]
</code>```

This is a direct translation of this Python answer. I'll add an explanation over dinner.

Body:
Factor, 98 bytes

[ [ length ] [ dup [ [ = ] curry dupd count ] { } map-as nip ] bi [ / log 2 log / ] with map sum ]

This is a direct translation of this Python answer. I'll add an explanation over dinner.


答:
JavaScript (ES6), 110 bytes

```<code>(a,b)=>{for(i=0;;i++)for(j=i;j<=a.length;j++)if(b.startsWith(a.slice(j))&&b.endsWith(a.slice(0,j-i)))return i}
</code>```

Works by slicing ever longer pieces out of the middle of a until they match the two ends of b. The loop is not infinite as it will stop on or before i == a.length.

Title: How compatible are my strings?

Body:
JavaScript (ES6), 110 bytes

(a,b)=>{for(i=0;;i++)for(j=i;j<=a.length;j++)if(b.startsWith(a.slice(j))&&b.endsWith(a.slice(0,j-i)))return i}

Works by slicing ever longer pieces out of the middle of a until they match the two ends of b. The loop is not infinite as it will stop on or before i == a.length.


答:
Python, 57 bytes

f=lambda s,p='':set(s)and{p+s}|f(s[1:],' '+p)|f(s[:-1],p)
```

Outputs a set like {' b', 'a', 'ab'}. The idea is to recurse down two branched that cut off the first or last character. The gives redundant outputs, but the set automatically removes duplicates. For alignment, every time the first character is cut off, a space is added to the prefix p, which is concatenated onto the front.

Title: Exploded substrings

Body:
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!

Body:
Python, 57 bytes

f=lambda s,p='':set(s)and{p+s}|f(s[1:],' '+p)|f(s[:-1],p)

Outputs a set like {' b', 'a', 'ab'}. The idea is to recurse down two branched that cut off the first or last character. The gives redundant outputs, but the set automatically removes duplicates. For alignment, every time the first character is cut off, a space is added to the prefix p, which is concatenated onto the front.


答:
Python 2, 99 bytes

```<code>def l(b):l=len(b);return(l>=sum(b)*2or l%2<1)and-~l or[i+1for i,c in enumerate(b)if b[i]][l/2]*2
</code>```

Python port of Agawa001's brilliant answer.

Readable version:

```<code>def l(b):
    if len(b) >= 2*sum(b) or len(b)%2 == 0:
        return len(b) + 1

    return 2*[i+1 for i, c in enumerate(b) if b[i]][len(b)//2]
</code>```

Title: The Back-and-Forth Sequence

Body:
Python 2, 99 bytes

def l(b):l=len(b);return(l>=sum(b)*2or l%2<1)and-~l or[i+1for i,c in enumerate(b)if b[i]][l/2]*2

Python port of Agawa001's brilliant answer.

Readable version:

def l(b):
    if len(b) >= 2*sum(b) or len(b)%2 == 0:
        return len(b) + 1

    return 2*[i+1 for i, c in enumerate(b) if b[i]][len(b)//2]


答:
MATL, 20 bytes

```<code>XJZyXyi:"!J2$1!*s1$e
</code>```

Try it online!

Explanation

This avoids the matrix multiplication by doing it manually, using element-wise multiplication with broadcast followed by vectorized sum. Specifically, to multiply matrices M and N, both of size s×s:

Transpose M. Call the resulting matrix P.

Permute the dimensions of N such that N is "turned" with a rotation axis along the first dimension, giving an s×1×s 3D array, say Q.

Multiply each element of P times each element of Q, with implicit broadcast. This means that P is automatically replicated s times along the third dimension, and Q is replicated s times along the second, to make them both s×s×s, before the actual element-wise multiplication takes place.

Sum along the first dimension to yield a 1×s×s array.

Squeeze the leading singleton dimension out, to produce an s×s result.

Commented code:

```<code>XJ      % take matrix A. Copy to clipboard J
ZyXy    % generate identity matrix of the same size
i:      % take exponent n. Generate range [1 2 ... n] (possibly empty)
"       % for each element in that range
  !     %   transpose matrix with product accumulated up to now (this is step 1)
  J     %   paste A
  2$1!  %   permute dimensions: rotation along first-dimension axis (step 2)
  *     %   element-wise multiplication with broadcast (step 3)
  s     %   sum along first dimension (step 4)
  1$e   %   squeeze out singleton dimension, i.e. first dimension (step 5)
        % end for. Display
</code>```

Title: Find the Matrix Power

Body:
Problem

Create a program or function that can calculate the result of a matrix raised to the nth power. Your code will take an arbitrary square matrix A and a non-negative integer n, and return a matrix with the value An.

Restrictions

Built-in functions that compute the matrix power and matrix product are not allowed.

The rest of the standard rules for code-golf apply.

Explanation

Given a square matrix A, the value of An = A A ⋯ A (repeated matrix product of A with itself, n times). If n is positive, the standard just mentioned is used. When n is zero, the identity matrix with the same order of A is the result.

Goal

This is code-golf and the shortest code wins.

Test Cases

Here, A is the input matrix, n is the input integer, and r is the output matrix where r = An.

```<code>n = 0
A = 62 72
    10 34
r =  1  0
     0  1

n = 1
A = 23 61 47
    81 11 60
    42  9  0
r = 23 61 47
    81 11 60
    42  9  0

n = 2
A =  12  28 -26  3
     -3 -10 -13  0
     25  41   3 -4
    -20 -14  -4 29
r = -650 -1052  -766 227
    -331  -517   169  43
     332   469 -1158 -53
    -878  -990   574 797

n = 4
A = -42 -19  18 -38
    -33  26 -13  31
    -43  25 -48  28
     34 -26  19 -48
r = -14606833  3168904 -6745178  4491946
      1559282  3713073 -4130758  7251116
      8097114  5970846 -5242241 12543582
     -5844034 -4491274  4274336 -9196467

n = 5
A =  7  0 -3  8 -5  6 -6
     6  7  1  2  6 -3  2
     7  8  0  0 -8  5  2
     3  0  1  2  4 -3  4
     2  4 -1 -7 -4 -1 -8
    -3  8 -9 -2  7 -4 -8
    -4 -5 -1  0  5  5 -1
r =  39557  24398 -75256 131769  50575   14153  -7324
    182127  19109   3586 115176 -23305    9493 -44754
    146840  31906 -23476 190418 -38946   65494  26468
     42010 -21876  41060 -13950 -55148   19290   -406
     44130  34244 -35944  34272  22917  -39987 -54864
      1111  40810 -92324  35831 215711 -117849 -75038
    -70219   8803 -61496   6116  45247   50166   2109
</code>```

Body:
MATL, 20 bytes

XJZyXyi:"!J2$1!*s1$e

Try it online!

Explanation

This avoids the matrix multiplication by doing it manually, using element-wise multiplication with broadcast followed by vectorized sum. Specifically, to multiply matrices M and N, both of size s×s:

Transpose M. Call the resulting matrix P.

Permute the dimensions of N such that N is "turned" with a rotation axis along the first dimension, giving an s×1×s 3D array, say Q.

Multiply each element of P times each element of Q, with implicit broadcast. This means that P is automatically replicated s times along the third dimension, and Q is replicated s times along the second, to make them both s×s×s, before the actual element-wise multiplication takes place.

Sum along the first dimension to yield a 1×s×s array.

Squeeze the leading singleton dimension out, to produce an s×s result.

Commented code:

XJ      % take matrix A. Copy to clipboard J
ZyXy    % generate identity matrix of the same size
i:      % take exponent n. Generate range [1 2 ... n] (possibly empty)
"       % for each element in that range
  !     %   transpose matrix with product accumulated up to now (this is step 1)
  J     %   paste A
  2$1!  %   permute dimensions: rotation along first-dimension axis (step 2)
  *     %   element-wise multiplication with broadcast (step 3)
  s     %   sum along first dimension (step 4)
  1$e   %   squeeze out singleton dimension, i.e. first dimension (step 5)
        % end for. Display


答:
Jelly, <s>17</s> <s>16</s> 15 bytes

```<code>Z×'³S€€
LṬ€z0Ç¡
</code>```

Try it online!

Permalinks with grid output: test case 1 | test case 2 | test case 3 | test case 4 | test case 5

How it works

```<code>LṬ€z0Ç¡  Main link. Arguments: A (matrix), n (power)

L        Get the length l of A.
 Ṭ€      Turn each k in [1, ..., l] into a Boolean list [0, 0, ..., 1] of length k.
   z0    Zip; transpose the resulting 2D list, padding with 0 for rectangularity.
         This constructs the identity matrix of dimensions k×k.
     Ç¡  Execute the helper link n times.

Z×'³S€€  Helper link. Argument: B (matrix)

Z        Zip; transpose rows and columns of B.
   ³     Yield A.
 ×'      Spawned multiplication; element-wise mutiply each rows of zipped B (i.e.,
         each column of B) with each row of A.
         This is "backwards", but multiplication of powers of A is commutative.
    S€€  Compute the sum of each product of rows.
</code>```

Title: Find the Matrix Power

Body:
Jelly, <s>17</s> <s>16</s> 15 bytes

Z×'³S€€
LṬ€z0Ç¡

Try it online!

Permalinks with grid output: test case 1 | test case 2 | test case 3 | test case 4 | test case 5

How it works

LṬ€z0Ç¡  Main link. Arguments: A (matrix), n (power)

L        Get the length l of A.
 Ṭ€      Turn each k in [1, ..., l] into a Boolean list [0, 0, ..., 1] of length k.
   z0    Zip; transpose the resulting 2D list, padding with 0 for rectangularity.
         This constructs the identity matrix of dimensions k×k.
     Ç¡  Execute the helper link n times.

Z×'³S€€  Helper link. Argument: B (matrix)

Z        Zip; transpose rows and columns of B.
   ³     Yield A.
 ×'      Spawned multiplication; element-wise mutiply each rows of zipped B (i.e.,
         each column of B) with each row of A.
         This is "backwards", but multiplication of powers of A is commutative.
    S€€  Compute the sum of each product of rows.


问:
ECHO! Echo! echo. (echo)
Your challenge, should you choose to accept it, is simple:

Implement RFC 862, also known as the Echo Protocol:

The Echo protocol

An echo service simply sends back to the originating source any data it receives.

TCP Based Echo Service

One echo service is defined as a connection based application on TCP. A server listens for TCP connections on TCP port 7.  Once a connection is established any data received is sent back.  This continues until the calling user terminates the connection.

UDP Based Echo Service

Another echo service is defined as a datagram based application on UDP.  A server listens for UDP datagrams on UDP port 7.  When a datagram is received, the data from it is sent back in an answering datagram.

Scoring

The score is one point for every byte of code as encoded in UTF-8 or a language-specific code page, whichever is smaller.

If the program incompletely implements RFC 862 by providing only UDP or only TCP, the score is doubled.

If the program incorrectly implements RFC 862 by either using a port other than 7 or by dropping or transforming certain bytes due to language limitations or corner cutting, the score is quadrupled. (This stacks with the preceding point if applicable.)

If the program is invalid, the score is ω.

Rules

A valid program:

Does not use standard loopholes.

Per connection:

Accepts connections and receive incoming data.

Sends outgoing data in an amount that is always less than or equal to the amount of data received.

Does not invoke programs external to itself. (Spawning children to deal with multiple connections is fine, spinning up inetd or its local equivalent is not.)

Does not use library functions specifically designed to start and maintain an echo service.

This is code golf, so lowest score wins.

答:
Racket, 231

(thread(λ()(do([l(tcp-listen 7)])(#f)(let-values([(i o)(tcp-accept l)])(copy-port i o)))))((λ(s b)(udp-bind! s #f 7)(do()(#f)(let-values([(n h p)(udp-receive! s b)])(udp-send-to s h p b 0 n))))(udp-open-socket)(make-bytes 65535))
```

TCP and UDP.

The TCP echo server uses a handy Racket procedure named copy-port that copies ports in the background, managed by Racket, instead of by the programmer. That also means I don't have to spin off a thread for each client, only for the listener (so I can start the UDP listener on the main thread).

Title: ECHO! Echo! echo. (echo)

Body:
Racket, 231

(thread(λ()(do([l(tcp-listen 7)])(#f)(let-values([(i o)(tcp-accept l)])(copy-port i o)))))((λ(s b)(udp-bind! s #f 7)(do()(#f)(let-values([(n h p)(udp-receive! s b)])(udp-send-to s h p b 0 n))))(udp-open-socket)(make-bytes 65535))

TCP and UDP.

The TCP echo server uses a handy Racket procedure named copy-port that copies ports in the background, managed by Racket, instead of by the programmer. That also means I don't have to spin off a thread for each client, only for the listener (so I can start the UDP listener on the main thread).


问:
Correct using a Parity Block
For more information on Parity: Wikipedia

Challenge

Write a program that takes an input (stdin, argv, ect) of four nibbles and two parity nibbles. Your program should then test to see whether the 'block' is valid, using even parity; if it is then output 1. Then try to make any corrections, if correction is possible output the corrected block. If you cannot correct the block output -1. You can assume the parity nibbles are never corrupt.

To re-cap and clarify:

If the input is valid output 1.

If the input is invalid and fixable output the fixed block.

If the input is invalid and cannot be fixed output -1.

You can only edit bits if their respective row and column in the parity bit is incorrect.

Input Format:

```<code><NIBBLE> <NIBBLE> <NIBBLE> <NIBBLE> <PARITY-Y> <PARITY-X>
</code>```

So 1010 0111 1101 1011 1011 0111 Would look like:

Winning

This is code-golf: Smallest program wins.

Input and Output Examples

Input 1010 0111 1101 1011 1011 0111

Output 1

The Input is Valid

Input 1010 0011 1101 1011 1011 0111

Output 1010 0111 1101 1011

The Input was Invalid, but correctable

Input 1010 0001 1101 1011 1011 0111

Output -1
The Input was Invalid, and not correctable

答:
JavaScript (ES6), 234 bytes

```<code>s=>(a=s.split` `,[...a.pop()].map((c,i)=>a[i]+=c),x=y=0,[...a].map((s,i)=>[...s].map((c,j)=>{x^=c<<i;y^=c<<j})),x&=15,y&=15,a.pop(),x|y?x-(x&-x)|y-(y&-y)?-1:[...a].map((s,i)=>s.slice(0,4).replace(/./g,(c,j)=>c^x>>i&y>>j&1)).join` `:1)
</code>```

Save 21 bytes if an array of strings is an acceptable I/O format, or 46 bytes if a two-dimensional array of bits is acceptable. Explanation: The original string is split into blocks and then rearranged into an almost square formation:

```<code>DDDDX
DDEDX
DDDDX
DDDDX
YYYY
</code>```

The row and column parities are then calculated, each setting the appropriate bit in the x and y variables, so for instance if the error was in the bit marked E it would set x to 2 and y to 4. (If the parity of the parity blocks was also provided, then it could also be checked, and an error in the parity blocks or indeed the parity bit itself could be detected. The two parity blocks should have the same parity, of course.)

```<code>s=>(                    String parameter
 a=s.split` `,          Split it into blocks
 [...a.pop()]           Remove the X parity block and loop over it
  .map((c,i)=>a[i]+=c), Append the X parity bits to the data blocks
 x=y=0,                 Initialise the X and Y parity
 [...a].map((s,i)=>     Loop over rows
  [...s].map((c,j)=>     and columns
   {x^=c<<i;y^=c<<j})),   updating the parity
 x&=15,y&=15,           Only bits 0-3 are important
 a.pop(),               Remove the Y parity block
 x|y?                   If there were parity errors
  x-(x&-x)|y-(y&-y)?-1:  If there were several errors then return -1
   [...a].map((s,i)=>     If there was one error then loop over blocks
    s.slice(0,4)           Removing the X parity bit
     .replace(/./g,(c,j)=>  Loop over bits
      c^x>>i&y>>j&1))        Flip the bit if it was the incorrect bit
    .join` `:              Join the blocks together
   1)                    Return 1 if there were no parity errors
</code>```

Title: Correct using a Parity Block

Body:
JavaScript (ES6), 234 bytes

s=>(a=s.split` `,[...a.pop()].map((c,i)=>a[i]+=c),x=y=0,[...a].map((s,i)=>[...s].map((c,j)=>{x^=c<<i;y^=c<<j})),x&=15,y&=15,a.pop(),x|y?x-(x&-x)|y-(y&-y)?-1:[...a].map((s,i)=>s.slice(0,4).replace(/./g,(c,j)=>c^x>>i&y>>j&1)).join` `:1)

Save 21 bytes if an array of strings is an acceptable I/O format, or 46 bytes if a two-dimensional array of bits is acceptable. Explanation: The original string is split into blocks and then rearranged into an almost square formation:

DDDDX
DDEDX
DDDDX
DDDDX
YYYY

The row and column parities are then calculated, each setting the appropriate bit in the x and y variables, so for instance if the error was in the bit marked E it would set x to 2 and y to 4. (If the parity of the parity blocks was also provided, then it could also be checked, and an error in the parity blocks or indeed the parity bit itself could be detected. The two parity blocks should have the same parity, of course.)

s=>(                    String parameter
 a=s.split` `,          Split it into blocks
 [...a.pop()]           Remove the X parity block and loop over it
  .map((c,i)=>a[i]+=c), Append the X parity bits to the data blocks
 x=y=0,                 Initialise the X and Y parity
 [...a].map((s,i)=>     Loop over rows
  [...s].map((c,j)=>     and columns
   {x^=c<<i;y^=c<<j})),   updating the parity
 x&=15,y&=15,           Only bits 0-3 are important
 a.pop(),               Remove the Y parity block
 x|y?                   If there were parity errors
  x-(x&-x)|y-(y&-y)?-1:  If there were several errors then return -1
   [...a].map((s,i)=>     If there was one error then loop over blocks
    s.slice(0,4)           Removing the X parity bit
     .replace(/./g,(c,j)=>  Loop over bits
      c^x>>i&y>>j&1))        Flip the bit if it was the incorrect bit
    .join` `:              Join the blocks together
   1)                    Return 1 if there were no parity errors


问:
Self-Mutilating Program
Simply put, your goal is to create a complete program that modifies its own source code until every character of the source is different than what it started as.

Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc.

Rules

Your program must halt sometime after the modification is complete.

It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file.

Standard loopholes are disallowed.

Shortest program wins.

If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage.

Edit: If your program halts with errors, please specify it as such (and maybe say what the errors are.)

答:
Batch, 11 bytes

```<code>@echo>%0&&*
</code>```

Modifies source code to ECHO is on.

```<code>@           - don't echo the command.
 echo       - print ECHO is on.
     >%0    - write to own file.
        &&* - execute * command after the above is done, * doesn't exist so program halts.
</code>```

The @ is there so the command isn't echoed, but mostly so the two echos don't line up.

Title: Self-Mutilating Program

Body:
Batch, 11 bytes

@echo>%0&&*

Modifies source code to ECHO is on.

@           - don't echo the command.
 echo       - print ECHO is on.
     >%0    - write to own file.
        &&* - execute * command after the above is done, * doesn't exist so program halts.

The @ is there so the command isn't echoed, but mostly so the two echos don't line up.


答:
JavaScript (Node.js) 102 Bytes (51 * 2)

```<code>require("net").createServer(s=>s.pipe(s)).listen(7)
</code>```

You can add UDP for a total of 132 bytes, as seen below:

```<code>require("net").createServer(s=>s.pipe(s)).listen(7),(u=require("dgram").createSocket("udp4")).on("message",msg=>u.send(msg)).bind(7)
</code>```

Was tested on node.js v5.2.0

Make sure to run with sudo on Unix descendants (OS X, Linux, etc.)

Title: ECHO! Echo! echo. (echo)

Body:
Your challenge, should you choose to accept it, is simple:

Implement RFC 862, also known as the Echo Protocol:

The Echo protocol

An echo service simply sends back to the originating source any data it receives.

TCP Based Echo Service

One echo service is defined as a connection based application on TCP. A server listens for TCP connections on TCP port 7.  Once a connection is established any data received is sent back.  This continues until the calling user terminates the connection.

UDP Based Echo Service

Another echo service is defined as a datagram based application on UDP.  A server listens for UDP datagrams on UDP port 7.  When a datagram is received, the data from it is sent back in an answering datagram.

Scoring

The score is one point for every byte of code as encoded in UTF-8 or a language-specific code page, whichever is smaller.

If the program incompletely implements RFC 862 by providing only UDP or only TCP, the score is doubled.

If the program incorrectly implements RFC 862 by either using a port other than 7 or by dropping or transforming certain bytes due to language limitations or corner cutting, the score is quadrupled. (This stacks with the preceding point if applicable.)

If the program is invalid, the score is ω.

Rules

A valid program:

Does not use standard loopholes.

Per connection:

Accepts connections and receive incoming data.

Sends outgoing data in an amount that is always less than or equal to the amount of data received.

Does not invoke programs external to itself. (Spawning children to deal with multiple connections is fine, spinning up inetd or its local equivalent is not.)

Does not use library functions specifically designed to start and maintain an echo service.

This is code golf, so lowest score wins.

Body:
JavaScript (Node.js) 102 Bytes (51 * 2)

require("net").createServer(s=>s.pipe(s)).listen(7)

You can add UDP for a total of 132 bytes, as seen below:

require("net").createServer(s=>s.pipe(s)).listen(7),(u=require("dgram").createSocket("udp4")).on("message",msg=>u.send(msg)).bind(7)

Was tested on node.js v5.2.0

Make sure to run with sudo on Unix descendants (OS X, Linux, etc.)


答:
Jolf, 4 bytes, noncompeting

```<code>₯S₯C
</code>```

This ₯Sets the ₯Code element's value to the input, undefined as none is given. Try it here!

Title: Self-Mutilating Program

Body:
Simply put, your goal is to create a complete program that modifies its own source code until every character of the source is different than what it started as.

Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc.

Rules

Your program must halt sometime after the modification is complete.

It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file.

Standard loopholes are disallowed.

Shortest program wins.

If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage.

Edit: If your program halts with errors, please specify it as such (and maybe say what the errors are.)

Body:
Jolf, 4 bytes, noncompeting

₯S₯C

This ₯Sets the ₯Code element's value to the input, undefined as none is given. Try it here!