问:
Counting Eisenstein primes

Introduction

Eisenstein integers are complex numbers of the form

a+bω

Where a,b are integers, and

ω = e^(2πi/3)

The Eisenstein integers form a triangular lattice in the complex plane:

We say that an Eisenstein integer z=a+bω is prime if it cannot be written as the product of two non-unit (not 1,-1,ω,-ω,ω^2, or -ω^2) Eisenstein integers

Program

Input: A natural number n.

Output: The number of Eisenstein primes which are of the form a+bω for which a,b are natural numbers (including zero) less than or equal to n

Test Cases

0 → 0

1 → 0

2 → 5

3 → 9

4 → 13

5 → 20

Scoring

This is code-golf, so least amount of bytes wins

答:
Julia, <s>66</s> <s>62</s> 60 bytes

```<code>!n=sum(isprime,[a<1<b%3?b:a^2-a*b+b^2for a=[0;0;0:n],b=0:n])
</code>```

Try it online!

Explanation

We’re interested in the primes in this parallelogram on the complex plane (example for n = 4):

We can split them into primes on the green lines, and on the gray lines.

Wikipedia tells me an Eisenstein number z is a green line Eisenstein prime iff |z| is a natural prime equal to 2 mod 3.

It also says z is a gray line Eisenstein prime iff |z|² = a² − ab + b² is a natural prime.

So we loop over a = 0…n and b = 0…n, and check:

If (a = 0 or b = 0 or a = b) and max(a, b) % 3 = 2, then count whether max(a, b) is a prime.

Else, count whether a² − ab + b² is a prime.

However, we can abuse the distribution’s symmetry. Instead of counting each green line once, we can just count one green line thrice! That is, only check a = 0 and increment the counter by three when we find a green line prime. The a=[0;0;0:n] achieves exactly this.

Since we know we’re only considering the green line a = 0, we can replace max(a, b) by b.

The “green line condition” is nicely expressed in Julia using operator chaining: a<1<b%3.

(For the remaining green lines, we will never return a false positive: if a = b or b = 0 then a² − ab + b² = a², which can’t be prime.)

Ideas

Maybe, instead of writing a^2-a*b+b^2, I can conditionally replace the exponent at b by 1 when a<1<b%3 – then the expression reduces to b. This doesn’t seem to be shorter, but it’s neat!

Title: Counting Eisenstein primes

Body:
Julia, <s>66</s> <s>62</s> 60 bytes

!n=sum(isprime,[a<1<b%3?b:a^2-a*b+b^2for a=[0;0;0:n],b=0:n])

Try it online!

Explanation

We’re interested in the primes in this parallelogram on the complex plane (example for n = 4):

We can split them into primes on the green lines, and on the gray lines.

Wikipedia tells me an Eisenstein number z is a green line Eisenstein prime iff |z| is a natural prime equal to 2 mod 3.

It also says z is a gray line Eisenstein prime iff |z|² = a² − ab + b² is a natural prime.

So we loop over a = 0…n and b = 0…n, and check:

If (a = 0 or b = 0 or a = b) and max(a, b) % 3 = 2, then count whether max(a, b) is a prime.

Else, count whether a² − ab + b² is a prime.

However, we can abuse the distribution’s symmetry. Instead of counting each green line once, we can just count one green line thrice! That is, only check a = 0 and increment the counter by three when we find a green line prime. The a=[0;0;0:n] achieves exactly this.

Since we know we’re only considering the green line a = 0, we can replace max(a, b) by b.

The “green line condition” is nicely expressed in Julia using operator chaining: a<1<b%3.

(For the remaining green lines, we will never return a false positive: if a = b or b = 0 then a² − ab + b² = a², which can’t be prime.)

Ideas

Maybe, instead of writing a^2-a*b+b^2, I can conditionally replace the exponent at b by 1 when a<1<b%3 – then the expression reduces to b. This doesn’t seem to be shorter, but it’s neat!


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

答:
Python 2, 238 bytes + 20% = 285.6

# coding: utf-8
import codecs
with codecs.open(__file__,'r') as f:
    t = f.read()
n="utf-8" if t.startswith("# coding: ascii") else "ascii"
with codecs.open(__file__,'w', encoding=n) as f:
    f.write(t[0]+" coding: "+n+t[t.find("\n"):])
```

Basically, this toggles the current file encoding of the python source between ascii and utf-8, thus essentially changing every character of the source!

ContentLicense: CC BY-SA 3.0

Title: Self-Mutilating Program

Body:
Python 2, 238 bytes + 20% = 285.6

# coding: utf-8
import codecs
with codecs.open(__file__,'r') as f:
    t = f.read()
n="utf-8" if t.startswith("# coding: ascii") else "ascii"
with codecs.open(__file__,'w', encoding=n) as f:
    f.write(t[0]+" coding: "+n+t[t.find("\n"):])

Basically, this toggles the current file encoding of the python source between ascii and utf-8, thus essentially changing every character of the source!


问:
Write a program that reverses the name of its source file
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

答:
Python (2.7 or 3.4+), 61 49 bytes

I believe this is close to the optimal Python solution:

```<code>import os;a=__file__;os.rename(a,a[-4::-1]+".py")
</code>```

Inspired by s4b3r6's answer, but uses list slicing instead of reverse, and saves __file__ to a variable to save bytes when using it twice.

Note: This assumes that the filename is always *.py. A slightly more generic solution that can handle any two-character file extension would be to use a[-3:] to replace ".py", at the cost of 1 extra byte.

Update: Saved 12 bytes by using the list slicing trick a[-4::-1] to remove the file extension, instead of splitting and then reversing with a.split(".")[0][::-1].

Body:
Python (2.7 or 3.4+), 61 49 bytes

I believe this is close to the optimal Python solution:

import os;a=__file__;os.rename(a,a[-4::-1]+".py")

Inspired by s4b3r6's answer, but uses list slicing instead of reverse, and saves __file__ to a variable to save bytes when using it twice.

Note: This assumes that the filename is always *.py. A slightly more generic solution that can handle any two-character file extension would be to use a[-3:] to replace ".py", at the cost of 1 extra byte.

Update: Saved 12 bytes by using the list slicing trick a[-4::-1] to remove the file extension, instead of splitting and then reversing with a.split(".")[0][::-1].


问:
7-segment differences
I think most people around here know what a 7-segment display for digits is:

```<code> _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|
</code>```

We can define the 7-segment difference (7SD) between two digits to be the number of segments that need to be toggled to switch from one to the other. E.g. the 7SD between 1 and 2 is 5 (the three horizontal segments and the lower two vertical segments need to be toggled), and the 7SD between 6 and 8 is 1.

Furthermore, we can define the 7SD between two numbers to be the sum of 7SDs between their corresponding digits. If one number is longer than the other, we assume they are right-aligned and add the number of segments needed to display the additional most-significant digits of the larger number. As an example, consider the 7SD between 12345 and 549:

```<code>  x:  1 2 3 4 5
  y:      5 4 9
