答:
Haskell, 77 bytes

```<code>import Data.List
data S=L[S]deriving(Eq,Ord)
f(L x)=L$sort$f<$>x
a!b=f a==f b
</code>```

Title: Are the two sets equal

Body:
{}is the empty set. You may use () or [] if you choose.

We aren't going to rigorously define "set", but sets all satisfy the following properties:

Sets follow the usual mathematical structure. Here are some important points:

Sets are not ordered.

No set contains itself.

Elements are either in a set or not, this is boolean. Therefore set elements cannot have multiplicities (i.e. an element cannot be in a set multiple times.)

Elements of a set are also sets and {} is the only primitive element.

Task

Write a program/function that determines whether two sets are equal.

Input

Two valid sets via stdin or function argument.  The input format is loose within reason.

Some valid inputs are:

```<code>{} {{}}
{{},{{}}} {{{{{},{{}}}}}}
{{},{{},{{}}}} {{{},{{}}},{{{{{},{{}}}}}}}
</code>```

Invalid inputs:

```<code>{{} {}              Brackets will always be balanced.
{{},{}} {}          Set contains the same element twice
</code>```

Output

A truthy value if the inputs are equal, falsy otherwise.

Test cases

Your submission should answer correctly for all valid inputs, not just for the test cases. These may be updated at any point.

Truthy:

```<code>{} {}
{{},{{}}} {{{}},{}}
{{},{{},{{{}},{}}}} {{{{},{{}}},{}},{}}
</code>```

Falsy:

```<code>{} {{}}
{{},{{},{{{}},{}}}} {{{{}}},{},{{}}}
{{},{{}},{{{}}},{{},{{}}}} {}
</code>```

Scoring

code-golf

Additional Rules

An additional rule has been added banning unordered iterable types altogether. They are too common and trivialize this challenge far too much. Feel free to leave answers that violate this in place, please just make an indication that they were made before the rule change.

Body:
Haskell, 77 bytes

import Data.List
data S=L[S]deriving(Eq,Ord)
f(L x)=L$sort$f<$>x
a!b=f a==f b


问:
Reimplementing square root
Define a function, s, which takes a number and returns the square root.

No use of library functions, such as Java's Math.sqrt() or PHP's built in sqrt(), allowed.

答:
Python - 11 chars

Technically not a library function :)

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

As a function it's 16 chars

```<code>f=lambda x:x**.5
</code>```

ContentLicense: CC BY-SA 2.5

Title: Reimplementing square root

Body:
Python - 11 chars

Technically not a library function :)

input()**.5

As a function it's 16 chars

f=lambda x:x**.5


问:
Finding "sub-palindromes".
The shortest code that finds all unique "sub-palindromes" of a string, that is: any substring with length > 1 that is a palindrome.

eg.1

```<code>input: "12131331"
output: "33", "121", "131", "313", "1331"
</code>```

eg.2

```<code>input: "3333"
output: "33", "333", "3333"
</code>```

答:
Haskell 98, 88 <s>91</s> <s>96</s>

```<code>import List
main=interact$show.filter(\x->length x>1&&x==reverse x).nub.(tails=<<).inits
</code>```

Title: Finding "sub-palindromes".

Body:
Haskell 98, 88 <s>91</s> <s>96</s>

import List
main=interact$show.filter(\x->length x>1&&x==reverse x).nub.(tails=<<).inits


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

ContentLicense: CC BY-SA 4.0

Title: Approximation of e

Body:
dc, 43 bytes

[d1-d1<f*]sf[dlfx1r/r1-d1<e+]se1?dk1-d1<e+p

This is a fairly direct translation of the series.  I tried to be cleverer, but that resulted in longer code.

Explanation

[d1-d1<f*]sf

A simple factorial function, for n>0

[dlfx1r/r1-d1<e+]se

Execute the factorial for n,...,1; invert and sum

1?dk1-

Prime the stack with 1; accept input and set an appropriate precision

d1<e+

If input was 0 or 1, we can just pass it on, else compute the partial sum.

p

Print the result.

Test results

The first 100 expansions:

0
1
2
2.500
2.6666
2.70832
2.716665
2.7180553
2.71825394
2.718278766
2.7182815251
2.71828180110
2.718281826194
2.7182818282857
2.71828182844671
2.718281828458223
2.7182818284589936
2.71828182845904216
2.718281828459045062
2.7182818284590452257
2.71828182845904523484
2.718281828459045235331
2.7182818284590452353584
2.71828182845904523536012
2.718281828459045235360273
2.7182818284590452353602862
2.71828182845904523536028736
2.718281828459045235360287457
2.7182818284590452353602874700
2.71828182845904523536028747123
2.718281828459045235360287471339
2.7182818284590452353602874713514
2.71828182845904523536028747135253
2.718281828459045235360287471352649
2.7182818284590452353602874713526606
2.71828182845904523536028747135266232
2.718281828459045235360287471352662481
2.7182818284590452353602874713526624964
2.71828182845904523536028747135266249759
2.718281828459045235360287471352662497738
2.7182818284590452353602874713526624977552
2.71828182845904523536028747135266249775705
2.718281828459045235360287471352662497757231
2.7182818284590452353602874713526624977572453
2.71828182845904523536028747135266249775724691
2.718281828459045235360287471352662497757247074
2.7182818284590452353602874713526624977572470919
2.71828182845904523536028747135266249775724709352
2.718281828459045235360287471352662497757247093683
2.7182818284590452353602874713526624977572470936984
2.71828182845904523536028747135266249775724709369978
2.718281828459045235360287471352662497757247093699940
2.7182818284590452353602874713526624977572470936999574
2.71828182845904523536028747135266249775724709369995936
2.718281828459045235360287471352662497757247093699959554
2.7182818284590452353602874713526624977572470936999595729
2.71828182845904523536028747135266249775724709369995957475
2.718281828459045235360287471352662497757247093699959574944
2.7182818284590452353602874713526624977572470936999595749646
2.71828182845904523536028747135266249775724709369995957496673
2.718281828459045235360287471352662497757247093699959574966943
2.7182818284590452353602874713526624977572470936999595749669652
2.71828182845904523536028747135266249775724709369995957496696740
2.718281828459045235360287471352662497757247093699959574966967601
2.7182818284590452353602874713526624977572470936999595749669676254
2.71828182845904523536028747135266249775724709369995957496696762747
2.718281828459045235360287471352662497757247093699959574966967627699
2.7182818284590452353602874713526624977572470936999595749669676277220
2.71828182845904523536028747135266249775724709369995957496696762772386
2.718281828459045235360287471352662497757247093699959574966967627724050
2.7182818284590452353602874713526624977572470936999595749669676277240739
2.71828182845904523536028747135266249775724709369995957496696762772407632
2.718281828459045235360287471352662497757247093699959574966967627724076601
2.7182818284590452353602874713526624977572470936999595749669676277240766277
2.71828182845904523536028747135266249775724709369995957496696762772407663006
2.718281828459045235360287471352662497757247093699959574966967627724076630325
2.7182818284590452353602874713526624977572470936999595749669676277240766303508
2.71828182845904523536028747135266249775724709369995957496696762772407663035328
2.718281828459045235360287471352662497757247093699959574966967627724076630353518
2.7182818284590452353602874713526624977572470936999595749669676277240766303535449
2.71828182845904523536028747135266249775724709369995957496696762772407663035354729
2.718281828459045235360287471352662497757247093699959574966967627724076630353547565
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475915
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759429
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594542
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945681
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457111
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571352
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713792
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138185
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382143
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821752
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217826
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178492
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785218
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852481
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525131
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251635
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516607
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166394

Using 1000 terms:

2.7182818284590452353602874713526624977572470936999595749669676277240\
766303535475945713821785251664274274663919320030599218174135966290435\
729003342952605956307381323286279434907632338298807531952510190115738\
341879307021540891499348841675092447614606680822648001684774118537423\
454424371075390777449920695517027618386062613313845830007520449338265\
602976067371132007093287091274437470472306969772093101416928368190255\
151086574637721112523897844250569536967707854499699679468644549059879\
316368892300987931277361782154249992295763514822082698951936680331825\
288693984964651058209392398294887933203625094431173012381970684161403\
970198376793206832823764648042953118023287825098194558153017567173613\
320698112509961818815930416903515988885193458072738667385894228792284\
998920868058257492796104841984443634632449684875602336248270419786232\
090021609902353043699418491463140934317381436405462531520961836908887\
070167683964243781405927145635490613031072085103837505101157477041718\
986106873969655212671546889570350116

ContentLicense: CC BY-SA 3.0


问:
Leyland Numbers
Given a natural number \$n\$, return the \$n\$-th Leyland number.

Leyland Number

Leyland numbers are positive integers \$k\$ of the form

$$k = x^y + y^x$$

Where \$x\$ and \$y\$ are integers strictly greater than 1.

They are enumerated in ascending order.

EDIT: @DigitalTrauma suggested I include following "definition":

Imagine we throw \$x^y+y^x\$ in a bag for all possible values of \$x\$ and \$y\$, and avoid throwing in duplicates. Then we sort that bag. The sorted bag is our sequence.

Details

You may use 0 or 1 based indexing, whatever suits you best.

Your program must be able to output at least all Leyland numbers less than the maximum of signed 32-bit integers. (The last Leyland number below this limit is 1996813914, at index 82.)

Test cases

The first few terms are following:

```<code>8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124
</code>```

A076980 in OEIS, except for the first entry. Note that because of that additional first entry, the indices on OEIS are shifted by one.

More can be found in the OEIS b-file

答:
Bash + GNU utilities, 63

printf %s\\n x={2..32}\;y={2..32}\;x^y+y^x|bc|sort -nu|sed $1!d
```

1-based indexing.  It looks like this is pretty much the same approach as @TimmyD's answer.  Instead of nested loops, bash brace expansion is used to generate arithmetic expressions that are piped to bc for evaluation.

Ideone.

Title: Leyland Numbers

Body:
Bash + GNU utilities, 63

printf %s\\n x={2..32}\;y={2..32}\;x^y+y^x|bc|sort -nu|sed $1!d

1-based indexing.  It looks like this is pretty much the same approach as @TimmyD's answer.  Instead of nested loops, bash brace expansion is used to generate arithmetic expressions that are piped to bc for evaluation.

Ideone.


问:
Find operations required to get result
So task is simple, given array of numbers and result, you need to find what operations you need to use on numbers from array , to obtain requested result.

Let's make it simple for start, and allow only basic operations such as: addition, subtraction, multiplication and division.

Example:

```<code>Input  : [5,5,5,5,5] 100
Output : 5*5*5-5*5
</code>```

To give some advantage to languages like Java, request is to implement function, not entire program, and result can be return via parameter or print to console.

Code is scored based on amount bytes, and as it's golf code challenge, lowest score wins.

Another requirment is <s>You can get additional -10 points</s> if for array contains only digids, support solutions where you could construct numbers from following digits.
Ie

```<code>Input  : [1,2,3,4,5] 0
Output : 12-3-4-5
</code>```

Note that, provided outputs are proposed outputs, some cases might have more than one solution. It's up to you will you provide one or more solutions for given task.

EDIT:
Result has to be valid from mathematical point of view, hence division is rational division, not integer, and operation precedence is same as in classical math (first multiplication and division then addition and subtraction).

答:
Matlab, 234 238 258 bytes

I'm assuming based on the limitations of the other answers that the number order of the input array is maintained by fiat.

```<code>n=length(x)-1
k=n*2+2
p=unique(nchoosek(repmat('*-+/',1,n),n),'rows')
p=[p char(' '*~~p(:,1))]'
c=char(x'*~~p(1,:))
o=p(:,r==cellfun(@eval,mat2cell(reshape([c(:) p(:)]',k,[]),k,0|p(1,:))))
reshape([repmat(x',size(o,2),1) o(:)]',k,[])'
</code>```

This code takes a string of numbers x, say x = '12345' and a result r, say r = 15 and returns all of the strings of expressions you can evaluate to get r from x using the four operators.

I've used two different length-equivalent ways of avoiding using ones(length())-type or repmat(length())-type expressions: ~~p(1,:) which returns not-not values in p (i.e., a list of 1s the samelength as the first dimension of p) and 0|p(:,1) which returns 0 or is-there-a-value-in-p (i.e., a list of 1s the same length as the second dimension of p).

Matlab doesn't have an nchoosek with replacement method, so I've duplicated the operators the correct number of times, computed the whole space of nchoosek for that larger selection of operators, and then used a unique call to pare the result down to what it should be (removing equivalent combinations like '***+' and '***+'). I add a trailing space to match the length of the input vector for concatenation purposes and then compose the operator strings with the input strings into the columns of a matrix. I then evaluate the expressions columnwise to get results and find the order of operators that corresponds to those columns with results that match our input r.

Test: x = '12345', r = 15:

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

If I had to take an array of double precision values, I'd need x = num2str(x,'%d'); in order to convert the digits to a string, adding 21 (20 without the ;) to my score. *The extra bytes were semicolons I left in purely so that anyone running this code won't see their command prompt blow up with long arrays. Since my edit produces a giant pile of warnings about logicals and colon-operands now anyway, I've removed the semicolons in the new version.

Edit 2: Forgot to replace a 2*n+2 with k.

Old answer:

```<code>n=length(x)-1;
p=unique(nchoosek(repmat(['*','-','+','/'],1,n),n),'rows');
l=length(p);
p=[p repmat(' ',l,1)]';
c=reshape([repmat(x',l,1) p(:)]',n*2+2,[]);
o = p(:,r == cellfun(@eval, mat2cell(c,n*2+2,ones(l,1))));
reshape([repmat(x',size(o,2),1) o(:)]',n*2+2,[])'
</code>```

Title: Find operations required to get result

Body:
Matlab, 234 238 258 bytes

I'm assuming based on the limitations of the other answers that the number order of the input array is maintained by fiat.

n=length(x)-1
k=n*2+2
p=unique(nchoosek(repmat('*-+/',1,n),n),'rows')
p=[p char(' '*~~p(:,1))]'
c=char(x'*~~p(1,:))
o=p(:,r==cellfun(@eval,mat2cell(reshape([c(:) p(:)]',k,[]),k,0|p(1,:))))
reshape([repmat(x',size(o,2),1) o(:)]',k,[])'

This code takes a string of numbers x, say x = '12345' and a result r, say r = 15 and returns all of the strings of expressions you can evaluate to get r from x using the four operators.

I've used two different length-equivalent ways of avoiding using ones(length())-type or repmat(length())-type expressions: ~~p(1,:) which returns not-not values in p (i.e., a list of 1s the samelength as the first dimension of p) and 0|p(:,1) which returns 0 or is-there-a-value-in-p (i.e., a list of 1s the same length as the second dimension of p).

Matlab doesn't have an nchoosek with replacement method, so I've duplicated the operators the correct number of times, computed the whole space of nchoosek for that larger selection of operators, and then used a unique call to pare the result down to what it should be (removing equivalent combinations like '***+' and '***+'). I add a trailing space to match the length of the input vector for concatenation purposes and then compose the operator strings with the input strings into the columns of a matrix. I then evaluate the expressions columnwise to get results and find the order of operators that corresponds to those columns with results that match our input r.

Test: x = '12345', r = 15:

1*2*3+4+5
1+2+3+4+5
1-2*3+4*5

If I had to take an array of double precision values, I'd need x = num2str(x,'%d'); in order to convert the digits to a string, adding 21 (20 without the ;) to my score. *The extra bytes were semicolons I left in purely so that anyone running this code won't see their command prompt blow up with long arrays. Since my edit produces a giant pile of warnings about logicals and colon-operands now anyway, I've removed the semicolons in the new version.

Edit 2: Forgot to replace a 2*n+2 with k.

Old answer:

n=length(x)-1;
p=unique(nchoosek(repmat(['*','-','+','/'],1,n),n),'rows');
l=length(p);
p=[p repmat(' ',l,1)]';
c=reshape([repmat(x',l,1) p(:)]',n*2+2,[]);
o = p(:,r == cellfun(@eval, mat2cell(c,n*2+2,ones(l,1))));
reshape([repmat(x',size(o,2),1) o(:)]',n*2+2,[])'


问:
Integer square root of integer
Problem:

In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.

Test cases:

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

```<code>               INPUT ⟶ OUTPUT

                   0 ⟶  0
                   1 ⟶  1
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   8 ⟶  2
                   9 ⟶  3
                  15 ⟶  3
                  16 ⟶  4
               65535 ⟶ 255
               65536 ⟶ 256
18446744073709551615 ⟶ 4294967295
</code>```

Rules:

You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)

Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).

You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying return (n>0)?(uint32_t)sqrtl(n):-1; in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use *, /, +, -, and exponentiation (e.g., ** or ^ if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1). This restriction is to prevent "cheating" by calling sqrt() or a variant or raising a value to the ½ power.

If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.

If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., uint64_t and uint32_t as defined in stdint.h. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.

If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!

Have fun and get creative!

答:
JavaScript (ES6) 61 bytes

```<code>n=>n&&eval('g=n;while(Math.abs(g-(g=(n/g+g)/2))>1e-9);g-g%1')
</code>```

Tests:

f=n=>n&&eval('g=n;while(Math.abs(g-(g=(n/g+g)/2))>1e-9);g-g%1')

console.log(f(0) == 0);
console.log(f(1) == 1);
console.log(f(2) == 1);
console.log(f(3) == 1);
console.log(f(4) == 2);
console.log(f(8) == 2);
console.log(f(9) == 3);
console.log(f(15) == 3);
console.log(f(16) == 4);
console.log(f(65535) == 255);
console.log(f(65536) == 256);
console.log(f(18446744073709551615) == 4294967296);```
</div>
</div>
</p>

<p>I hope you can excuse the last test, since JavaScript interprets the literal value <code>18446744073709551615</code> as <code>18446744073709552000</code>. This is because JavaScript uses the IEEE 754 standard, which can only store every consecutive positive integer up to <code>9007199254740992</code> (2^53).</p>

<p>An alternative method that's even shorter is below. However, it does not meet the speed optimization requirements:</p>

<h3>JavaScript (ES6) 30 bytes (non-competing)</h3>

```n=>eval('for(a=0;a*a<=n;)a++')
```

<h2>Tests:</h2>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=n=>eval('for(a=0;a*a<=n;)a++')

console.log(f(0) == 0);
console.log(f(1) == 1);
console.log(f(2) == 1);
console.log(f(3) == 1);
console.log(f(4) == 2);
console.log(f(8) == 2);
console.log(f(9) == 3);
console.log(f(15) == 3);
console.log(f(16) == 4);
console.log(f(65535) == 255);
console.log(f(65536) == 256);
// console.log(f(18446744073709551615) == 4294967296)

f=n=>eval('for(a=4294967290;a*a<=n;)a++')

console.log(f(18446744073709551615) == 4294967296);</code>```

The last test case hypothetically evaluates to true, but would take around a month to execute.

Title: Integer square root of integer

Body:
JavaScript (ES6) 61 bytes

n=>n&&eval('g=n;while(Math.abs(g-(g=(n/g+g)/2))>1e-9);g-g%1')

Tests:

f=n=>n&&eval('g=n;while(Math.abs(g-(g=(n/g+g)/2))>1e-9);g-g%1')

console.log(f(0) == 0);
console.log(f(1) == 1);
console.log(f(2) == 1);
console.log(f(3) == 1);
console.log(f(4) == 2);
console.log(f(8) == 2);
console.log(f(9) == 3);
console.log(f(15) == 3);
console.log(f(16) == 4);
console.log(f(65535) == 255);
console.log(f(65536) == 256);
console.log(f(18446744073709551615) == 4294967296);

I hope you can excuse the last test, since JavaScript interprets the literal value 18446744073709551615 as 18446744073709552000. This is because JavaScript uses the IEEE 754 standard, which can only store every consecutive positive integer up to 9007199254740992 (2^53).

An alternative method that's even shorter is below. However, it does not meet the speed optimization requirements:

JavaScript (ES6) 30 bytes (non-competing)

n=>eval('for(a=0;a*a<=n;)a++')

Tests:

f=n=>eval('for(a=0;a*a<=n;)a++')

console.log(f(0) == 0);
console.log(f(1) == 1);
console.log(f(2) == 1);
console.log(f(3) == 1);
console.log(f(4) == 2);
console.log(f(8) == 2);
console.log(f(9) == 3);
console.log(f(15) == 3);
console.log(f(16) == 4);
console.log(f(65535) == 255);
console.log(f(65536) == 256);
// console.log(f(18446744073709551615) == 4294967296)

f=n=>eval('for(a=4294967290;a*a<=n;)a++')

console.log(f(18446744073709551615) == 4294967296);

The last test case hypothetically evaluates to true, but would take around a month to execute.


答:
MATLAB, 58 bytes

1-indexed

```<code>n=input('');[A B]=ndgrid(2:n+9);k=A.^B;x=unique(k'+k);x(n)
</code>```

unique in MATLAB flattens and sorts the matrix.

Thanks for help to @FryAmTheEggman and @flawr.

Title: Leyland Numbers

Body:
Given a natural number \$n\$, return the \$n\$-th Leyland number.

Leyland Number

Leyland numbers are positive integers \$k\$ of the form

$$k = x^y + y^x$$

Where \$x\$ and \$y\$ are integers strictly greater than 1.

They are enumerated in ascending order.

EDIT: @DigitalTrauma suggested I include following "definition":

Imagine we throw \$x^y+y^x\$ in a bag for all possible values of \$x\$ and \$y\$, and avoid throwing in duplicates. Then we sort that bag. The sorted bag is our sequence.

Details

You may use 0 or 1 based indexing, whatever suits you best.

Your program must be able to output at least all Leyland numbers less than the maximum of signed 32-bit integers. (The last Leyland number below this limit is 1996813914, at index 82.)

Test cases

The first few terms are following:

```<code>8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124
</code>```

A076980 in OEIS, except for the first entry. Note that because of that additional first entry, the indices on OEIS are shifted by one.

More can be found in the OEIS b-file

Body:
MATLAB, 58 bytes

1-indexed

n=input('');[A B]=ndgrid(2:n+9);k=A.^B;x=unique(k'+k);x(n)

unique in MATLAB flattens and sorts the matrix.

Thanks for help to @FryAmTheEggman and @flawr.


问:
Golf the Sequence whose Exponential Generating Function is tangent
Almost every function can be expressed as a polynomial with infinite terms.

For example, e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...

For example, sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...

The coefficients of the n-th terms form a sequence, and the corresponding function is called the Generating Function of the sequence.

The coefficients of the n-th terms form a sequence.

Often, the n-th term would have a denominator of n!. Therefore, we multiply the coefficient by n! to obtain another sequence, whose Exponential Generating Function would be the original function.

For example, the sequence whose Exponential Generating Function is e^x would be 1,1,1,1,....

For example, the sequence whose Exponential Generating Function is sin(x) would be 0,1,0,-1,0,1,0,-1,....

Task

Your task is to find the n-th term of the sequence whose Exponential Generating Function is tan(x).

Testcases

```<code>n result
0 0
1 1
2 0
3 2
4 0
5 16
6 0
7 272
8 0
9 7936
10 0
11 353792
12 0
13 22368256
14 0
15 1903757312
16 0
17 209865342976
18 0
19 29088885112832
20 0
21 4951498053124096
22 0
23 1015423886506852352
24 0
25 246921480190207983616
26 0
</code>```

(Copied from here.) (Warning: the 0-th term is different)

Example implementation

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L16
def memoized(f):
    memo = {}
    def m_fun(*args):
        if args in memo:
            return memo[args]
        else:
            res = f(*args)
            memo[args] = res
            return res
    return m_fun

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L169
@memoized
def binomial(n,r):
    if r > n:
        return 0
    elif r==n:
        return 1
    res = 1
    i = 1
    while i<=r:
        res *= (n+1-i)
        res /= i
        i+=1
    return int(res)

# 2*u(n+1) = Sum_{k=0..n} binomial(n, k)*u(k)*u(n-k)
# from A000111
@memoized
def u(n):
    if n<0: return 0
    if n==0: return 1
    if n==1: return 1
    return sum([binomial(n-1,k)*u(k)*u(n-1-k) for k in range(n)])//2

def t(n):
    if n%2 == 0: return 0
    return u(n)

print('\n'.join([str(x) + ' ' + str(t(x)) for x in range(26)]))
```

Ideone it!

References

Generating function on Wikipedia

Exponential generating function on Wikipedia

Exponential generating function example on Wikipedia

Generating function on MathWorld

Exponential generating function on MathWorld

Taylor series on Wikipedia

Derivation of first 9 terms of required sequence

Obligatory OEIS A009006 (Note that the 0-th term is different)

Algorithm

OEIS A000111: up/down numbers

答:
Haskell, <s>95</s> 93 bytes

p=product
f n=sum[(-1)^(n`div`2+j+1)*j^n*p[k-j+1..n+1]`div`p[1..n+1-k+j]|k<-[1..n],j<-[0..k]]
```

It is basically an implementation of the general formula with some minor optimizations.

Body:
Haskell, <s>95</s> 93 bytes

p=product
f n=sum[(-1)^(n`div`2+j+1)*j^n*p[k-j+1..n+1]`div`p[1..n+1-k+j]|k<-[1..n],j<-[0..k]]

It is basically an implementation of the general formula with some minor optimizations.


问:
Fibonacci + Fizz Buzz = Fibo Nacci!
Fibonacci + FizzBuzz = Fibo Nacci!

Your challenge is to create a Fibo Nacci program!

A Fibo Nacci program outputs the first 100 Fibonacci numbers (starting from 1).

If the Fibonacci number is divisible by both 2 and 3 (i.e. it is divisible by 6), then output FiboNacci instead of the number.

Otherwise, if the Fibonacci number is divisible by 2, then output Fibo instead of the number.

Otherwise, if the Fibonacci number is divisible by 3, then output Nacci instead of the number.

Rules

The program should take no input.

The program should output a new line (\n) after every entry.

The program should not print anything to STDERR.

The program must output the first 100 Fibo Nacci entries (starting from 1).

Standard loopholes are not allowed (by default).

This is code-golf so shortest code in bytes wins!

Here is the expected output:

```<code>1
1
Fibo
Nacci
5
Fibo
13
Nacci
Fibo
55
89
FiboNacci
233
377
Fibo
Nacci
1597
Fibo
4181
Nacci
Fibo
17711
28657
FiboNacci
75025
121393
Fibo
Nacci
514229
Fibo
1346269
Nacci
Fibo
5702887
9227465
FiboNacci
24157817
39088169
Fibo
Nacci
165580141
Fibo
433494437
Nacci
Fibo
1836311903
2971215073
FiboNacci
7778742049
12586269025
Fibo
Nacci
53316291173
Fibo
139583862445
Nacci
Fibo
591286729879
956722026041
FiboNacci
2504730781961
4052739537881
Fibo
Nacci
17167680177565
Fibo
44945570212853
Nacci
Fibo
190392490709135
308061521170129
FiboNacci
806515533049393
1304969544928657
Fibo
Nacci
5527939700884757
Fibo
14472334024676221
Nacci
Fibo
61305790721611591
99194853094755497
FiboNacci
259695496911122585
420196140727489673
Fibo
Nacci
1779979416004714189
Fibo
4660046610375530309
Nacci
Fibo
19740274219868223167
31940434634990099905
FiboNacci
83621143489848422977
135301852344706746049
Fibo
Nacci
</code>```

The Catalogue

The <s>Snack</s> 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>```

/* Configuration */

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

/* App */

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

function answersUrl(index) {
  return "http://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 "http://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: 290px;
  float: left;
}

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

table thead {
  font-weight: bold;
}

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

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/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

```

答:
Python 3, 137 bytes

Fun question with lots of new things I learnt in doing it. Python3 isn't a golfing language, but I suppose this isn't too bad

```<code>f=lambda n:n if n<2 else f(n-2)+f(n-1)
for n in range(100):t=f(-~n);x="Fibo"*(t%2==0)+"Nacci"*(t%3==0);print(x if t%2==0 or t%3==0 else t)
</code>```

Hardest part was just to get it to only print the number

First line calculates the nth fib number. Second line joins Fibo and Nacci if it fits the rules an then it prints that string if it should else print the nth fib number.

Title: Fibonacci + Fizz Buzz = Fibo Nacci!

Body:
Python 3, 137 bytes

Fun question with lots of new things I learnt in doing it. Python3 isn't a golfing language, but I suppose this isn't too bad

f=lambda n:n if n<2 else f(n-2)+f(n-1)
for n in range(100):t=f(-~n);x="Fibo"*(t%2==0)+"Nacci"*(t%3==0);print(x if t%2==0 or t%3==0 else t)

Hardest part was just to get it to only print the number

First line calculates the nth fib number. Second line joins Fibo and Nacci if it fits the rules an then it prints that string if it should else print the nth fib number.


答:
Haskell, 52 bytes

r=[2..31]
([k|k<-[0..],elem k[x^y+y^x|x<-r,y<-r]]!!)
```

<p>Really inefficient. Tests each natural number for being a Leyland number, making an infinite list of those that are. Given an input, takes that index element of the list. Uses that only <code>x,y</code> up to 31 need to be checked for 32 bit integers. </p>

<p>Same length with <code>filter</code>:</p>

<pre class="lang-haskell prettyprint-override"><code>r=[2..31]
(filter(`elem`[x^y+y^x|x<-r,y<-r])[0..]!!)
</code>```

Title: Leyland Numbers

Body:
Haskell, 52 bytes

r=[2..31]
([k|k<-[0..],elem k[x^y+y^x|x<-r,y<-r]]!!)

Really inefficient. Tests each natural number for being a Leyland number, making an infinite list of those that are. Given an input, takes that index element of the list. Uses that only x,y up to 31 need to be checked for 32 bit integers.

Same length with filter:

r=[2..31]
(filter(`elem`[x^y+y^x|x<-r,y<-r])[0..]!!)


答:
C#, <s>141</s>, 127 bytes.

Oh c#, you are such a long language.

```<code>n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).Distinct().ToList()[n];
</code>```

This is a lambda that needs to be assigned to delegate double del(int n); to be run, as such:

```<code>delegate double del(int n);
del f=n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).OrderBy(q=>q).Distinct().ToList()[n];
</code>```

Title: Leyland Numbers

Body:
C#, <s>141</s>, 127 bytes.

Oh c#, you are such a long language.

n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).Distinct().ToList()[n];

This is a lambda that needs to be assigned to delegate double del(int n); to be run, as such:

delegate double del(int n);
del f=n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).OrderBy(q=>q).Distinct().ToList()[n];


答:
Python 3, 129->116 bytes

I know there is a shorter python 3 answer, but I still wanted to contribute my solution.

t=[]
for k in range(100):a,b,q=k//10,k%10,a**b+b**a;f=lambda q:0if q in t else t.append(q);f(q)
print(sorted(t)[7:])
```

This was the best way that I could to think of to handle going through all values for x and all values for y.
If anyone can golf my approach it would be appreciated

Title: Leyland Numbers

Body:
Python 3, 129->116 bytes

I know there is a shorter python 3 answer, but I still wanted to contribute my solution.

t=[]
for k in range(100):a,b,q=k//10,k%10,a**b+b**a;f=lambda q:0if q in t else t.append(q);f(q)
print(sorted(t)[7:])

This was the best way that I could to think of to handle going through all values for x and all values for y.
If anyone can golf my approach it would be appreciated


答:
CJam (33 32 27 26 23 20 bytes)

```<code>2,{ee::*_(@+.+}ri*0=
</code>```

Online demo

Dissection

This essentially implements the recurrence described by xnor.

```<code>2,        e# [0 1] represents the base case f(0,j) = j==1
{         e# Loop...
  ee::*   e#   Multiply each array element by its index
  _(@+.+  e#   Sum the array shifted left and the array shifted right
}ri*      e# ... n times
0=        e# Evaluate at j=0
</code>```

Or with a rather different approach, for 23 bytes:

```<code>ri_1&a{{1$+}*]W%0+}@*0=
</code>```

Online demo. Thanks to Dennis for 3 bytes.

Dissection

```<code>1a         e# Push [1]
{          e# Repeat...
  {1$+}*]  e#   Compute array of partial sums
  W%0+     e#   Reverse and append 0
}qi:A*     e# ... A times, where A is the input value
0=A1&*     e# Result is first element if A odd, and 0 otherwise
</code>```

Or with a very different approach, for 29 bytes:

```<code>qie!Ma-{W\+W+3ew{_$.=1=},!},,
</code>```

Online demo

Unfortunately a special case is required for input 0.

Dissection

```<code>qi            e# Take an integer n from stdin
e!            e#   Compute all permutations of [0 ... n-1]
Ma-           e#   Special-case n=0
{             e#   Filter...
  W\+W+       e#     Prepend and postpend -1
  3ew         e#     Take slices of 3 consecutive elements
  {           e#     Filter...
    _$.=1=    e#       Test whether the middle element is the second largest
  },!         e#     ... and require no matches
},,           e#   ... and count
</code>```

You may be thinking "WTF?! He's answering the wrong question." If so, that's understandable, but both approaches do indeed give the correct results.

Title: Golf the Sequence whose Exponential Generating Function is tangent

Body:
Almost every function can be expressed as a polynomial with infinite terms.

For example, e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...

For example, sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...

The coefficients of the n-th terms form a sequence, and the corresponding function is called the Generating Function of the sequence.

The coefficients of the n-th terms form a sequence.

Often, the n-th term would have a denominator of n!. Therefore, we multiply the coefficient by n! to obtain another sequence, whose Exponential Generating Function would be the original function.

For example, the sequence whose Exponential Generating Function is e^x would be 1,1,1,1,....

For example, the sequence whose Exponential Generating Function is sin(x) would be 0,1,0,-1,0,1,0,-1,....

Task

Your task is to find the n-th term of the sequence whose Exponential Generating Function is tan(x).

Testcases

```<code>n result
0 0
1 1
2 0
3 2
4 0
5 16
6 0
7 272
8 0
9 7936
10 0
11 353792
12 0
13 22368256
14 0
15 1903757312
16 0
17 209865342976
18 0
19 29088885112832
20 0
21 4951498053124096
22 0
23 1015423886506852352
24 0
25 246921480190207983616
26 0
</code>```

(Copied from here.) (Warning: the 0-th term is different)

Example implementation

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L16
def memoized(f):
    memo = {}
    def m_fun(*args):
        if args in memo:
            return memo[args]
        else:
            res = f(*args)
            memo[args] = res
            return res
    return m_fun

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L169
@memoized
def binomial(n,r):
    if r > n:
        return 0
    elif r==n:
        return 1
    res = 1
    i = 1
    while i<=r:
        res *= (n+1-i)
        res /= i
        i+=1
    return int(res)

# 2*u(n+1) = Sum_{k=0..n} binomial(n, k)*u(k)*u(n-k)
# from A000111
@memoized
def u(n):
    if n<0: return 0
    if n==0: return 1
    if n==1: return 1
    return sum([binomial(n-1,k)*u(k)*u(n-1-k) for k in range(n)])//2

def t(n):
    if n%2 == 0: return 0
    return u(n)

print('\n'.join([str(x) + ' ' + str(t(x)) for x in range(26)]))
```

Ideone it!

References

Generating function on Wikipedia

Exponential generating function on Wikipedia

Exponential generating function example on Wikipedia

Generating function on MathWorld

Exponential generating function on MathWorld

Taylor series on Wikipedia

Derivation of first 9 terms of required sequence

Obligatory OEIS A009006 (Note that the 0-th term is different)

Algorithm

OEIS A000111: up/down numbers

Body:
CJam (33 32 27 26 23 20 bytes)

2,{ee::*_(@+.+}ri*0=

Online demo

Dissection

This essentially implements the recurrence described by xnor.

2,        e# [0 1] represents the base case f(0,j) = j==1
{         e# Loop...
  ee::*   e#   Multiply each array element by its index
  _(@+.+  e#   Sum the array shifted left and the array shifted right
}ri*      e# ... n times
0=        e# Evaluate at j=0

Or with a rather different approach, for 23 bytes:

ri_1&a{{1$+}*]W%0+}@*0=

Online demo. Thanks to Dennis for 3 bytes.

Dissection

1a         e# Push [1]
{          e# Repeat...
  {1$+}*]  e#   Compute array of partial sums
  W%0+     e#   Reverse and append 0
}qi:A*     e# ... A times, where A is the input value
0=A1&*     e# Result is first element if A odd, and 0 otherwise

Or with a very different approach, for 29 bytes:

qie!Ma-{W\+W+3ew{_$.=1=},!},,

Online demo

Unfortunately a special case is required for input 0.

Dissection

qi            e# Take an integer n from stdin
e!            e#   Compute all permutations of [0 ... n-1]
Ma-           e#   Special-case n=0
{             e#   Filter...
  W\+W+       e#     Prepend and postpend -1
  3ew         e#     Take slices of 3 consecutive elements
  {           e#     Filter...
    _$.=1=    e#       Test whether the middle element is the second largest
  },!         e#     ... and require no matches
},,           e#   ... and count

You may be thinking "WTF?! He's answering the wrong question." If so, that's understandable, but both approaches do indeed give the correct results.


Body:
JavaScript (ES6), <s>127</s> 45 bytes

f=(n,m=0)=>n?++m*f(--n,m--)+--m*f(n,m):m-1?0:1

Port of @xnor's solutions.


Title: Leyland Numbers

Body:
Perl 6, <s> 60 58 </s> 56 bytes

<s>{sort(keys bag [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}
{sort(keys set [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}
{sort(unique [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}
{squish(sort [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}</s>
{squish(sort [X[&({$^a**$^b+$b**$a})]] (2..31)xx 2)[$_]}
{squish(sort [X[&({$^a**$^b+$b**$a})]] 2..31,2..31)[$_]}

Test:

#! /usr/bin/env perl6
use v6.c;

my &Leyland = {squish(sort [X[&({$^a**$^b+$b**$a})]] 2..31,2..31)[$_]}

say ^14 .map: &Leyland;
time-this {Leyland 81};

sub time-this (&code) {
  my $start = now;
  my $value = code();
  printf "takes %.3f seconds to come up with $value\n", now - $start;
}

(8 17 32 54 57 100 145 177 320 368 512 593 945 1124)
takes 0.107 seconds to come up with 1996813914

Explanation:

{
  squish( # remove repeated values
    sort
      [X[&( # cross reduce with:
        { $^a ** $^b + $b ** $a }
      )]]
        ( 2 .. $_+2 ) # ｢Range.new(2,$_+2)｣ (inclusive range)
        xx 2          # repeat list
  )[$_]
}


答:
F#, <s>117</s>, 104

Welp, it's shorter than my C# answer at least.

Saved 13 bytes thanks to Reed Copsey in the F# chatroom.

```<code>let f n=[for x in 2I..32I do for y in 2I..32I->x**(int y)+y**(int x)]|>Seq.sort|>Seq.distinct|>Seq.nth n
</code>```

Title: Leyland Numbers

Body:
F#, <s>117</s>, 104

Welp, it's shorter than my C# answer at least.

Saved 13 bytes thanks to Reed Copsey in the F# chatroom.

let f n=[for x in 2I..32I do for y in 2I..32I->x**(int y)+y**(int x)]|>Seq.sort|>Seq.distinct|>Seq.nth n


答:
Mathematica, 20 bytes

```<code>Tan@x~D~{x,#}/.x->0&
</code>```

Straight-forward approach. Calculate the nth derivative of tan(x) and evaluate it at x = 0.

Usage

Body:
Mathematica, 20 bytes

Tan@x~D~{x,#}/.x->0&

Straight-forward approach. Calculate the nth derivative of tan(x) and evaluate it at x = 0.

Usage


答:
Haskell, 48 bytes

0%1=1
0%_=0
i%j=sum[k*(i-1)%k|k<-[j+1,j-1]]
(%0)
```
<p>We can compute the <code>i</code>th coefficient of the exponential generating function by differentiating the tangent function <code>i</code> times and evaluating at <code>0</code>. Each derivative is a polynomial in <code>tan(x)</code>, and the value at 0 is its constant term.</p>
<p>We recursively express the coefficient of <code>tan(x)^j</code> in the <code>i</code>th derivative of <code>tan</code> with the function <code>i%j</code>. The recursive expression comes from the relation <code>tan(x)' = 1 + tan(x)^2</code>.</p>
<p>So, the derivative of <code>tan(x)^j</code> is</p>
<pre class="lang-haskell prettyprint-override"><code>j*tan(x)^(j-1)*(tan(x)^2+1), or equivalently
j*tan(x)^(j+1) + j*tan(x)^(j-1)
</code>```

So, the contributors to tan(x)^j in the ith derivative are tan(x)^(j-1) and tan(x)^(j+1) in the (i-1)st derivative, each with coefficient equal to its power.

Body:
Haskell, 48 bytes

0%1=1
0%_=0
i%j=sum[k*(i-1)%k|k<-[j+1,j-1]]
(%0)

We can compute the ith coefficient of the exponential generating function by differentiating the tangent function i times and evaluating at 0. Each derivative is a polynomial in tan(x), and the value at 0 is its constant term.

We recursively express the coefficient of tan(x)^j in the ith derivative of tan with the function i%j. The recursive expression comes from the relation tan(x)' = 1 + tan(x)^2.

So, the derivative of tan(x)^j is

j*tan(x)^(j-1)*(tan(x)^2+1), or equivalently
j*tan(x)^(j+1) + j*tan(x)^(j-1)

So, the contributors to tan(x)^j in the ith derivative are tan(x)^(j-1) and tan(x)^(j+1) in the (i-1)st derivative, each with coefficient equal to its power.


答:
SQL (PostgreSQL 9.4), 171 bytes

Done as a prepared statement.  Generate a couple of series 2 - 99, cross join them and do the equation.  Densely rank the results to index them and select the first result that has the rank of the integer input.

```<code>prepare l(int)as select s from(select dense_rank()over(order by s)r,s from(select x^y+y^x from generate_series(2,99)x(x),generate_series(2,99)y(y))c(s))d where r=$1limit 1
</code>```

Executed as follows

```<code>execute l(82)
s
-----------------
1996813914
</code>```

This ended up running a lot quicker than I expected

Title: Leyland Numbers

Body:
SQL (PostgreSQL 9.4), 171 bytes

Done as a prepared statement.  Generate a couple of series 2 - 99, cross join them and do the equation.  Densely rank the results to index them and select the first result that has the rank of the integer input.

prepare l(int)as select s from(select dense_rank()over(order by s)r,s from(select x^y+y^x from generate_series(2,99)x(x),generate_series(2,99)y(y))c(s))d where r=$1limit 1

Executed as follows

execute l(82)
s
-----------------
1996813914

This ended up running a lot quicker than I expected


答:
Python, 57 bytes

f=lambda i,j=0:~-j*f(i-1,j-1)-~j*f(i-1,j+1)if i else j==1
```
<p>Less golfed:</p>
<pre class="lang-python prettyprint-override"><code>f=lambda i,j=0:j==1 if i==0 else (j-1)*f(i-1,j-1)+(j+1)*f(i-1,j+1)
</code>```

We can compute the ith coefficient of the exponential generating function by differentiating the tangent function i times and evaluating at 0. Each derivative is a polynomial in tan(x), and its value at 0 is its constant term.

We recursively express the coefficient of tan(x)**j in the ith derivative of tan with the function f(i,j). The recursive expression comes from the relation tan(x)' = 1 + tan(x)**2.

So, the derivative of tan(x)**j is

j*tan(x)**(j-1)*(tan(x)**2+1), or equivalently
j*tan(x)**(j+1) + j*tan(x)**(j-1)
```
<p>So, the contributors to <code>tan(x)**j</code> in the <code>i</code>th derivative are <code>tan(x)**(j-1)</code> and <code>tan(x)**(j+1)</code> in the <code>(i-1)</code>st derivative, each with coefficient equal to its power. This gives the recursive expression</p>
<pre class="lang-python prettyprint-override"><code>f(i,j) = (j-1)*f(i-1,j-1) + (j+1)*f(i-1,j+1)
</code>```

Note that we don't need to exclude negative exponents j because they evaluate to zero anyway and don't contribute because crossing j=0 gives a multiplier of 0.

The base case of i==0 corresponds to tan(x) itself with j==1, and zero coefficients otherwise. The final evaluation happens at the constant term j=0, which is put in as a default value.

Body:
Python, 57 bytes

f=lambda i,j=0:~-j*f(i-1,j-1)-~j*f(i-1,j+1)if i else j==1

Less golfed:

f=lambda i,j=0:j==1 if i==0 else (j-1)*f(i-1,j-1)+(j+1)*f(i-1,j+1)

We can compute the ith coefficient of the exponential generating function by differentiating the tangent function i times and evaluating at 0. Each derivative is a polynomial in tan(x), and its value at 0 is its constant term.

We recursively express the coefficient of tan(x)**j in the ith derivative of tan with the function f(i,j). The recursive expression comes from the relation tan(x)' = 1 + tan(x)**2.

So, the derivative of tan(x)**j is

j*tan(x)**(j-1)*(tan(x)**2+1), or equivalently
j*tan(x)**(j+1) + j*tan(x)**(j-1)

So, the contributors to tan(x)**j in the ith derivative are tan(x)**(j-1) and tan(x)**(j+1) in the (i-1)st derivative, each with coefficient equal to its power. This gives the recursive expression

f(i,j) = (j-1)*f(i-1,j-1) + (j+1)*f(i-1,j+1)

Note that we don't need to exclude negative exponents j because they evaluate to zero anyway and don't contribute because crossing j=0 gives a multiplier of 0.

The base case of i==0 corresponds to tan(x) itself with j==1, and zero coefficients otherwise. The final evaluation happens at the constant term j=0, which is put in as a default value.


答:
J, <s>15</s> 13 bytes

There is also the builtin t: which calculates the nth coefficient of the exponential generating function of tan(x).

```<code>(1&o.%2&o.)t:
</code>```

Thanks to @Leaky Nun for reminding me of Taylor series adverbs in J which saved 2 bytes.

Alternative for 15 bytes.

```<code>3 :'(3&o.d.y)0'
</code>```

Another approach is to calculate the nth derivative of tan(x) and evaluate it at x = 0.

Note: In J, the amount of memory used by the derivative function d. grows quickly as n passes 10.

Usage

```<code>   f =: (1&o.%2&o.)t:
   f 7
272
   (,.f"0) i. 11  NB. Additional commands are just for formatting the output
 0    0
 1    1
 2    0
 3    2
 4    0
 5   16
 6    0
 7  272
 8    0
 9 7936
10    0
</code>```

Explanation

```<code>(1&o.%2&o.)t:  Input: n
(         )    Define a monad (one argument function), call the input y
 1&o.          Get the trig function sin(x) and call it on y
      2&o.     Get the trig function cos(x) and call it on y
     %         Divide sin(y) by cos(y) to get tan(y)
           t:  Get the nth coefficient of the exponential generating series
               for that function and return

3 :'(3&o.d.y)0'  Input: n
3 :'          '  Define a monad (one argument function) with input y
     3&o.        Get the trig function tan(x)
           y     The input n
         d.      Get the nth derivative of tan(x)
             0   Evaluate the nth derivative at x = 0 and return
</code>```

Body:
J, <s>15</s> 13 bytes

There is also the builtin t: which calculates the nth coefficient of the exponential generating function of tan(x).

(1&o.%2&o.)t:

Thanks to @Leaky Nun for reminding me of Taylor series adverbs in J which saved 2 bytes.

Alternative for 15 bytes.

3 :'(3&o.d.y)0'

Another approach is to calculate the nth derivative of tan(x) and evaluate it at x = 0.

Note: In J, the amount of memory used by the derivative function d. grows quickly as n passes 10.

Usage

   f =: (1&o.%2&o.)t:
   f 7
272
   (,.f"0) i. 11  NB. Additional commands are just for formatting the output
 0    0
 1    1
 2    0
 3    2
 4    0
 5   16
 6    0
 7  272
 8    0
 9 7936
10    0

Explanation

(1&o.%2&o.)t:  Input: n
(         )    Define a monad (one argument function), call the input y
 1&o.          Get the trig function sin(x) and call it on y
      2&o.     Get the trig function cos(x) and call it on y
     %         Divide sin(y) by cos(y) to get tan(y)
           t:  Get the nth coefficient of the exponential generating series
               for that function and return

3 :'(3&o.d.y)0'  Input: n
3 :'          '  Define a monad (one argument function) with input y
     3&o.        Get the trig function tan(x)
           y     The input n
         d.      Get the nth derivative of tan(x)
             0   Evaluate the nth derivative at x = 0 and return


答:
MATLAB with Symbolic Toolbox, 84 bytes

```<code>n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
</code>```

Example runs:

```<code>>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
7
ans =
272

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
8
ans =
0

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
9
ans =
7936
</code>```

Body:
MATLAB with Symbolic Toolbox, 84 bytes

n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)

Example runs:

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
7
ans =
272

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
8
ans =
0

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
9
ans =
7936


问:
Is my emoji dry?
This is my pet emoji, Billy:

```<code>-_-
</code>```

Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better!

```<code>  /\
 /  \
/    \

  -_-
</code>```

This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered:

```<code>  /\
 /  \
/    \

     -_-
</code>```

In this case, sections 2 and 3 of his body are exposed to the rain.

Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes / followed by a series of descending backslashes \. For example, these are all valid umbrellas:

```<code>  /\
 /  \
/    \

/\

    /\
   /  \
  /    \
 /      \
/        \
</code>```

And these are not:

```<code>/   \

\/

  \
 / \
/   \

 0\
/  \

//\\
/  \
</code>```

You need to determine which parts of my emoji are exposed to the rain.

Clarifications

Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc.

You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array).

You can assume that all inputs will have a valid umbrella, and the same emoji: -_-. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji.

Everything that isn't part of the umbrella or the emoji will be a space   character or newline.

The input will be padded with spaces so that the length of each line is the same.

Standard loopholes apply, and the shortest answer in bytes wins!

Test IO:

All of the sample cases will use one-indexing.

```<code>  /\
 /  \
/    \

  -_-

Outputs: []

----------------

   /\
  /  \

     -_-

Outputs: [2, 3]

----------------

    /\
   -_-

Outputs: [1]

----------------

     /\
    /  \
   /    \
  /      \
 /        \
/          \

               -_-

Outputs: [1, 2, 3]
</code>```

答:
Matlab, 43 bytes

```<code>@(x)find(sum((x(:,x(end,:)~=' '))~=' ')==1)
</code>```

This code finds column positions of non-space characters in the final row of the input, sums the number of non-space characters in those columns, and finds where there's only one such character (the emoji's character, un-shielded by umbrella!). This code only returns proper results for well-formed umbrellas (it assumes any character above our emoji is part of a well-formed umbrella).

Here is a bit of utility code for writing test cases and checking my work:

```<code>ws = @(x) repmat(' ',1,x);  %  for making strings of spaces
% for writing three-storey umbrellas over an emoji located left-edge at position x
thrht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/  \' ws(2); ws(1) '/' ws(4) '\' ws(1); ws(8)], [ws(x-1) '-_-']);
twht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/  \' ws(2); ws(8)], [ws(x-1) '-_-']);
</code>```

Running x = thrht(7) gives

```<code>x =

   /\
  /  \
 /    \

      -_-
</code>```

Or
    x = twht(0)
gives

```<code>x =

   /\
  /  \

 -_-
</code>```

Title: Is my emoji dry?

Body:
Matlab, 43 bytes

@(x)find(sum((x(:,x(end,:)~=' '))~=' ')==1)

This code finds column positions of non-space characters in the final row of the input, sums the number of non-space characters in those columns, and finds where there's only one such character (the emoji's character, un-shielded by umbrella!). This code only returns proper results for well-formed umbrellas (it assumes any character above our emoji is part of a well-formed umbrella).

Here is a bit of utility code for writing test cases and checking my work:

ws = @(x) repmat(' ',1,x);  %  for making strings of spaces
% for writing three-storey umbrellas over an emoji located left-edge at position x
thrht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/  \' ws(2); ws(1) '/' ws(4) '\' ws(1); ws(8)], [ws(x-1) '-_-']);
twht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/  \' ws(2); ws(8)], [ws(x-1) '-_-']);

Running x = thrht(7) gives

x =

   /\
  /  \
 /    \

      -_-

Or
    x = twht(0)
gives

x =

   /\
  /  \

 -_-


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;function answersUrl(e){return"https://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"https://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+(?:\.\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

```

答:
NTFJ, 86 bytes

```<code>0000 false              ~
0001 p and q            |:|
0010 p and not q        :||:|
0011 p                  $
0100 not p and q        #{:||:|
0101 q                  #{$
0110 xor                :#{:#{:||#}:|||
0111 p or q             :|#{:||
1000 not p and not q    :|#{:||:|
1001 eq                 :#{:#{:||#}:|||:|
1010 not q              #{$:|
1011 p or not q         #{:||
1100 not p              $:|
1101 not p or q         :||
1110 not p or not q     |
1111 true               #
</code>```

Try it here! But read below first.

Input is implicit on stack. Result is let on stack. Add 16 bytes (one * to the end of each) if you want 0x00 or 0x01 to output representing 0 and 1. Add an additional 160 bytes if you want a 0 or a 1 printed. (Put ~~##~~~#{@ before each *.)

NTFJ's only binary operator is NAND, so each of these is written in NAND form.

Let's go through each of them.

0: false

```<code>~
</code>```

~ represents a false bit. Simple enough. Since input is implicit at the bottom of the stack, this is left at the top of it.

1: p and q

```<code>|:|
</code>```

NTFJ operates on a stack. : is the command for duplicate. Observe that p and q ≡ not (p nand q) and that not q = q nand q.

```<code>Command | Stack
        | p q
   |    | (p nand q)
   :    | (p nand q) (p nand q)
   |    | (p nand q) nand (p nand q)
        | => not (p nand q)
        | => p and q
</code>```

(Note, then, :|can be said to be negation and |:| can be said to be conjunction)

2: p and not q

```<code>:||:|
</code>```

Observe that this just a negation, :| and a conjunction |:|.

```<code>Command | Stack
        | p q
  :|    | p (not q)
  |:|   | p and (not q)
</code>```

3: p

```<code>$
</code>```

$ pops an item from the stack. So... yeah.

4: not p and q

```<code>#{:||:|
</code>```

This is the same thing as 2, except with #{ at the beginning. # pushes 1 (the true bit) and { rotates the stack left once. Simple enough.

5: q

```<code>#{$
</code>```

Rotate left once, drop.

6: xor

```<code>:#{:#{:||#}:|||
</code>```

Observe:

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

However, there is no way to duplicate the stack entirely. So, we're going to have to bring each of p, q to the top and duplicate it.

```<code>~
</code>```1

And thus, we have our xor.

7: p or q

```<code>~
</code>```2

Negate top, bring bottom to top, negate that, and nand them together. Basically, p or q = (not p) nand (not q).

8: not p and not q

```<code>:|#{:||:|
</code>```

This is simply the negation of 7. Easy.

9: eq

```<code>:#{:#{:||#}:|||:|
</code>```

This is just xnor, or not xor. Simple again.

10: not q

```<code>#{$:|
</code>```

Negation of 5.

11: p or not q

```<code>#{:||
</code>```

Negate p, nand. (not p) nand q = not ((not p) and q) = p or (not q) (by De Morgan's laws).

12: not p

```<code>$:|
</code>```

Drop, stop, and negate.

13: not p or q

```<code>:||
</code>```

De Morgan's laws to save the day, again! Same process as 11, just negating q instead of p.

14: not p or not q

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

This is just a mimic nand.

15: true

```<code>|:|
</code>```0

# is the true bit.

Body:
NTFJ, 86 bytes

0000 false              ~
0001 p and q            |:|
0010 p and not q        :||:|
0011 p                  $
0100 not p and q        #{:||:|
0101 q                  #{$
0110 xor                :#{:#{:||#}:|||
0111 p or q             :|#{:||
1000 not p and not q    :|#{:||:|
1001 eq                 :#{:#{:||#}:|||:|
1010 not q              #{$:|
1011 p or not q         #{:||
1100 not p              $:|
1101 not p or q         :||
1110 not p or not q     |
1111 true               #

Try it here! But read below first.

Input is implicit on stack. Result is let on stack. Add 16 bytes (one * to the end of each) if you want 0x00 or 0x01 to output representing 0 and 1. Add an additional 160 bytes if you want a 0 or a 1 printed. (Put ~~##~~~#{@ before each *.)

NTFJ's only binary operator is NAND, so each of these is written in NAND form.

Let's go through each of them.

0: false

~

~ represents a false bit. Simple enough. Since input is implicit at the bottom of the stack, this is left at the top of it.

1: p and q

|:|

NTFJ operates on a stack. : is the command for duplicate. Observe that p and q ≡ not (p nand q) and that not q = q nand q.

Command | Stack
        | p q
   |    | (p nand q)
   :    | (p nand q) (p nand q)
   |    | (p nand q) nand (p nand q)
        | => not (p nand q)
        | => p and q

(Note, then, :|can be said to be negation and |:| can be said to be conjunction)

2: p and not q

:||:|

Observe that this just a negation, :| and a conjunction |:|.

Command | Stack
        | p q
  :|    | p (not q)
  |:|   | p and (not q)

3: p

$

$ pops an item from the stack. So... yeah.

4: not p and q

#{:||:|

This is the same thing as 2, except with #{ at the beginning. # pushes 1 (the true bit) and { rotates the stack left once. Simple enough.

5: q

#{$

Rotate left once, drop.

6: xor

:#{:#{:||#}:|||

Observe:

p xor q = (p and (not q)) or ((not p) and q)                ; by experimentation (trust me)
        = (not ((not p) nand q)) or (not (p nand (not q)))  ; by definition of nand
        = not (((not p) nand q) and (p nand (not q)))       ; by De Morgan's laws
        = ((not p) nand q) nand (p nand (not q))            ; by definition of nand

However, there is no way to duplicate the stack entirely. So, we're going to have to bring each of p, q to the top and duplicate it.

Command | Stack
        | p q
   :    | p q q
  #{    | q q p
   :    | q q p p
  #{    | q p p q
  :|    | q p p (not q)
   |    | q p (p nand (not q))
  #}    | (p nand (not q)) q p
  :|    | (p nand (not q)) q (not p)
   |    | (p nand (not q)) (q nand (not p))
   |    | (p nand (not q)) nand (q nand (not p))

And thus, we have our xor.

7: p or q

:|#{:||

Negate top, bring bottom to top, negate that, and nand them together. Basically, p or q = (not p) nand (not q).

8: not p and not q

:|#{:||:|

This is simply the negation of 7. Easy.

9: eq

:#{:#{:||#}:|||:|

This is just xnor, or not xor. Simple again.

10: not q

#{$:|

Negation of 5.

11: p or not q

#{:||

Negate p, nand. (not p) nand q = not ((not p) and q) = p or (not q) (by De Morgan's laws).

12: not p

$:|

Drop, stop, and negate.

13: not p or q

:||

De Morgan's laws to save the day, again! Same process as 11, just negating q instead of p.

14: not p or not q

|

This is just a mimic nand.

15: true

#

# is the true bit.


问:
Cycles in run-length encoding
Consider some binary sequence, using 1 and 2, e.g.:

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

Let's write down the run lengths of that:

```<code>1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1 ...
_  _  ____  ____  _  _  _  ____
1, 1, 2,    2,    1, 1, 1, 2,   ...
</code>```

In this case we happen to get another binary sequence. Of course, that's not guaranteed (e.g. if we repeated the process, the third run would be 3), but let's assume we do.

Now the question is, can we find a sequence such that applying this type of run-length encoding multiple times gives us back the original sequence? For a cycle-length of 1 (i.e. a fixed point of this transformation), we find the Oldenburger-Kolakoski sequence (OEIS entry A0000002):

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

(There is actually another solution: we can also omit the leading 1.)

What about a cycle of length-2? That's also possible! The following two sequences are each others' list of run lengths:

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

(These are OEIS entries A025142 and A025143. This is the only solution.)

Can we find a cycle of length 3? Sure, here each sequence is the run-length encoding of the next (and the third one is the run-length encoding of the first):

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

In this case there is one other solution. It turns out that we can find such a cycle for every cycle length. In fact, the number of distinct cycles of length n is given by OEIS entry A001037 (this is not counting the arbitrary choice of which sequence in a cycle is considered the first).

Fun fact: As unlikely as it seems, this challenge was inspired by studying the complex map f(z) = z - 1/z. Whoever figures out what that map has to do with this challenge gets a cookie.

The Challenge

Given a cycle length k > 0 and a sequence length n > 0, output the first n terms of k distinct (infinite) binary sequences that form a cycle under the above run-length transformation. If multiple cycles exist, you may output any one of them. It's up to you which sequence in the cycle to start with, and which direction the cycle goes (so you can either output them such that each sequence describes the next, or such that each sequence describes the previous one, cyclically).

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

Output may be in any convenient, unambiguous, nested list format, such that the the outer dimension is k and the inner dimension is n.

Standard code-golf rules apply.

Additional examples

Here are some examples. But as I said, the solutions are not unique, so your own solutions might differ and still be correct. Maybe these will help you come up with a solution though. Each example is k n followed by the sequences, such that each line describes the next (cyclically):

```<code>4 20
1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2
2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1
2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1
1, 1, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1

5 6
2, 2, 1, 2, 2, 1
1, 1, 2, 2, 1, 2
2, 1, 2, 2, 1, 1
1, 1, 2, 1, 1, 2
2, 1, 2, 2, 1, 2

8 20
2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2
1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1
2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2
2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2
1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1
2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2
1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1
2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1

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

Note that not all of the lines in the last two outputs differ, although they would eventually if n was large enough.

Related Questions

Generate a Kolakoski sequence

答:
CJam (41 bytes)

```<code>{Ma*{1:Bm<{1+ee{(1&B^)+}%e~A<0:B;}%}@:A*}
</code>```

This is an anonymous function which takes input on the stack in the order n k and leaves output on the stack. Online demo

The basic idea is to start with a Lyndon word column [2 1 1 1 ...] and iteratively extend right on the basis that knowing the initial element of each row and the alternation we can run-length decode and get more elements.

Title: Cycles in run-length encoding

Body:
CJam (41 bytes)

{Ma*{1:Bm<{1+ee{(1&B^)+}%e~A<0:B;}%}@:A*}

This is an anonymous function which takes input on the stack in the order n k and leaves output on the stack. Online demo

The basic idea is to start with a Lyndon word column [2 1 1 1 ...] and iteratively extend right on the basis that knowing the initial element of each row and the alternation we can run-length decode and get more elements.


问:
The handshake problem
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect n >= 0

Test cases

```<code>(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116
</code>```

Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

Title: The handshake problem

Body:
Perl 5, 25 bytes

A subroutine:

{($_=pop)*!/\D/*($_-1)/2}

See it in action:

perl -e'print sub{($_=pop)*!/\D/*($_-1)/2}->(3.14)'


Title: Golf all the 16 logic gates with 2 inputs and 1 output!

Body:
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;function answersUrl(e){return"https://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"https://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+(?:\.\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

```

Body:
Haskell, <s>78</s> <s>76</s> 75 bytes

_#_=2<1

&&

>

pure

<

_#b=b

/=

||

(not.).max

==

_#b=not b

>=

a#_=not a

<=

(not.).min

_#_=1<2

Edit: -1 byte thanks to @cole.


答:
dc, 37 bytes

dc ("desk calculator") is a standard unix command, a stack-based postfix calculator. It lacks bit operations, and comparison operators can only be used to execute macros (which is not worth the bytes). Integer division makes up for some of that.

These scripts expect 0 and 1 values on the stack, and leave the result on the stack.

```<code>0,0,0,0 (false)              0
0,0,0,1 (and)                *         a*b
0,0,1,0                      -1+2/     (a-b+1)/2
0,0,1,1 (A)                  r         reverse a, b: a now on top
0,1,0,0                      -1-2/     (a-b-1)/2
0,1,0,1 (B)                            (0 bytes) do nothing: b on top
0,1,1,0 (xor)                -         a-b
0,1,1,1 (or)                 +         a+b
1,0,0,0 (nor)                +v1-      sqrt(a+b) -1
1,0,0,1 (xnor)               +1-       a+b-1
1,0,1,0 (not B)              1-        b-1
1,0,1,1 (if B then A)        -1+       a-b+1
1,1,0,0 (not A)              r1-       a-1
1,1,0,1 (if A then B)        -1-       a-b-1
1,1,1,0 (nand)               *1-       a*b - 1
1,1,1,1 (true)               1
</code>```

Body:
dc, 37 bytes

dc ("desk calculator") is a standard unix command, a stack-based postfix calculator. It lacks bit operations, and comparison operators can only be used to execute macros (which is not worth the bytes). Integer division makes up for some of that.

These scripts expect 0 and 1 values on the stack, and leave the result on the stack.

0,0,0,0 (false)              0
0,0,0,1 (and)                *         a*b
0,0,1,0                      -1+2/     (a-b+1)/2
0,0,1,1 (A)                  r         reverse a, b: a now on top
0,1,0,0                      -1-2/     (a-b-1)/2
0,1,0,1 (B)                            (0 bytes) do nothing: b on top
0,1,1,0 (xor)                -         a-b
0,1,1,1 (or)                 +         a+b
1,0,0,0 (nor)                +v1-      sqrt(a+b) -1
1,0,0,1 (xnor)               +1-       a+b-1
1,0,1,0 (not B)              1-        b-1
1,0,1,1 (if B then A)        -1+       a-b+1
1,1,0,0 (not A)              r1-       a-1
1,1,0,1 (if A then B)        -1-       a-b-1
1,1,1,0 (nand)               *1-       a*b - 1
1,1,1,1 (true)               1


答:
Sage, 26 bytes

lambda n:tan(x).diff(n)(0)
```

Like the other solutions in math-oriented languages, this function computes the nth derivative of tan(x) and evaluates it at x = 0.

Try it online

Body:
Almost every function can be expressed as a polynomial with infinite terms.

For example, e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...

For example, sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...

The coefficients of the n-th terms form a sequence, and the corresponding function is called the Generating Function of the sequence.

The coefficients of the n-th terms form a sequence.

Often, the n-th term would have a denominator of n!. Therefore, we multiply the coefficient by n! to obtain another sequence, whose Exponential Generating Function would be the original function.

For example, the sequence whose Exponential Generating Function is e^x would be 1,1,1,1,....

For example, the sequence whose Exponential Generating Function is sin(x) would be 0,1,0,-1,0,1,0,-1,....

Task

Your task is to find the n-th term of the sequence whose Exponential Generating Function is tan(x).

Testcases

```<code>n result
0 0
1 1
2 0
3 2
4 0
5 16
6 0
7 272
8 0
9 7936
10 0
11 353792
12 0
13 22368256
14 0
15 1903757312
16 0
17 209865342976
18 0
19 29088885112832
20 0
21 4951498053124096
22 0
23 1015423886506852352
24 0
25 246921480190207983616
26 0
</code>```

(Copied from here.) (Warning: the 0-th term is different)

Example implementation

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L16
def memoized(f):
    memo = {}
    def m_fun(*args):
        if args in memo:
            return memo[args]
        else:
            res = f(*args)
            memo[args] = res
            return res
    return m_fun

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L169
@memoized
def binomial(n,r):
    if r > n:
        return 0
    elif r==n:
        return 1
    res = 1
    i = 1
    while i<=r:
        res *= (n+1-i)
        res /= i
        i+=1
    return int(res)

# 2*u(n+1) = Sum_{k=0..n} binomial(n, k)*u(k)*u(n-k)
# from A000111
@memoized
def u(n):
    if n<0: return 0
    if n==0: return 1
    if n==1: return 1
    return sum([binomial(n-1,k)*u(k)*u(n-1-k) for k in range(n)])//2

def t(n):
    if n%2 == 0: return 0
    return u(n)

print('\n'.join([str(x) + ' ' + str(t(x)) for x in range(26)]))
```

Ideone it!

References

Generating function on Wikipedia

Exponential generating function on Wikipedia

Exponential generating function example on Wikipedia

Generating function on MathWorld

Exponential generating function on MathWorld

Taylor series on Wikipedia

Derivation of first 9 terms of required sequence

Obligatory OEIS A009006 (Note that the 0-th term is different)

Algorithm

OEIS A000111: up/down numbers

Body:
Sage, 26 bytes

lambda n:tan(x).diff(n)(0)

Like the other solutions in math-oriented languages, this function computes the nth derivative of tan(x) and evaluates it at x = 0.

Try it online


答:
, 5 chars / 7 bytes

```<code>МƦ⁽ï2
</code>```

Try it here (ES6 browsers only).

Builtins are pretty cool.

Title: The handshake problem

Body:
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect n >= 0

Test cases

```<code>(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116
</code>```

Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

Body:
, 5 chars / 7 bytes

МƦ⁽ï2

Try it here (ES6 browsers only).

Builtins are pretty cool.


答:
RETURN, 8 bytes

```<code>[$1-×2÷]
</code>```

Try it here.

Anonymous lambda that leaves result as top of stack. Usage:

```<code>10[$1-×2÷]!
</code>```

Explanation

```<code>[      ]  lambda
 $1-      n-1
    ×     *n
     2÷   /2
</code>```

Title: The handshake problem

Body:
RETURN, 8 bytes

[$1-×2÷]

Try it here.

Anonymous lambda that leaves result as top of stack. Usage:

10[$1-×2÷]!

Explanation

[      ]  lambda
 $1-      n-1
    ×     *n
     2÷   /2


答:
Actually, 24 bytes

These programs take input as A\nB (with \n representing a newline), which leaves B on top of the stack, with A below. False is represented by 0, and True is represented by any positive integer.

```<code>é0  (false: clear stack, push 0)
*   (and: multiply)
<   (A and not B: less-than)
X   (A: discard B)
>   (B and not A: greater-than)
@X  (B: discard A)
^   (A xor B: xor)
|   (A or B: or)
|Y  (A nor B: or, boolean negate)
=   (A xnor B: equals)
@XY (not B: discard A, boolean negate B)
≤   (if B then A: less-than-or-equal)
XY  (not A: discard B, boolean negate)
≥   (if A then B: greater-than-or-equal)
*Y  (A nand B: multiply, boolean negate)
é1  (true: clear stack, push 1)
</code>```

Thanks to Leaky Nun for 3 bytes

Body:
Actually, 24 bytes

These programs take input as A\nB (with \n representing a newline), which leaves B on top of the stack, with A below. False is represented by 0, and True is represented by any positive integer.

é0  (false: clear stack, push 0)
*   (and: multiply)
<   (A and not B: less-than)
X   (A: discard B)
>   (B and not A: greater-than)
@X  (B: discard A)
^   (A xor B: xor)
|   (A or B: or)
|Y  (A nor B: or, boolean negate)
=   (A xnor B: equals)
@XY (not B: discard A, boolean negate B)
≤   (if B then A: less-than-or-equal)
XY  (not A: discard B, boolean negate)
≥   (if A then B: greater-than-or-equal)
*Y  (A nand B: multiply, boolean negate)
é1  (true: clear stack, push 1)

Thanks to Leaky Nun for 3 bytes


答:
Python 2, 137 bytes

[].sort
min
int.__rshift__
round
range
{}.get
cmp
max
lambda a,b:a<1>b
lambda a,b:a==b
lambda a,b:b<1
pow
{0:1,1:0}.get
{0:1}.get
lambda a,b:a+b<2
slice
```
<p>Takes inputs like <code>min(True,False)</code> (or as <code>min(1,0)</code>). Takes heavy advantage of outputs only needing to have the right Truthy-Falsey value. Whenever possible, uses a built-in to avoid a costly <code>lambda</code>. I used code to search for built-ins that work.</p>
<p>My favorite one is <code>{0:1}.get</code>, which I thought of by hand. The dictionary <code>{0:1}</code> maps the key <code>0</code> to the value <code>1</code>. Its <code>get</code> method takes a key and a default, outputting the value matching the key, or the default if there's no such key. So, the only way to output a <code>0</code> is as <code>{0:1}.get(1,0)</code>, with missing key <code>1</code> and default <code>0</code>. One can get other variants with different dictionaries, but only this one was the shortest.</p>
<pre class="lang-python prettyprint-override"><code>built_in_names = list(__builtins__)

object_names = ["int","(0)","(1)"] + \
["True","False","0L","1L","0j","1j"] + \
["str", "''", "'0'","'1'","'a'"] + \
["list", "[]", "[0]", "[1]","['']","[[]]","[{}]"] + \
["set","set()","{0}","{1}","{''}"] + \
["dict","{}","{0:0}","{0:1}","{1:0}","{1:1}","{0:0,1:0}", "{0:0,1:1}","{0:1,1:0}","{0:1,1:1}"] + \
["id"]

object_method_names = [object_name+"."+method_name
for object_name in object_names
for method_name in dir(eval(object_name))]

additional_func_names = [
"lambda a,b:0",
"lambda a,b:1",
"lambda a,b:a",
"lambda a,b:b",
"lambda a,b:b<1",
"lambda a,b:a<1",
"lambda a,b:a+b",
"lambda a,b:a*b",
"lambda a,b:a==b",
"lambda a,b:a-b",
"lambda a,b:a<=b",
"lambda a,b:a>=b",
"lambda a,b:a>b",
"lambda a,b:a<b",
"lambda a,b:a<1>b",
"lambda a,b:a+b<2"]

func_names = built_in_names + object_method_names + additional_func_names

t=True
f=False

cases = [(f,f),(f,t),(t,f),(t,t)]

def signature(func):
    table = [bool(func(x,y)) for x,y in cases]
    table_string = ''.join([str(int(val)) for val in table])
    return table_string

d={}

for func_name in func_names:
    try:
        func = eval(func_name)
        result = signature(func)
        if result not in d or len(func_name)<len(d[result]):
            d[result]=func_name
    except:
        pass

total_length = sum(len(func) for sig,func in d.items())

print total_length
print

for sig in sorted(d):
    print d[sig]
</code>```

Body:
Python 2, 137 bytes

[].sort
min
int.__rshift__
round
range
{}.get
cmp
max
lambda a,b:a<1>b
lambda a,b:a==b
lambda a,b:b<1
pow
{0:1,1:0}.get
{0:1}.get
lambda a,b:a+b<2
slice

Takes inputs like min(True,False) (or as min(1,0)). Takes heavy advantage of outputs only needing to have the right Truthy-Falsey value. Whenever possible, uses a built-in to avoid a costly lambda. I used code to search for built-ins that work.

My favorite one is {0:1}.get, which I thought of by hand. The dictionary {0:1} maps the key 0 to the value 1. Its get method takes a key and a default, outputting the value matching the key, or the default if there's no such key. So, the only way to output a 0 is as {0:1}.get(1,0), with missing key 1 and default 0. One can get other variants with different dictionaries, but only this one was the shortest.

built_in_names = list(__builtins__)

object_names = ["int","(0)","(1)"] + \
["True","False","0L","1L","0j","1j"] + \
["str", "''", "'0'","'1'","'a'"] + \
["list", "[]", "[0]", "[1]","['']","[[]]","[{}]"] + \
["set","set()","{0}","{1}","{''}"] + \
["dict","{}","{0:0}","{0:1}","{1:0}","{1:1}","{0:0,1:0}", "{0:0,1:1}","{0:1,1:0}","{0:1,1:1}"] + \
["id"]

object_method_names = [object_name+"."+method_name
for object_name in object_names
for method_name in dir(eval(object_name))]

additional_func_names = [
"lambda a,b:0",
"lambda a,b:1",
"lambda a,b:a",
"lambda a,b:b",
"lambda a,b:b<1",
"lambda a,b:a<1",
"lambda a,b:a+b",
"lambda a,b:a*b",
"lambda a,b:a==b",
"lambda a,b:a-b",
"lambda a,b:a<=b",
"lambda a,b:a>=b",
"lambda a,b:a>b",
"lambda a,b:a<b",
"lambda a,b:a<1>b",
"lambda a,b:a+b<2"]

func_names = built_in_names + object_method_names + additional_func_names

t=True
f=False

cases = [(f,f),(f,t),(t,f),(t,t)]

def signature(func):
    table = [bool(func(x,y)) for x,y in cases]
    table_string = ''.join([str(int(val)) for val in table])
    return table_string

d={}

for func_name in func_names:
    try:
        func = eval(func_name)
        result = signature(func)
        if result not in d or len(func_name)<len(d[result]):
            d[result]=func_name
    except:
        pass

total_length = sum(len(func) for sig,func in d.items())

print total_length
print

for sig in sorted(d):
    print d[sig]