7SD:  2+5+2+0+1 = 10
</code>```

Your task is to compute 7SD between n and n+1, given n.

For convenience, here is the full table of 7SDs between individual digits. The row _ represents an empty position.

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

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

Input

Input is a single positive integer n.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument.

You may assume that the input is at most one less than the largest number which can be represented by your language's standard integer type, as long as that type supports at least values up to and including 127.

Output

You should print a single integer, the 7SD between n and n+1.

You may output via STDOUT (or closest alternative), function return value or function (out) argument.

Scoring

Standard code-golf rules apply, shortest code (in bytes) wins.

Test Cases

For some obscure reason, this sequence isn't in OEIS yet, although there is the closely related sequence A123587. Here are the first 100 numbers (starting with n = 1, 2, 3, ...):

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

The first input for which the 7SD is greater than 9 is 1999 which should yield 11. Here are some other larger examples:

```<code>n          7SD
1999        11
12345        1
999999      14
5699999     15
8765210248   1
</code>```

答:
Python, 50 48 bytes

```<code>f=lambda n:26523308-0**n*2>>n%10*3&7or f(n/10)+2
</code>```

Explanation

This function operates on the least significant digit of the number n, summing the 7SD of the digits when incremented by one until after the first non-9 digit.

26523308 is a bitmask that encodes the mapping for the digits 0-8. When n=0, which only occurs when n comprises only 9s, the answer will be off by two. This is compensated by the expression 0**n*2. As for the digit 9, the bitmask evaluates to zero which will trigger the recursive call while adding 2 to the 7SD.

Title: 7-segment differences

Body:
Python, 50 48 bytes

f=lambda n:26523308-0**n*2>>n%10*3&7or f(n/10)+2

Explanation

This function operates on the least significant digit of the number n, summing the 7SD of the digits when incremented by one until after the first non-9 digit.

26523308 is a bitmask that encodes the mapping for the digits 0-8. When n=0, which only occurs when n comprises only 9s, the answer will be off by two. This is compensated by the expression 0**n*2. As for the digit 9, the bitmask evaluates to zero which will trigger the recursive call while adding 2 to the 7SD.


问:
Weapons of Math Instruction
Last time when I tried to come up with something easy that wasn't a duplicate, it ended up being way too hard.. So hopefully this time it's indeed something newcomers can try as well.

Input:

An array/list with integers/decimals. (Or a string representing an array with integers/decimals.)

Output:

Loop through the numbers and apply the following five mathematical operands in this order:

Addition (+);

Subtraction (−);

Multiplication (* or × or ·);

Real / Calculator Division (/ or ÷);

Exponentiation (^ or **).

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the mathematical operation than the examples, then that is of course completely acceptable.)

Keep continuing until you've reached the end of the list, and then give the result of the sum.

Challenge rules:

Exponentiation by 0 (n ^ 0) should result in 1 (this also applies to 0 ^ 0 = 1).

There are no test cases for division by 0 (n / 0), so you don't have to worry about that edge-case.

If the array contains just a single number, we return that as the result.

General rules:

This is code-golf, so shortest answer in bytes wins.

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Test cases:

```<code>[1,2,3,4,5] -> 0
-> 1 + 2 = 3
  -> 3 - 3 = 0
    -> 0 * 4 = 0
      -> 0 / 5 = 0

[5,12,23,2,4,4,2,6,7] -> 539
-> 5 + 12 = 17
  -> 17 - 23 = -6
    -> -6 * 2 = -12
      -> -12 / 4 = -3
        -> -3 ^ 4 = 81
          -> 81 + 2 = 83
            -> 83 - 6 = 77
              -> 77 * 7 -> 539

[-8,50,3,3,-123,4,17,99,13] -> -1055.356...
-> -8 + 50 = 42
  -> 42 - 3 = 39
    -> 39 * 3 = 117
      -> 117 / -123 = -0.9512...
        -> -0.9512... ^ 4 = 0.818...
          -> 0.818... + 17 = 17.818...
            -> 17.818... - 99 -> -81.181...
              -> -81.181... * 13 = -1055.356...

[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256
-> 2 + 2 = 4
  -> 4 - 2 = 2
    -> 2 * 2 = 4
      -> 4 / 2 = 2
        -> 2 ^ 2 = 4
          -> 4 + 2 = 6
            -> 6 - 2 = 4
              -> 4 * 2 = 8
                -> 8 / 2 = 4
                  -> 4 ^ 2 = 16
                    -> 16 + 2 = 18
                      -> 18 - 2 = 16
                        -> 16 * 2 = 32
                          -> 32 / 2 = 16
                            -> 16 ^ 2 = 256

[1,0,1,0,1,0] -> 1
-> 1 + 0 = 1
  -> 1 - 1 = 0
    -> 0 * 0 = 0
      -> 0 / 1 = 0
        -> 0 ^ 0 = 1

[-9,-8,-1] -> -16
  -> -9 + -8 = -17
    -> -17 - -1 = -16

[0,-3] -> -3
  -> 0 + -3 = -3

[-99] -> -99
</code>```

答:
Pyth, <s>27</s> <s>26</s> 25 bytes

```<code>.v+>tlQ*lQ"^c*-+":jdQ\-\_
</code>```

Test suite.

Pyth uses prefix notation: 1+2 is written as +1 2 (space needed to separate numbers).

Therefore, for the first testcase, the expression would be (((1+2)-3)*4)/5, which in prefix notation, would be written as /*-+ 1 2 3 4 5.

In Pyth, float division is c instead of /, so it becomes c*-+ 1 2 3 4 5.

Also, in Pyth, -100 is written as _100 instead.

Therefore, for the third test case, which is ((((((((-8+50)-3)*3)/-123)^4)+17)-99)*13), it becomes: *-+^c*-+ _8 50 3 3 _123 4 17 99 13.

```<code>.v+>tlQ*lQ"^c*-+":jdQ\-\_
                  jdQ       Join input by space.
                 :   \-\_   Replace "-" with "_".
   >tlQ*lQ"^c*-+"           Generate the string "...^c*-+" of suitable length.
  +                         Join the two strings above.
.v                          Evaluate as a Pyth expression.
</code>```

History

33 bytes: v:P+*lQ\(ssV+R\)Q*"+-*/p"lQ\p"**"

27 bytes: .vs+_XUtQUQ"+-*c^"m:+;d\-\_

26 bytes: .vs+_XUtQUQ"+-*c^":jdQ\-\_

Title: Weapons of Math Instruction

Body:
Pyth, <s>27</s> <s>26</s> 25 bytes

.v+>tlQ*lQ"^c*-+":jdQ\-\_

Test suite.

Pyth uses prefix notation: 1+2 is written as +1 2 (space needed to separate numbers).

Therefore, for the first testcase, the expression would be (((1+2)-3)*4)/5, which in prefix notation, would be written as /*-+ 1 2 3 4 5.

In Pyth, float division is c instead of /, so it becomes c*-+ 1 2 3 4 5.

Also, in Pyth, -100 is written as _100 instead.

Therefore, for the third test case, which is ((((((((-8+50)-3)*3)/-123)^4)+17)-99)*13), it becomes: *-+^c*-+ _8 50 3 3 _123 4 17 99 13.

.v+>tlQ*lQ"^c*-+":jdQ\-\_
                  jdQ       Join input by space.
                 :   \-\_   Replace "-" with "_".
   >tlQ*lQ"^c*-+"           Generate the string "...^c*-+" of suitable length.
  +                         Join the two strings above.
.v                          Evaluate as a Pyth expression.

History

33 bytes: v:P+*lQ\(ssV+R\)Q*"+-*/p"lQ\p"**"

27 bytes: .vs+_XUtQUQ"+-*c^"m:+;d\-\_

26 bytes: .vs+_XUtQUQ"+-*c^":jdQ\-\_


答:
Javascript ES7 49 bytes

```<code>a=>a.reduce((c,d,e)=>[c**d,c+d,c-d,c*d,c/d][e%5])
</code>```

Saved 9 bytes thanks to Dom Hastings, saved another 6 thanks to Leaky Nun

Uses the new exponentiation operator.

Title: Weapons of Math Instruction

Body:
Last time when I tried to come up with something easy that wasn't a duplicate, it ended up being way too hard.. So hopefully this time it's indeed something newcomers can try as well.

Input:

An array/list with integers/decimals. (Or a string representing an array with integers/decimals.)

Output:

Loop through the numbers and apply the following five mathematical operands in this order:

Addition (+);

Subtraction (−);

Multiplication (* or × or ·);

Real / Calculator Division (/ or ÷);

Exponentiation (^ or **).

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the mathematical operation than the examples, then that is of course completely acceptable.)

Keep continuing until you've reached the end of the list, and then give the result of the sum.

Challenge rules:

Exponentiation by 0 (n ^ 0) should result in 1 (this also applies to 0 ^ 0 = 1).

There are no test cases for division by 0 (n / 0), so you don't have to worry about that edge-case.

If the array contains just a single number, we return that as the result.

General rules:

This is code-golf, so shortest answer in bytes wins.

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Test cases:

```<code>[1,2,3,4,5] -> 0
-> 1 + 2 = 3
  -> 3 - 3 = 0
    -> 0 * 4 = 0
      -> 0 / 5 = 0

[5,12,23,2,4,4,2,6,7] -> 539
-> 5 + 12 = 17
  -> 17 - 23 = -6
    -> -6 * 2 = -12
      -> -12 / 4 = -3
        -> -3 ^ 4 = 81
          -> 81 + 2 = 83
            -> 83 - 6 = 77
              -> 77 * 7 -> 539

[-8,50,3,3,-123,4,17,99,13] -> -1055.356...
-> -8 + 50 = 42
  -> 42 - 3 = 39
    -> 39 * 3 = 117
      -> 117 / -123 = -0.9512...
        -> -0.9512... ^ 4 = 0.818...
          -> 0.818... + 17 = 17.818...
            -> 17.818... - 99 -> -81.181...
              -> -81.181... * 13 = -1055.356...

[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256
-> 2 + 2 = 4
  -> 4 - 2 = 2
    -> 2 * 2 = 4
      -> 4 / 2 = 2
        -> 2 ^ 2 = 4
          -> 4 + 2 = 6
            -> 6 - 2 = 4
              -> 4 * 2 = 8
                -> 8 / 2 = 4
                  -> 4 ^ 2 = 16
                    -> 16 + 2 = 18
                      -> 18 - 2 = 16
                        -> 16 * 2 = 32
                          -> 32 / 2 = 16
                            -> 16 ^ 2 = 256

[1,0,1,0,1,0] -> 1
-> 1 + 0 = 1
  -> 1 - 1 = 0
    -> 0 * 0 = 0
      -> 0 / 1 = 0
        -> 0 ^ 0 = 1

[-9,-8,-1] -> -16
  -> -9 + -8 = -17
    -> -17 - -1 = -16

[0,-3] -> -3
  -> 0 + -3 = -3

[-99] -> -99
</code>```

Body:
Javascript ES7 49 bytes

a=>a.reduce((c,d,e)=>[c**d,c+d,c-d,c*d,c/d][e%5])

Saved 9 bytes thanks to Dom Hastings, saved another 6 thanks to Leaky Nun

Uses the new exponentiation operator.


问:
Count sum of all digits
This challenge is to write a program or script which counts the sum of all digits within the integers from 1 up to and including a given number.

Input, one positive integer.
Output, the sum of digits in that number and all smaller numbers.

Examples:

```<code>Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 + 4 + 5 = 15

Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51
</code>```

To be clear, this is to count a sum of the digits - not the integers. For single-digit inputs, this will be the same. However, inputs larger than 10 will have different responses. This would be an incorrect response:

```<code>Input: 12
Output: 78
</code>```

Another example, to show the difference:

```<code>Input: 10

Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46
</code>```

A larger test case (CORRECT RESPONSE):

```<code>Input: 1000000
Output: 27000001
</code>```

Rules & Guidelines:

Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.

The number must be input by the user - not hard-coded. Input may be received as a command-line argument, file, stdin, or any other means by which your language can take user input.

The code must be able to properly handle inputs at least up to (2^64)-1.

The code should only output the sum.

Submitted programs & scripts should be user-friendly and not wasteful of computer resources (e.g.: they should not declare insanely-large arrays to hold every character). There is no strict bonus or penalty for this, but please be good programmers.

Scoring:

Primary scoring mechanism is by code length. Lower scores are better. The following bonuses and penalties also apply:

-25 Bonus if your code can handle all positive numbers, for example: 1234567891234567891234564789087414984894900000000

-50 Bonus if your code can handle simple expressions, for example 55*96-12. To qualify for this bonus, the code should handle + - / * (addition, subtraction, division, multiplication) operators and enforce order of operations. Division is regular integer division.

The given example (55*96-12) evaluates to 5268. Your code should return the same for either of those inputs - correct answer is 81393.

-10 Bonus if your code qualifies for the -50 bonus and can handle the ^ (exponent) operator.

-100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions.

+300 Penalty if your code relies upon any web resources.

答:
Brainfuck 12 Chars / Points

```<code>,[[>+>+<<-]>[-<+>]<-].
</code>```

However this solution only handles numbers to 256-1

And you have to enter as I symbols. E.g.: 0 > 48; 1 > 49

A simple conversion would be

```<code>,>++++++++[<------>-]<[[>+>+<<-]>[-<+>]<-].
</code>```

Breakdown:

```<code>,[[>+>+<<-]>[-<+>]<-].
,                       #Take user input
 [                      #While the input number is still > 0
  [>+>+<<-]             #Move it to the two next slots
           >[-<+>]      #And copy it back in the first slot
                  <-]   #Decrease the input by 1 and repeat
                     .  #Print out result

The Number in third slot will constantly be added to
</code>```

ContentLicense: CC BY-SA 4.0

Title: Count sum of all digits

Body:
Brainfuck 12 Chars / Points

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

However this solution only handles numbers to 256-1

And you have to enter as I symbols. E.g.: 0 > 48; 1 > 49

A simple conversion would be

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

Breakdown:

,[[>+>+<<-]>[-<+>]<-].
,                       #Take user input
 [                      #While the input number is still > 0
  [>+>+<<-]             #Move it to the two next slots
           >[-<+>]      #And copy it back in the first slot
                  <-]   #Decrease the input by 1 and repeat
                     .  #Print out result

The Number in third slot will constantly be added to


答:
Pyke, <s>22</s> 21 bytes

```<code>lt5L%"+-*/^"L@\RJQ_XE
</code>```

Try it here!

```<code>lt5L%                 -    map(len(input)-1, %5)
     "+-*/^"L@        -   map(^, "+-*/^"[<])
              \RJ     -  "R".join(^)
                    E - pyke_eval(^, V)
                 Q_X  -  splat(reversed(input))
</code>```

Title: Weapons of Math Instruction

Body:
Pyke, <s>22</s> 21 bytes

lt5L%"+-*/^"L@\RJQ_XE

Try it here!

lt5L%                 -    map(len(input)-1, %5)
     "+-*/^"L@        -   map(^, "+-*/^"[<])
              \RJ     -  "R".join(^)
                    E - pyke_eval(^, V)
                 Q_X  -  splat(reversed(input))


答:
Brachylog, 68 bytes

```<code>hI,?bL,1:+:-:*:/:^b:L:I{bhv?t.|[O:L:I]h$(P,LbM,OhA,Lh:Ir:A&:M:Pr&.}.
</code>```

That's long… but it uses no evaluation predicate.

Explanation

Main predicate

```<code>hI,                                  Unify I with the first element of the input
   ?bL,                              L is the input minus the first element
       1:+:-:*:/:^b                  Construct the list of predicates [+:-:*:/:^]
                   :L:I{...}.        Call predicate 1 with [[+:-:*:/:^]:L:I] as input
</code>```

Predicate 1

```<code>bhv?t.                               If the second element of Input is empty (i.e. L),
                                     unify Output with the last element of Input
|                                    Or
[O:L:I]                              Input = [O:L:I]
       h$(P,                         P is O circularly permutated to the left
            LbM,                     M is L minus the first element
                OhA,                 A is the first element of O
                    Lh:Ir:A&         Call predicate A on [I:First element of L]
                            :M:Pr&.  Call predicate 1 recursively with P:M:
</code>```

Title: Weapons of Math Instruction

Body:
Brachylog, 68 bytes

hI,?bL,1:+:-:*:/:^b:L:I{bhv?t.|[O:L:I]h$(P,LbM,OhA,Lh:Ir:A&:M:Pr&.}.

That's long… but it uses no evaluation predicate.

Explanation

Main predicate

hI,                                  Unify I with the first element of the input
   ?bL,                              L is the input minus the first element
       1:+:-:*:/:^b                  Construct the list of predicates [+:-:*:/:^]
                   :L:I{...}.        Call predicate 1 with [[+:-:*:/:^]:L:I] as input

Predicate 1

bhv?t.                               If the second element of Input is empty (i.e. L),
                                     unify Output with the last element of Input
|                                    Or
[O:L:I]                              Input = [O:L:I]
       h$(P,                         P is O circularly permutated to the left
            LbM,                     M is L minus the first element
                OhA,                 A is the first element of O
                    Lh:Ir:A&         Call predicate A on [I:First element of L]
                            :M:Pr&.  Call predicate 1 recursively with P:M:


答:
TSQL <s>116</s> <s>115</s> 88 bytes

Thanks to Ross Presser suggestion I was able to golf this down to 88 characters

-- In Try-it code, this must be DECLARE @y TABLE
CREATE TABLE T(a real, i int identity)
INSERT T values(5),(12),(23),(2),(4),(4),(2),(6),(7)

DECLARE @ REAL SELECT @=CHOOSE(i%5+1,@/a,ISNULL(POWER(@,a),a),@+a,@-a,@*a)FROM T
PRINT @
```

Try it online

Title: Weapons of Math Instruction

Body:
TSQL <s>116</s> <s>115</s> 88 bytes

Thanks to Ross Presser suggestion I was able to golf this down to 88 characters

-- In Try-it code, this must be DECLARE @y TABLE
CREATE TABLE T(a real, i int identity)
INSERT T values(5),(12),(23),(2),(4),(4),(2),(6),(7)

DECLARE @ REAL SELECT @=CHOOSE(i%5+1,@/a,ISNULL(POWER(@,a),a),@+a,@-a,@*a)FROM T
PRINT @

Try it online


答:
Java 8, <s>173</s> <s>172</s> <s>167</s> <s>138</s> <s>137</s> <s>118</s> 113 bytes

a->{double r=a[0],t;for(int i=1;i<a.length;r=new double[]{Math.pow(r,t),r+t,r-t,r*t,r/t}[i++%5])t=a[i];return r;}
```
<p><strong>Explanation:</strong></p>
<p>Try it here.</p>
<pre class="lang-java prettyprint-override"><code>a->{                     // Method with double-array parameter and double return-type
  double r=a[0],         //  Result-double, starting at the first item of the input
         t;              //  Temp double
  for(int i=1;           //  Index-integer, starting at the second item
      i<a.length;        //  Loop over the input-array
      r=new double[]{    //    After every iteration, change `r` to:
         Math.pow(r,t),  //      If `i%5` is 0: `r^t`
         r+t,            //      Else-if `i%5` is 1: `r+t`
         r-t,            //      Else-if `i%5` is 2: `r-t`
         r*t,            //      Else-if `i%5` is 3: `r*t`
         r/t}[i++%5])    //      Else-if `i%5` is 4: `r/t`
                         //      And increase `i` by 1 afterwards with `i++`
    t=a[i];              //   Change `t` to the next item in the array
  return r;}             //  Return result-double
</code>```

Title: Weapons of Math Instruction

Body:
Java 8, <s>173</s> <s>172</s> <s>167</s> <s>138</s> <s>137</s> <s>118</s> 113 bytes

a->{double r=a[0],t;for(int i=1;i<a.length;r=new double[]{Math.pow(r,t),r+t,r-t,r*t,r/t}[i++%5])t=a[i];return r;}

Explanation:

Try it here.

a->{                     // Method with double-array parameter and double return-type
  double r=a[0],         //  Result-double, starting at the first item of the input
         t;              //  Temp double
  for(int i=1;           //  Index-integer, starting at the second item
      i<a.length;        //  Loop over the input-array
      r=new double[]{    //    After every iteration, change `r` to:
         Math.pow(r,t),  //      If `i%5` is 0: `r^t`
         r+t,            //      Else-if `i%5` is 1: `r+t`
         r-t,            //      Else-if `i%5` is 2: `r-t`
         r*t,            //      Else-if `i%5` is 3: `r*t`
         r/t}[i++%5])    //      Else-if `i%5` is 4: `r/t`
                         //      And increase `i` by 1 afterwards with `i++`
    t=a[i];              //   Change `t` to the next item in the array
  return r;}             //  Return result-double


答:
J, 40 bytes

```<code>^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#)
</code>```

Finds the number of values needed to use a multiple of 5 operators, than pads with the identity values of those operators. In order, + is 0, - is 0, * is 1, % is 1, and ^ is 1, which can be a bit value 00111, or 7 in base 10. Then operates on that list while cycling through operators.

Usage

```<code>   f =: ^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#)
   f 1 2 3 4 5
0
   f 5 12 23 2 4 4 2 6 7
539
   f _8 50 3 3 _123 4 17 99 13
_1055.36
   f 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
256
   f 1 0 1 0 1 0
1
   f _9 _8 _1
_16
   f 0 _3
_3
   f _99
_99
</code>```

Explanation

```<code>^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#) Input: A
                                      #  Get length of A
                                    4+   Add four to it
                                  5|     Take it mod 5
                                5-       Find 5 minus its value, call it x
                           #&2           Create x copies of 2
                       7#:~              Convert 7 to base 2 and take the last x digits
                      ,                  Append those x digits to the end of A
                   |.@                   Reverse it, call it A'
^~                                       Power, reversed operators
    %~                                   Division, reversed operators
       *                                 Multiplication
         -~                              Subtraction, reversed operators
            +                            Addition
             /@                          Insert the previous operations, separated by `,
                                         into A' in order and cycle until the end
                                         Then evaluate the equation from right-to-left
                                         and return
</code>```

Title: Weapons of Math Instruction

Body:
J, 40 bytes

^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#)

Finds the number of values needed to use a multiple of 5 operators, than pads with the identity values of those operators. In order, + is 0, - is 0, * is 1, % is 1, and ^ is 1, which can be a bit value 00111, or 7 in base 10. Then operates on that list while cycling through operators.

Usage

   f =: ^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#)
   f 1 2 3 4 5
0
   f 5 12 23 2 4 4 2 6 7
539
   f _8 50 3 3 _123 4 17 99 13
_1055.36
   f 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
256
   f 1 0 1 0 1 0
1
   f _9 _8 _1
_16
   f 0 _3
_3
   f _99
_99

Explanation

^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#) Input: A
                                      #  Get length of A
                                    4+   Add four to it
                                  5|     Take it mod 5
                                5-       Find 5 minus its value, call it x
                           #&2           Create x copies of 2
                       7#:~              Convert 7 to base 2 and take the last x digits
                      ,                  Append those x digits to the end of A
                   |.@                   Reverse it, call it A'
^~                                       Power, reversed operators
    %~                                   Division, reversed operators
       *                                 Multiplication
         -~                              Subtraction, reversed operators
            +                            Addition
             /@                          Insert the previous operations, separated by `,
                                         into A' in order and cycle until the end
                                         Then evaluate the equation from right-to-left
                                         and return


答:
Actually, 23 bytes

```<code>;l"+-*/ⁿ"*@R':j':+'?o+ƒ
</code>```

Try it online!

Actually uses postfix notation for mathematics, and operators that only ever take two arguments (such as the operators for addition, subtraction, multiplication, division, and exponentiation) do nothing when there is only one element on the stack. Thus, turning the input into Actually code is as simple as reversing the input, formatting it as numerics, and appending the operations. Then, the resultant code can be executed, giving the desired output.

Explanation:

```<code>;l"+-*/ⁿ"*@R':j':+'?o+ƒ
;l"+-*/ⁿ"*               repeat the operations a number of times equal to the length of the input
                            (since extraneous operations will be NOPs, there's no harm in overshooting)
          @R             reverse the input
            ':j          join on ":" (make a string, inserting ":" between every pair of elements in the list)
               ':+       prepend a ":" (for the first numeric literal)
                  '?o    append a "?"
                           (this keeps the poor numeric parsing from trying to gobble up the first + as part of the numeric literal, since ? isn't interpreted as part of the literal, and is a NOP)
                     +   append the operations string
                      ƒ  cast as a function and call it
</code>```

Example of translated code for input 1,2,3,4,5:

```<code>:5:4:3:2:1?+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ
</code>```

Title: Weapons of Math Instruction

Body:
Actually, 23 bytes

;l"+-*/ⁿ"*@R':j':+'?o+ƒ

Try it online!

Actually uses postfix notation for mathematics, and operators that only ever take two arguments (such as the operators for addition, subtraction, multiplication, division, and exponentiation) do nothing when there is only one element on the stack. Thus, turning the input into Actually code is as simple as reversing the input, formatting it as numerics, and appending the operations. Then, the resultant code can be executed, giving the desired output.

Explanation:

;l"+-*/ⁿ"*@R':j':+'?o+ƒ
;l"+-*/ⁿ"*               repeat the operations a number of times equal to the length of the input
                            (since extraneous operations will be NOPs, there's no harm in overshooting)
          @R             reverse the input
            ':j          join on ":" (make a string, inserting ":" between every pair of elements in the list)
               ':+       prepend a ":" (for the first numeric literal)
                  '?o    append a "?"
                           (this keeps the poor numeric parsing from trying to gobble up the first + as part of the numeric literal, since ? isn't interpreted as part of the literal, and is a NOP)
                     +   append the operations string
                      ƒ  cast as a function and call it

Example of translated code for input 1,2,3,4,5:

:5:4:3:2:1?+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ


答:
Haskell - 74

```<code>f(x:xs)=foldl(\x(o,y)->o x y)x(zip(cycle[(+),(-),(*),(/),flip(^).floor])xs)
</code>```

Test cases:

```<code>λ> f[1,2,3,4,5] -> 0.0
λ> f[5,12,23,2,4,4,2,6,7] -> 539.0
λ> f[-8,50,3,3,-123,4,17,99,13] -> -1055.356943846277
λ> f [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256.0
</code>```

It could probably be shorter; Haskell's support for infinite lists and higher order functions make the direct solution quite pleasant, though. A version of ^ :: Double -> Double -> Double would be nicer for golfing, but I couldn't find one. Thankfully, I didn't need a full lambda, so pointless style shaved off a few bytes.

Title: Weapons of Math Instruction

Body:
Haskell - 74

f(x:xs)=foldl(\x(o,y)->o x y)x(zip(cycle[(+),(-),(*),(/),flip(^).floor])xs)

Test cases:

λ> f[1,2,3,4,5] -> 0.0
λ> f[5,12,23,2,4,4,2,6,7] -> 539.0
λ> f[-8,50,3,3,-123,4,17,99,13] -> -1055.356943846277
λ> f [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256.0

It could probably be shorter; Haskell's support for infinite lists and higher order functions make the direct solution quite pleasant, though. A version of ^ :: Double -> Double -> Double would be nicer for golfing, but I couldn't find one. Thankfully, I didn't need a full lambda, so pointless style shaved off a few bytes.


答:
Haskell, <s>76</s> <s>65</s> <s>64</s> 62 bytes

Thanks to @Damien for removing another two bytes=)

```<code>f(u:v)=foldl(\x(f,y)->f x y)u(zip(v>>[(+),(-),(*),(/),(**)])v)
</code>```

This uses the >> which here just appends the list [(+),...] to itself length v times. The rest still works still the same as the old versions.

Old versions:

These solutions make use of the infinite lists, as cycle[...] just repeats the given list infinitely. Then it basically gets ziped with the list of numbers, and we just fold (reduce in other languages) the zipped list via a lambda, that applies the operators to the accumulator/current list element.

```<code>f(u:v)=foldl(\x(f,y)->f x y)u(zip(cycle[(+),(-),(*),(/),(**)])v)

f(u:v)=foldl(\x(y,f)->f x y)u(zip v(cycle[(+),(-),(*),(/),(**)]))

f l=foldl(\x(y,f)->f x y)(head l)(zip(drop 1l)(cycle[(+),(-),(*),(/),(**)]))
</code>```

Title: Weapons of Math Instruction

Body:
Haskell, <s>76</s> <s>65</s> <s>64</s> 62 bytes

Thanks to @Damien for removing another two bytes=)

f(u:v)=foldl(\x(f,y)->f x y)u(zip(v>>[(+),(-),(*),(/),(**)])v)

This uses the >> which here just appends the list [(+),...] to itself length v times. The rest still works still the same as the old versions.

Old versions:

These solutions make use of the infinite lists, as cycle[...] just repeats the given list infinitely. Then it basically gets ziped with the list of numbers, and we just fold (reduce in other languages) the zipped list via a lambda, that applies the operators to the accumulator/current list element.

f(u:v)=foldl(\x(f,y)->f x y)u(zip(cycle[(+),(-),(*),(/),(**)])v)

f(u:v)=foldl(\x(y,f)->f x y)u(zip v(cycle[(+),(-),(*),(/),(**)]))

f l=foldl(\x(y,f)->f x y)(head l)(zip(drop 1l)(cycle[(+),(-),(*),(/),(**)]))


答:
Oracle PL/SQL, <s>275</s> 254 Bytes

```<code>declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;
</code>```

The data must be inserted in a table called T with a column N of type NUMBER

Usage:

```<code>drop table t;
create table t (n number);
insert into t values (-8);
insert into t values (50);
insert into t values (3);
insert into t values (3);
insert into t values (-123);
insert into t values (4);
insert into t values (17);
insert into t values (99);
insert into t values (13);

declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;
</code>```

Output:

```<code>-1055,356943846277162152071601242992595623
</code>```

275 Bytes version:

```<code>declare r number;cursor c is select n,mod(rownum,5) r from t;begin for x in c loop if r is null then r:=x.n;else case x.r when 2 then r:=r+x.n;when 3 then r:=r-x.n;when 4 then r:=r*x.n;when 0 then r:=r/x.n;else r:=r**x.n; end case;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;
</code>```

Title: Weapons of Math Instruction

Body:
Oracle PL/SQL, <s>275</s> 254 Bytes

declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;

The data must be inserted in a table called T with a column N of type NUMBER

Usage:

drop table t;
create table t (n number);
insert into t values (-8);
insert into t values (50);
insert into t values (3);
insert into t values (3);
insert into t values (-123);
insert into t values (4);
insert into t values (17);
insert into t values (99);
insert into t values (13);

declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;

Output:

-1055,356943846277162152071601242992595623

275 Bytes version:

declare r number;cursor c is select n,mod(rownum,5) r from t;begin for x in c loop if r is null then r:=x.n;else case x.r when 2 then r:=r+x.n;when 3 then r:=r-x.n;when 4 then r:=r*x.n;when 0 then r:=r/x.n;else r:=r**x.n; end case;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;


Title: Weapons of Math Instruction

Body:
Mathematica, <s>67</s> <s>66</s> 65 bytes

Fold[{+##,#-#2,#2#,#/#2,If[#2==0,1,#^#2]}[[i++~Mod~5+1]]&,i=0;#]&

Simple Fold with a variable i holding the index.


答:
Retina, 34 bytes

```<code>M!`.9*$
^9
0
T`d`4523315412
.
$*
.
</code>```

Try it online! (The first line just allows the processing of multiple test cases at once.)

Explanation

Like most answers have discovered by now, we don't need to use the full table, since only the least-significant non-9 digit changes when incrementing. That's also how this answer works.

```<code>M!`.9*$
</code>```

This matches (M) the regex .9*$ i.e. the first digit that is only separated by 9s from the end. The ! tells Retina to replace the input with this match, discarding everything that doesn't affect the 7SD.

```<code>^9
0
</code>```

If the input now starts with a 9 that means, the input itself consisted only of 9s, so the 7-segment display needs to prepend a 1 which costs 2. The simplest way to handle this is to replace the leading 9 in this case with a 0, since the cost of incrementing a 9 (to 0) is 2 and the cost of incrementing 0 (to 1) is 4, so this raises the overall cost by 2 as required.

```<code>T`d`4523315412
</code>```

Now we have a transliteration stage which replaces each digit with its cost for incrementing it (since the d expands to 0123456789). Note that this is the first subdiagonal of the 7SD table.

```<code>.
$*
</code>```

This replaces each digit n with n copies of 1, i.e. it converts each digit to unary, and since there are no separators immediately adds them together.

```<code>.
</code>```

Finally, we count the number of characters (i.e. number of matches of .) in the result, which converts the unary sum back to decimal.

Title: 7-segment differences

Body:
I think most people around here know what a 7-segment display for digits is:

```<code> _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|
</code>```

We can define the 7-segment difference (7SD) between two digits to be the number of segments that need to be toggled to switch from one to the other. E.g. the 7SD between 1 and 2 is 5 (the three horizontal segments and the lower two vertical segments need to be toggled), and the 7SD between 6 and 8 is 1.

Furthermore, we can define the 7SD between two numbers to be the sum of 7SDs between their corresponding digits. If one number is longer than the other, we assume they are right-aligned and add the number of segments needed to display the additional most-significant digits of the larger number. As an example, consider the 7SD between 12345 and 549:

```<code>  x:  1 2 3 4 5
  y:      5 4 9
7SD:  2+5+2+0+1 = 10
</code>```

Your task is to compute 7SD between n and n+1, given n.

For convenience, here is the full table of 7SDs between individual digits. The row _ represents an empty position.

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

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

Input

Input is a single positive integer n.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument.

You may assume that the input is at most one less than the largest number which can be represented by your language's standard integer type, as long as that type supports at least values up to and including 127.

Output

You should print a single integer, the 7SD between n and n+1.

You may output via STDOUT (or closest alternative), function return value or function (out) argument.

Scoring

Standard code-golf rules apply, shortest code (in bytes) wins.

Test Cases

For some obscure reason, this sequence isn't in OEIS yet, although there is the closely related sequence A123587. Here are the first 100 numbers (starting with n = 1, 2, 3, ...):

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

The first input for which the 7SD is greater than 9 is 1999 which should yield 11. Here are some other larger examples:

```<code>n          7SD
1999        11
12345        1
999999      14
5699999     15
8765210248   1
</code>```

Body:
Retina, 34 bytes

M!`.9*$
^9
0
T`d`4523315412
.
$*
.

Try it online! (The first line just allows the processing of multiple test cases at once.)

Explanation

Like most answers have discovered by now, we don't need to use the full table, since only the least-significant non-9 digit changes when incrementing. That's also how this answer works.

M!`.9*$

This matches (M) the regex .9*$ i.e. the first digit that is only separated by 9s from the end. The ! tells Retina to replace the input with this match, discarding everything that doesn't affect the 7SD.

^9
0

If the input now starts with a 9 that means, the input itself consisted only of 9s, so the 7-segment display needs to prepend a 1 which costs 2. The simplest way to handle this is to replace the leading 9 in this case with a 0, since the cost of incrementing a 9 (to 0) is 2 and the cost of incrementing 0 (to 1) is 4, so this raises the overall cost by 2 as required.

T`d`4523315412

Now we have a transliteration stage which replaces each digit with its cost for incrementing it (since the d expands to 0123456789). Note that this is the first subdiagonal of the 7SD table.

.
$*

This replaces each digit n with n copies of 1, i.e. it converts each digit to unary, and since there are no separators immediately adds them together.

.

Finally, we count the number of characters (i.e. number of matches of .) in the result, which converts the unary sum back to decimal.


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+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,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px}</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

```

答:
Enigma-2D, 2 bytes

```<code>RL
</code>```

The IP alternates between moving rightwards and leftwards.

Body:
Enigma-2D, 2 bytes

RL

The IP alternates between moving rightwards and leftwards.


答:
PowerShell v4+, 68 bytes

```<code>$a,$b=($c=(ls).Name)-split'\.';mv $c "$(-join($a[$a.length..0])).$b"
</code>```

Only works because the script is guaranteed to be in a directory all by itself. Performs an ls (alias for Get-ChildItem) and takes the .Name of the resultant object(s). We store that in $c and then -split it on literal period to get the filename and extension, and store those in $a and $b, respectively.

Next is the mv (alias for Move-Item) command, where we're moving $c to $a(reversed).$b.

Example

```<code>PS C:\Tools\Scripts\golfing\reverse> ls

    Directory: C:\Tools\Scripts\golfing\reverse

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/13/2016   7:58 AM         88 reverse.ps1

PS C:\Tools\Scripts\golfing\reverse> .\reverse.ps1

PS C:\Tools\Scripts\golfing\reverse> ls

    Directory: C:\Tools\Scripts\golfing\reverse

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/13/2016   7:58 AM         88 esrever.ps1
</code>```

Title: Write a program that reverses the name of its source file

Body:
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Body:
PowerShell v4+, 68 bytes

$a,$b=($c=(ls).Name)-split'\.';mv $c "$(-join($a[$a.length..0])).$b"

Only works because the script is guaranteed to be in a directory all by itself. Performs an ls (alias for Get-ChildItem) and takes the .Name of the resultant object(s). We store that in $c and then -split it on literal period to get the filename and extension, and store those in $a and $b, respectively.

Next is the mv (alias for Move-Item) command, where we're moving $c to $a(reversed).$b.

Example

PS C:\Tools\Scripts\golfing\reverse> ls

    Directory: C:\Tools\Scripts\golfing\reverse

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/13/2016   7:58 AM         88 reverse.ps1

PS C:\Tools\Scripts\golfing\reverse> .\reverse.ps1

PS C:\Tools\Scripts\golfing\reverse> ls

    Directory: C:\Tools\Scripts\golfing\reverse

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/13/2016   7:58 AM         88 esrever.ps1


问:
Approximation of e
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

答:
Brachylog, 18 bytes

```<code>:1-:0r:ef:$!a:/a+.
</code>```

Explanation

```<code>:1-                 Subtract 1 from Input
   :0r              Create the list [0, Input - 1]
      :ef           Find all integers between 0 and Input - 1
         :$!a       Apply factorial to each member of that list
             :/a    Apply inverse to each element of that list
                +.  Unify the output with the sum of the list
</code>```

Title: Approximation of e

Body:
Brachylog, 18 bytes

:1-:0r:ef:$!a:/a+.

Explanation

:1-                 Subtract 1 from Input
   :0r              Create the list [0, Input - 1]
      :ef           Find all integers between 0 and Input - 1
         :$!a       Apply factorial to each member of that list
             :/a    Apply inverse to each element of that list
                +.  Unify the output with the sum of the list


问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution 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.

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

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

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.

Also note that languages do have to fulfil our usual criteria for programming languages.

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.

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 catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue 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

```

答:
Wat, 6 + 1 = 7 bytes

```<code>åó#ÐÑÅ
</code>```

(This code don't have any rapport with DNA)

Explanation:

```<code>åó#ÐÑÅ

å      Read a character
 ó     Duplicate the top of the stack
  #    Skip the next character
   Ð   End the program
    Ñ  If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
     Å Print the character on the top of the stack
       After, the IP wrap and the line is reexecuted
</code>```

Title: Simple cat program

Body:
Wat, 6 + 1 = 7 bytes

åó#ÐÑÅ

(This code don't have any rapport with DNA)

Explanation:

åó#ÐÑÅ

å      Read a character
 ó     Duplicate the top of the stack
  #    Skip the next character
   Ð   End the program
    Ñ  If the top of the stack is 0, go backward (execute Ð and end the program), otherwise go forward
     Å Print the character on the top of the stack
       After, the IP wrap and the line is reexecuted


答:
PowerShell v2+, 124 bytes

```<code>param($n)$o=$n[0];if($y=$n.count-1){1..$y|%{$o=if(($x=$i++%5)-4){"$o"+'+-*/'[$x]+$n[$_]|iex}else{[math]::pow($o,$n[$_])}}}$o
</code>```

Long because PowerShell doesn't have a ^ or ** operator, so we have to account for a separate case and use a .NET call.

Takes input $n as an array, sets our output $o to be the first digit. We then check the .count of the array, and so long as it's greater than one we enter the if. Otherwise, we skip the if.

Inside the if we loop through the array 1..$y|%{...} and each iteration we re-set $o to a new value, the result of another if/else statement. So long as our counter $i++ isn't modulo-5 equal to 4 (i.e., we're not at the ^ operator), we simply take $o and concatenate it with the appropriate symbol '+-*/'[$x] and the next number in the input array $n[$_]. We pipe that to iex (alias for Invoke-Expression and similar to eval), and that gets re-saved to $o. If we're on the ^ operator, we're in the else, so we execute a [math]::Pow() call, and that result gets re-saved back into $o.

In either case, we simply output $o to the pipeline and exit, with output implicit.

Title: Weapons of Math Instruction

Body:
Last time when I tried to come up with something easy that wasn't a duplicate, it ended up being way too hard.. So hopefully this time it's indeed something newcomers can try as well.

Input:

An array/list with integers/decimals. (Or a string representing an array with integers/decimals.)

Output:

Loop through the numbers and apply the following five mathematical operands in this order:

Addition (+);

Subtraction (−);

Multiplication (* or × or ·);

Real / Calculator Division (/ or ÷);

Exponentiation (^ or **).

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the mathematical operation than the examples, then that is of course completely acceptable.)

Keep continuing until you've reached the end of the list, and then give the result of the sum.

Challenge rules:

Exponentiation by 0 (n ^ 0) should result in 1 (this also applies to 0 ^ 0 = 1).

There are no test cases for division by 0 (n / 0), so you don't have to worry about that edge-case.

If the array contains just a single number, we return that as the result.

General rules:

This is code-golf, so shortest answer in bytes wins.

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Test cases:

```<code>[1,2,3,4,5] -> 0
-> 1 + 2 = 3
  -> 3 - 3 = 0
    -> 0 * 4 = 0
      -> 0 / 5 = 0

[5,12,23,2,4,4,2,6,7] -> 539
-> 5 + 12 = 17
  -> 17 - 23 = -6
    -> -6 * 2 = -12
      -> -12 / 4 = -3
        -> -3 ^ 4 = 81
          -> 81 + 2 = 83
            -> 83 - 6 = 77
              -> 77 * 7 -> 539

[-8,50,3,3,-123,4,17,99,13] -> -1055.356...
-> -8 + 50 = 42
  -> 42 - 3 = 39
    -> 39 * 3 = 117
      -> 117 / -123 = -0.9512...
        -> -0.9512... ^ 4 = 0.818...
          -> 0.818... + 17 = 17.818...
            -> 17.818... - 99 -> -81.181...
              -> -81.181... * 13 = -1055.356...

[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256
-> 2 + 2 = 4
  -> 4 - 2 = 2
    -> 2 * 2 = 4
      -> 4 / 2 = 2
        -> 2 ^ 2 = 4
          -> 4 + 2 = 6
            -> 6 - 2 = 4
              -> 4 * 2 = 8
                -> 8 / 2 = 4
                  -> 4 ^ 2 = 16
                    -> 16 + 2 = 18
                      -> 18 - 2 = 16
                        -> 16 * 2 = 32
                          -> 32 / 2 = 16
                            -> 16 ^ 2 = 256

[1,0,1,0,1,0] -> 1
-> 1 + 0 = 1
  -> 1 - 1 = 0
    -> 0 * 0 = 0
      -> 0 / 1 = 0
        -> 0 ^ 0 = 1

[-9,-8,-1] -> -16
  -> -9 + -8 = -17
    -> -17 - -1 = -16

[0,-3] -> -3
  -> 0 + -3 = -3

[-99] -> -99
</code>```

Body:
PowerShell v2+, 124 bytes

param($n)$o=$n[0];if($y=$n.count-1){1..$y|%{$o=if(($x=$i++%5)-4){"$o"+'+-*/'[$x]+$n[$_]|iex}else{[math]::pow($o,$n[$_])}}}$o

Long because PowerShell doesn't have a ^ or ** operator, so we have to account for a separate case and use a .NET call.

Takes input $n as an array, sets our output $o to be the first digit. We then check the .count of the array, and so long as it's greater than one we enter the if. Otherwise, we skip the if.

Inside the if we loop through the array 1..$y|%{...} and each iteration we re-set $o to a new value, the result of another if/else statement. So long as our counter $i++ isn't modulo-5 equal to 4 (i.e., we're not at the ^ operator), we simply take $o and concatenate it with the appropriate symbol '+-*/'[$x] and the next number in the input array $n[$_]. We pipe that to iex (alias for Invoke-Expression and similar to eval), and that gets re-saved to $o. If we're on the ^ operator, we're in the else, so we execute a [math]::Pow() call, and that result gets re-saved back into $o.

In either case, we simply output $o to the pipeline and exit, with output implicit.


答:
Jelly, 24 bytes

```<code>Rð_²+×µ€µ³RḊm3,µÆP×1¦3FS
</code>```

Roughly the same approach as my Julia answer.

```<code>                          Initial argument: n
R                           Compute [1, 2, …, n]
 ð_²+×                      (λ, ρ) —→ (λ − ρ)² + λρ (which is λ² − λρ + ρ²)
      µ€                    Zip with itself. Call this Q.

        µ                 Refocus argument: Q
         ³                  The initial argument n
          RḊm3              Compute candidate green line primes: [2, 5, 8, …, n]
              ,             Call this P. Make pair with argument.

               µ          Refocus argument: [P, Q]
                ÆP          Check primality
                  ×1¦3      Multiply the first element by 3
                      FS    Sum everything
                            (The result is 3·countprimes(P) + countprimes(Q))
</code>```

Title: Counting Eisenstein primes

Body:
Introduction

Eisenstein integers are complex numbers of the form

a+bω

Where a,b are integers, and

ω = e^(2πi/3)

The Eisenstein integers form a triangular lattice in the complex plane:

We say that an Eisenstein integer z=a+bω is prime if it cannot be written as the product of two non-unit (not 1,-1,ω,-ω,ω^2, or -ω^2) Eisenstein integers

Program

Input: A natural number n.

Output: The number of Eisenstein primes which are of the form a+bω for which a,b are natural numbers (including zero) less than or equal to n

Test Cases

0 → 0

1 → 0

2 → 5

3 → 9

4 → 13

5 → 20

Scoring

This is code-golf, so least amount of bytes wins

Body:
Jelly, 24 bytes

Rð_²+×µ€µ³RḊm3,µÆP×1¦3FS

Roughly the same approach as my Julia answer.

                          Initial argument: n
R                           Compute [1, 2, …, n]
 ð_²+×                      (λ, ρ) —→ (λ − ρ)² + λρ (which is λ² − λρ + ρ²)
      µ€                    Zip with itself. Call this Q.

        µ                 Refocus argument: Q
         ³                  The initial argument n
          RḊm3              Compute candidate green line primes: [2, 5, 8, …, n]
              ,             Call this P. Make pair with argument.

               µ          Refocus argument: [P, Q]
                ÆP          Check primality
                  ×1¦3      Multiply the first element by 3
                      FS    Sum everything
                            (The result is 3·countprimes(P) + countprimes(Q))


问:
Self-Interpreting Interpreter
Based on a comment by George Edison to this question, write the smallest self-interpreting interpreter.

You may use the language of your choosing.

Empty languages do not count.  Your program must be at least two characters long.

The program does not need to interpret the entire language, just a Turing-complete subset of language features (that contains the interpreter).

Quines don't count.

Do not use your language's built-in eval function or equivalent. Same goes for apply, etc.

答:
Concurrent Filesystem Befunge 98 - 53\18 bytes (almost certainly cheating)

Full 53 byte interpreter with no restrictions (although I haven't tested complicated timing interactions involving IP splitting and wrapping):

```<code>v ;;;;;;;;
>]390'ai@
 t;;;;;;;;
;>zzzzz#;
</code>```

Reads input from a file named a and executes it. It isn't specifed in the rules that we can't use self-modifying code.

18 byte interpreter that does not allow wrapping (the IP moving of one edge of the code and starting at the opposite edge):

```<code>]210'ai@
t
><
</code>```

ContentLicense: CC BY-SA 2.5

Title: Self-Interpreting Interpreter

Body:
Concurrent Filesystem Befunge 98 - 53\18 bytes (almost certainly cheating)

Full 53 byte interpreter with no restrictions (although I haven't tested complicated timing interactions involving IP splitting and wrapping):

v ;;;;;;;;
>]390'ai@
 t;;;;;;;;
;>zzzzz#;

Reads input from a file named a and executes it. It isn't specifed in the rules that we can't use self-modifying code.

18 byte interpreter that does not allow wrapping (the IP moving of one edge of the code and starting at the opposite edge):

]210'ai@
t
><


问:
Stack Exchange Vote Counter
Write a program/function that returns the vote count of its own Stack Exchange answer at the time of its execution.

Your program/function may access this page (codegolf.stackexchange.com/questions/82609) off the internet, however:

Your program/function may not accept any user input and

The use of URL shorteners is not allowed

Your program/function may use only its own source as a reference point to its vote count (for example: no referencing strings of text in its contained answer but not in its own source)

Your program/function must output its own vote count and only its own vote count (for example: no returning all vote counts on this page)

This is code-golf, shortest code wins.

答:
PHP, 121 bytes

Without api.

```<code><?php preg_match('/t ">(.*)/',file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),$v);echo$v[1];
</code>```

Gets the whole post and extracts the vote counts with regex. (don't parse HTML with regex!)

Ungolfed:

```<code><?php
   preg_match('/t ">(.*)/',
              file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),
              $v);

   echo $v[1];
</code>```

Title: Stack Exchange Vote Counter

Body:
PHP, 121 bytes

Without api.

<?php preg_match('/t ">(.*)/',file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),$v);echo$v[1];

Gets the whole post and extracts the vote counts with regex. (don't parse HTML with regex!)

Ungolfed:

<?php
   preg_match('/t ">(.*)/',
              file_get_contents('http://codegolf.stackexchange.com/posts/82799/ajax-load'),
              $v);

   echo $v[1];


问:
Roman numeral converter function
Create the shortest function to convert a string of Roman numerals to an integer.

The rules for each letter can be found at the Wikipedia page.  Letters above 1,000 will have parentheses placed around them to signal their higher value.

Requirements:

Must convert Roman numerals 1 to 500,000

Must complete in less than a minute

Does not use built-in functions that could provide an advantage (Ex: A function that converts Roman numerals to integers)

Is a function

The function does not need to support fractions.  Any invalid input should return the number 0.

Shortest function wins.  In the case of a tie, the one with the most votes wins.

Test Cases

Input

```<code>III
</code>```

Output

```<code>3
</code>```

Input

```<code>IIII
</code>```

Output

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

Input

```<code>XVI
</code>```

Output

```<code>16
</code>```

Input

```<code>(C)(D)(L)MMI
</code>```

Output

```<code>452001
</code>```

答:
C++: 914 855 chars

```<code>#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;typedef map<char,int>R;R D,P,M;struct U{U():t(0),l(0),a(0){}int t,l,a;operator int(){return t+l;}I&d(I&s){char c,b;s>>c;if(c=='('){s>>c>>b;T(b!=')')c+=32;}if(s){R::iterator f=D.find(c);T(f==D.end())if(P[c]==l){l=f->S-l;a=0;}else{T(l&&(f->S>l))a=l==f->S?a+1:1;T(a>M[c])t+=l;l=f->S;}}return s;}};I&operator>>(I&s,U&d){return d.d(s);}int main(){D[' ']=-1;X(73,1,32,3)X(86,5,73,1)X(88,10,73,3)X(76,50,88,1)X(67,100,88,3)X(68,500,67,1)X(77,1000,67,3)X(118,5000,77,1)X(120,10000,77,3)X(108,50000,120,1)X(99,100000,120,3)X(100,500000,99,1)X(109,1000000,99,3)string w;while(cin>>w){try{stringstream s(w);U c;while(s>>c);cout<<c<<"\n";}catch(int x){cout<<"0\n";}}}
</code>```

It could be compressed further.

```<code>> ./a.exe
III
3
IIII
0
XVI
16
(C)(D)(L)MMI
452001
</code>```

Slightly nicer formatting: 1582 char

```<code>#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;

typedef map<char,int>      R;

R     D,P,M;

struct U
{
    U(): t(0), l(0), a(0) {}

    int  t,l,a;

    operator int()
    {
        return t + l;
    }
    I& d(I& s)
    {
        char c,b;
        s >> c;
        if (c == '(')
        {
            s >> c >> b;
            T(b != ')')
            c = tolower(c);
        }
        if (s)
        {
            R::iterator f = D.find(c);
            T(f == D.end())

            if (P[c] == l)
            {
                l = f->S - l;
                a = 0;
            }
            else
            {
                T(l&&(f->S > l))
                a=l==f->S?a+1:1;
                T(a>M[c])
                t   += l;
                l     = f->S;
            }
        }

        return s;
    }

};

I& operator>>(I& s,U& d)
{
    return d.d(s);
}

int main()
{
    D[' ']=-1;
    X(73,1,32,3)
    X(86,5,73,1)
    X(88,10,73,3)
    X(76,50,88,1)
    X(67,100,88,3)
    X(68,500,67,1)
    X(77,1000,67,3)
    X(118,5000,77,1)
    X(120,10000,77,3)
    X(108,50000,120,1)
    X(99,100000,120,3)
    X(100,500000,99,1)
    X(109,1000000,99,3)

    string w;
    while(cin >> w)
    {
        try
        {
            stringstream s(w);
            U    c;
            while(s >> c);
            cout << c << "\n";
        }
        catch(int x)
        {
            cout << "0\n";
        }
    }
}
</code>```

Title: Roman numeral converter function

Body:
C++: 914 855 chars

#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;typedef map<char,int>R;R D,P,M;struct U{U():t(0),l(0),a(0){}int t,l,a;operator int(){return t+l;}I&d(I&s){char c,b;s>>c;if(c=='('){s>>c>>b;T(b!=')')c+=32;}if(s){R::iterator f=D.find(c);T(f==D.end())if(P[c]==l){l=f->S-l;a=0;}else{T(l&&(f->S>l))a=l==f->S?a+1:1;T(a>M[c])t+=l;l=f->S;}}return s;}};I&operator>>(I&s,U&d){return d.d(s);}int main(){D[' ']=-1;X(73,1,32,3)X(86,5,73,1)X(88,10,73,3)X(76,50,88,1)X(67,100,88,3)X(68,500,67,1)X(77,1000,67,3)X(118,5000,77,1)X(120,10000,77,3)X(108,50000,120,1)X(99,100000,120,3)X(100,500000,99,1)X(109,1000000,99,3)string w;while(cin>>w){try{stringstream s(w);U c;while(s>>c);cout<<c<<"\n";}catch(int x){cout<<"0\n";}}}

It could be compressed further.

> ./a.exe
III
3
IIII
0
XVI
16
(C)(D)(L)MMI
452001

Slightly nicer formatting: 1582 char

#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;

typedef map<char,int>      R;

R     D,P,M;

struct U
{
    U(): t(0), l(0), a(0) {}

    int  t,l,a;

    operator int()
    {
        return t + l;
    }
    I& d(I& s)
    {
        char c,b;
        s >> c;
        if (c == '(')
        {
            s >> c >> b;
            T(b != ')')
            c = tolower(c);
        }
        if (s)
        {
            R::iterator f = D.find(c);
            T(f == D.end())

            if (P[c] == l)
            {
                l = f->S - l;
                a = 0;
            }
            else
            {
                T(l&&(f->S > l))
                a=l==f->S?a+1:1;
                T(a>M[c])
                t   += l;
                l     = f->S;
            }
        }

        return s;
    }

};

I& operator>>(I& s,U& d)
{
    return d.d(s);
}

int main()
{
    D[' ']=-1;
    X(73,1,32,3)
    X(86,5,73,1)
    X(88,10,73,3)
    X(76,50,88,1)
    X(67,100,88,3)
    X(68,500,67,1)
    X(77,1000,67,3)
    X(118,5000,77,1)
    X(120,10000,77,3)
    X(108,50000,120,1)
    X(99,100000,120,3)
    X(100,500000,99,1)
    X(109,1000000,99,3)

    string w;
    while(cin >> w)
    {
        try
        {
            stringstream s(w);
            U    c;
            while(s >> c);
            cout << c << "\n";
        }
        catch(int x)
        {
            cout << "0\n";
        }
    }
}


问:
Shortest self-modifying code to wish a happy New Year!
Your code just has to print "Happy 2013".
However, if it detects that it's 2014, it has to modify itself (as a running process!!) and print "Happy 2014" instead.

By self-modifying I mean the running process must really modify itself: it should alter its own instructions while it is executing.

Shortest code wins.

-10% size bonus if it's general, so it works for 2015, etc.

Sorry if the task excludes some languages or systems where it's not possible...

答:
Befunge 98, 26 bytes - 10% (bonus) = 23.4

```<code>"EMIT"4(Yd0p"  yppaH"5k,.@
</code>```

The first space immediately after the quote gets overwritten with a unicode character with code point equal to the year.

The self-modifying part of this code actually makes it more verbose. The below code performs the same task without self-modification:

```<code>"EMIT"4(Y" yppaH"5k,.@
</code>```

Body:
Befunge 98, 26 bytes - 10% (bonus) = 23.4

"EMIT"4(Yd0p"  yppaH"5k,.@

The first space immediately after the quote gets overwritten with a unicode character with code point equal to the year.

The self-modifying part of this code actually makes it more verbose. The below code performs the same task without self-modification:

"EMIT"4(Y" yppaH"5k,.@


问:
Cat goes "Meow"

cat goes  "Meow"

We are all familiar with the concept of a cat program. The user types something in, it is echoed back to the user. Easy. But all cat programs I've seen so far have missed one fact: a cat goes "Meow". So your task is to write a program that copies all STDIN to STDOUT UNLESS the input is cat, in which case your program should output cat goes "Meow".

Scoring

This is code-golf, so your score is your byte count, with a few modifiers:

If your program works for any additional animals other than cat (e.g. cow: cow goes "Moo"), for each additional animal: -10

If your program doesn't use the word "cat": -15

If your program responds to fox with "What does the fox say": -25

Animals and sounds that go together:

cow goes moo
duck goes quack
sheep goes baa
bees go buzz
frogs go croak

Anything else on this list is allowed.

Rules

Standard loopholes apply

You must not write anything to STDERR

You can use single quotes/no quotes instead of double quotes.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 leaderboard snippet:

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

var QUESTION_ID=62500;var OVERRIDE_USER=46470;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Title: Cat goes "Meow"

Body:
Python 3, 44 - 15 = 29

i=input();print(i+' goes Meow'*(i=='ca''t'))


问:
Send a cosmic call
The cosmic call is a message sent into space in 1999 and 2003.
It's made of 23 127*127px monochrome bitmap images, as detailed here.

Your mission is to write a program that displays the entire 127*2921px message, either as a text (made of zeros, ones and line breaks) or as an image (drawn on screen or saved on disk). There will be two categories of winners: one for text output and one for image output.

All the tricks are permitted, except common loopholes.

It is allowed to output the 23 pages separately.

It is allowed to write up to 23 programs (like, one for each page) and sum their size to determine your score.

It is allowed to use up to 23 binary files alongside your program(s). Their weight is counted in your score.

The shortest code (in byte) wins.

At 1 bit per pixel, the image contains 127*127*23/8 = 46370 bytes + 7 bits of data. (warning: it's not allowed to output an extra zero if you store pixel values into 46371 bytes)

Trailing newline/space is allowed for the text output.

Visual output can not contain any black pixel besides the black pixels of the cosmic call. It can be drawn in one column (ordered correctly), or split in 23 images, or animated (like a gif), also ordered correctly.

Attachment: the text output, and the image output to reproduce:

答:
Pyth, 46381 bytes

For obvious reasons it cannot be posted here.

```<code>jc.BC"<too long>"127
</code>```

Sample.

Pastebin of hexdump of program.

Title: Send a cosmic call

Body:
Pyth, 46381 bytes

For obvious reasons it cannot be posted here.

jc.BC"<too long>"127

Sample.

Pastebin of hexdump of program.