答:
Jelly, <s>12</s> 11 bytes

```<code>Ṛ+\;S
ḂÇ⁸¡Ḣ
</code>```

Like Peter Taylor's CJam answer, this computes the nth term of Euler's up/down sequence if n is odd and special-cases even n as 0.

Try it online! or verify all test cases.

How it works

```<code>ḂÇ⁸¡Ḣ  Main link. Argument: n

Ḃ       Bit; yield n's parity.
 Ç⁸¡    Apply the helper link (Ç) n (⁸) times.
    Ḣ   Head; retrieve the first element of the resulting list.

Ṛ+\;S   Helper link. Argument: A (list or 1/0)

Ṛ       Cast A to list (if necessary) and reverse the result.
 +\     Take the cumulative sum.
   ;S   Append the sum of A.
</code>```

Body:
Jelly, <s>12</s> 11 bytes

Ṛ+\;S
ḂÇ⁸¡Ḣ

Like Peter Taylor's CJam answer, this computes the nth term of Euler's up/down sequence if n is odd and special-cases even n as 0.

Try it online! or verify all test cases.

How it works

ḂÇ⁸¡Ḣ  Main link. Argument: n

Ḃ       Bit; yield n's parity.
 Ç⁸¡    Apply the helper link (Ç) n (⁸) times.
    Ḣ   Head; retrieve the first element of the resulting list.

Ṛ+\;S   Helper link. Argument: A (list or 1/0)

Ṛ       Cast A to list (if necessary) and reverse the result.
 +\     Take the cumulative sum.
   ;S   Append the sum of A.


问:
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 (too many bytes)

Using only operations on lists and Raymond Manzoni's result:

```<code>c n = last $ map numerator $ zipWith (*) (scanl (*) (1) [2,3..]) (intersperse 0 $ foldr (.) id (replicate n (\xs->(xs ++ [(1%(1+2*length xs)) * (sum (zipWith (*) xs (reverse xs)))]))) [1])
</code>```

Unfortunately, this overflows for modest values of n, as it uses Int values. I will try to fix the problem using Integervalues. Until then, suggestions are welcome.

ContentLicense: CC BY-SA 3.0

Body:
Haskell (too many bytes)

Using only operations on lists and Raymond Manzoni's result:

c n = last $ map numerator $ zipWith (*) (scanl (*) (1) [2,3..]) (intersperse 0 $ foldr (.) id (replicate n (\xs->(xs ++ [(1%(1+2*length xs)) * (sum (zipWith (*) xs (reverse xs)))]))) [1])

Unfortunately, this overflows for modest values of n, as it uses Int values. I will try to fix the problem using Integervalues. Until then, suggestions are welcome.


答:
Julia, <s>40</s> <s>38</s> 32 bytes

!n=2(2*4^n-2^n-0^n)abs(zeta(-n))
```

Input and output is in form of BigFloats. Try it online!

Background

The Maclaurin series of the tangent function satisfies the identity

whenever x lies in its convergence radius, where Bn is a Bernoulli number.

Since B2(n+1) and (-1)n have the same sign, B2n+1 = 0 if n > 0 and B1 = 1/2, we can rewrite the above as follows.

Furthermore, whenever n is a non-negative integer, we have

where ζ denotes the Riemann zeta function.

From this, with the convention 00 = 1, it follows that

which is the formula the implementation uses.

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:
Julia, <s>40</s> <s>38</s> 32 bytes

!n=2(2*4^n-2^n-0^n)abs(zeta(-n))

Input and output is in form of BigFloats. Try it online!

Background

The Maclaurin series of the tangent function satisfies the identity

whenever x lies in its convergence radius, where Bn is a Bernoulli number.

Since B2(n+1) and (-1)n have the same sign, B2n+1 = 0 if n > 0 and B1 = 1/2, we can rewrite the above as follows.

Furthermore, whenever n is a non-negative integer, we have

where ζ denotes the Riemann zeta function.

From this, with the convention 00 = 1, it follows that

which is the formula the implementation uses.


答:
Julia, <s>39</s> 37 bytes

```<code>!n=(spdiagm((0:n,1:n+1),(1,-1))^n)[2]
</code>```

Saved 2 bytes thanks to Dennis.

Not the shortest Julia solution (see Dennis's solution), but this one is done purely using derivative logic... in the form of matrices.

Basically, it uses the fact that the derivative of tan(x) is 1+tan(x)^2. So since the derivative of any power of tan(x), say tan(x)^k, is k tan(x)^(k-1) tan(x)' = k tan(x)^(k-1) + k tan(x)^(k+1), we can use a simple matrix power on a matrix with the appropriate values to generate the expansion, with the second row or column (depending on construction) holding the derivatives of tan(x) itself.

So we just need to find the constant in the resulting expression, and that's the first value in the corresponding row or column.

Body:
Julia, <s>39</s> 37 bytes

!n=(spdiagm((0:n,1:n+1),(1,-1))^n)[2]

Saved 2 bytes thanks to Dennis.

Not the shortest Julia solution (see Dennis's solution), but this one is done purely using derivative logic... in the form of matrices.

Basically, it uses the fact that the derivative of tan(x) is 1+tan(x)^2. So since the derivative of any power of tan(x), say tan(x)^k, is k tan(x)^(k-1) tan(x)' = k tan(x)^(k-1) + k tan(x)^(k+1), we can use a simple matrix power on a matrix with the appropriate values to generate the expansion, with the second row or column (depending on construction) holding the derivatives of tan(x) itself.

So we just need to find the constant in the resulting expression, and that's the first value in the corresponding row or column.


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

Input:

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

Output:

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

Addition (+);

Subtraction (−);

Multiplication (* or × or ·);

Real / Calculator Division (/ or ÷);

Exponentiation (^ or **).

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

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

Challenge rules:

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

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

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

General rules:

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

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

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

Default Loopholes are forbidden.

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

Test cases:

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

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

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

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

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

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

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

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

答:
c#, <s>238</s>, 202 bytes

```<code>double d(double[]a){Array.Reverse(a);var s=new Stack<double>(a);int i=0,j;while(s.Count>1){double l=s.Pop(),r=s.Pop();j=i++%5;s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l,r));}return s.Peek();}
</code>```

I didn't see any c# solution so I will give one. This is my first codegolf. I started writing in c# "two months ago" (though I know Java to some extent).

It uses Stack

Ungolfed and test cases

```<code>using System;
using System.Collections.Generic;

class M
{
    double d(double[]a) {
        Array.Reverse(a);
        var s = new Stack<double>(a);
        int i=0,j;
        while (s.Count>1)
        {
            double l=s.Pop(),r=s.Pop();
            j=i++%5;
            s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l, r));
        }
        return s.Peek();
    }

    public static void Main()
    {
        int[][] a = new int[][]{
            new int[]{1,2,3,4,5},
            new int[]{5,12,23,2,4,4,2,6,7},
            new int[]{-8,50,3,3,-123,4,17,99,13},
            new int[]{2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2},
            new int[]{1,0,1,0,1,0},
            new int[]{-9,-8,-1},
            new int[]{0,-3},
            new int[]{-99}
        };

        for (int i = 0; i < a.Length; i++)
        {
            Console.WriteLine(new M().d(Array.ConvertAll(a[i], e => Convert.ToDouble(e))));
        }
        Console.ReadKey();
    }
}
</code>```

Output:

```<code>0
539
-1055,35694384628
256
1
-16
-3
-99
</code>```

Title: Weapons of Math Instruction

Body:
c#, <s>238</s>, 202 bytes

double d(double[]a){Array.Reverse(a);var s=new Stack<double>(a);int i=0,j;while(s.Count>1){double l=s.Pop(),r=s.Pop();j=i++%5;s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l,r));}return s.Peek();}

I didn't see any c# solution so I will give one. This is my first codegolf. I started writing in c# "two months ago" (though I know Java to some extent).

It uses Stack

Ungolfed and test cases

using System;
using System.Collections.Generic;

class M
{
    double d(double[]a) {
        Array.Reverse(a);
        var s = new Stack<double>(a);
        int i=0,j;
        while (s.Count>1)
        {
            double l=s.Pop(),r=s.Pop();
            j=i++%5;
            s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l, r));
        }
        return s.Peek();
    }

    public static void Main()
    {
        int[][] a = new int[][]{
            new int[]{1,2,3,4,5},
            new int[]{5,12,23,2,4,4,2,6,7},
            new int[]{-8,50,3,3,-123,4,17,99,13},
            new int[]{2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2},
            new int[]{1,0,1,0,1,0},
            new int[]{-9,-8,-1},
            new int[]{0,-3},
            new int[]{-99}
        };

        for (int i = 0; i < a.Length; i++)
        {
            Console.WriteLine(new M().d(Array.ConvertAll(a[i], e => Convert.ToDouble(e))));
        }
        Console.ReadKey();
    }
}

Output:

0
539
-1055,35694384628
256
1
-16
-3
-99


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

答:
Swift 3, 138 bytes

```<code>import Glibc;func l(n:Int)->Int{let r=stride(from:2.0,to:50,by:1);return Int(Set(r.flatMap{x in r.map{pow(x,$0)+pow($0,x)}}).sorted()[n])}
</code>```

Ungolfed code

Try it here

```<code>import Glibc
func l(n: Int) -> Int {
    // Create a Double sequence from 2 to 50 (because pow requires Double)
    let r = stride(from: 2.0, to: 50.0, by: 1.0)

    return Int(Set(r.flatMap {
        x in r.map {
            pow(x, $0) + pow($0, x)
        }
    }).sorted()[n])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Leyland Numbers

Body:
Swift 3, 138 bytes

import Glibc;func l(n:Int)->Int{let r=stride(from:2.0,to:50,by:1);return Int(Set(r.flatMap{x in r.map{pow(x,$0)+pow($0,x)}}).sorted()[n])}

Ungolfed code

Try it here

import Glibc
func l(n: Int) -> Int {
    // Create a Double sequence from 2 to 50 (because pow requires Double)
    let r = stride(from: 2.0, to: 50.0, by: 1.0)

    return Int(Set(r.flatMap {
        x in r.map {
            pow(x, $0) + pow($0, x)
        }
    }).sorted()[n])


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
Bash <s>196</s> <s>117</s> <s>114</s> 93 bytes

Updated to support better time precision by integrating suggestions from @manatwork and @Digital Trauma as well as a few other space optimizations:

d()(date +$1%s.%N;)
b=`d`
for i in {1..8};{ (d -;sleep 8;d +)>>j&}
wait
bc<<<`d`-$b
bc<<<`<j`
```

Note that this assumes the j file is absent at the beginning.

Body:
Bash <s>196</s> <s>117</s> <s>114</s> 93 bytes

Updated to support better time precision by integrating suggestions from @manatwork and @Digital Trauma as well as a few other space optimizations:

d()(date +$1%s.%N;)
b=`d`
for i in {1..8};{ (d -;sleep 8;d +)>>j&}
wait
bc<<<`d`-$b
bc<<<`<j`

Note that this assumes the j file is absent at the beginning.


问:
Golf the repeated totient function
You will take two positive integers n and x as input, and output Euler's totient function (number of positive integers less than x co-prime to x) applied n times.

Testcases

```<code>n x   result
1 10  4
2 10  2
3 10  1
1 100 40
2 100 16
3 100 8
4 100 4
5 100 2
6 100 1
</code>```

答:
MATL, 5 bytes

```<code>:"_Zp
</code>```

Try it online!

```<code>:        % Take n implicitly. Generate vector [1 2 ... n]
"        % For each loop, that is, repeat n times
  _Zp    %   Euler's totient function. Takes x implicitly first time
         % End for. Display implicitly
</code>```

Without using Euler's totient function: 9 bytes

```<code>:"t:Zd1=s
</code>```

Try it online!

```<code>:        % Take n implicitly. Generate range [1 2 ... n]
"        % For each loop, that is, repeat n times
  t      %   Duplicate. Takes x implicitly first time. Call that t
  :      %   Range [1 2 ... t]
  Zd     %   GCD of t and [1 2 ... t], elementwise
  1=s    %   How many times the result equals 1: Euler's totient
         % End for. Display implicitly
</code>```

Title: Golf the repeated totient function

Body:
MATL, 5 bytes

:"_Zp

Try it online!

:        % Take n implicitly. Generate vector [1 2 ... n]
"        % For each loop, that is, repeat n times
  _Zp    %   Euler's totient function. Takes x implicitly first time
         % End for. Display implicitly

Without using Euler's totient function: 9 bytes

:"t:Zd1=s

Try it online!

:        % Take n implicitly. Generate range [1 2 ... n]
"        % For each loop, that is, repeat n times
  t      %   Duplicate. Takes x implicitly first time. Call that t
  :      %   Range [1 2 ... t]
  Zd     %   GCD of t and [1 2 ... t], elementwise
  1=s    %   How many times the result equals 1: Euler's totient
         % End for. Display implicitly


答:
Mathematica, 17 bytes

```<code>EulerPhi~Nest~##&
</code>```

An unnamed function which takes x as the first argument and n as the second. Here EulerPhi~Nest~## is short for Nest[EulerPhi, ##] and then ## expands to a sequence of both arguments so we get Nest[EulerPhi, x, n]. And EulerPhi is of course the totient function.

Title: Golf the repeated totient function

Body:
You will take two positive integers n and x as input, and output Euler's totient function (number of positive integers less than x co-prime to x) applied n times.

Testcases

```<code>n x   result
1 10  4
2 10  2
3 10  1
1 100 40
2 100 16
3 100 8
4 100 4
5 100 2
6 100 1
</code>```

Body:
Mathematica, 17 bytes

EulerPhi~Nest~##&

An unnamed function which takes x as the first argument and n as the second. Here EulerPhi~Nest~## is short for Nest[EulerPhi, ##] and then ## expands to a sequence of both arguments so we get Nest[EulerPhi, x, n]. And EulerPhi is of course the totient function.


答:
Jelly, 3 bytes

```<code>ÆṪ¡
</code>```

Expects x as the first argument and n as the second.

Try it online!

This is as straightforward as it gets: ÆṪ is the built-in totient function and ¡ applies this function as many times as the second argument.

Title: Golf the repeated totient function

Body:
Jelly, 3 bytes

ÆṪ¡

Expects x as the first argument and n as the second.

Try it online!

This is as straightforward as it gets: ÆṪ is the built-in totient function and ¡ applies this function as many times as the second argument.


答:
Python 2, 172 bytes

import threading as H,time as T
m=T.time
z=H.Thread
s=m()
r=[]
def f():n=m();T.sleep(9);f.t+=m()-n
f.t=0
exec"r+=[z(None,f)];r[-1].start();"*8
map(z.join,r)
print m()-s,f.t
```

This requires an OS with time precision greater than 1 second to work properly (in other words, any modern OS). 8 threads are created which sleep for 9 seconds each, resulting in a realtime runtime of ~9 seconds, and a parallel runtime of ~72 seconds.

Though the official documentation says that the Thread constructor should be called with keyword arguments, I throw caution to the wind and use positional arguments anyway. The first argument (group) must be None, and the second argument is the target function.

nneonneo pointed out in the comments that attribute access (e.g. f.t) is shorter than list index access (e.g. t[0]). Unfortunately, in most cases, the few bytes gained from doing this would be lost by needing to create an object that allows user-defined attributes to be created at runtime. Luckily, functions support user-defined attributes at runtime, so I exploit this by saving the total time in the t attribute of f.

Try it online

Thanks to DenkerAffe for -5 bytes with the exec trick.

Thanks to kundor for -7 bytes by pointing out that the thread argument is unnecessary.

Thanks to nneonneo for -7 bytes from miscellaneous improvements.

Title: Wait a minute – in less than ten seconds

Body:
Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

Body:
Python 2, 172 bytes

import threading as H,time as T
m=T.time
z=H.Thread
s=m()
r=[]
def f():n=m();T.sleep(9);f.t+=m()-n
f.t=0
exec"r+=[z(None,f)];r[-1].start();"*8
map(z.join,r)
print m()-s,f.t

This requires an OS with time precision greater than 1 second to work properly (in other words, any modern OS). 8 threads are created which sleep for 9 seconds each, resulting in a realtime runtime of ~9 seconds, and a parallel runtime of ~72 seconds.

Though the official documentation says that the Thread constructor should be called with keyword arguments, I throw caution to the wind and use positional arguments anyway. The first argument (group) must be None, and the second argument is the target function.

nneonneo pointed out in the comments that attribute access (e.g. f.t) is shorter than list index access (e.g. t[0]). Unfortunately, in most cases, the few bytes gained from doing this would be lost by needing to create an object that allows user-defined attributes to be created at runtime. Luckily, functions support user-defined attributes at runtime, so I exploit this by saving the total time in the t attribute of f.

Try it online

Thanks to DenkerAffe for -5 bytes with the exec trick.

Thanks to kundor for -7 bytes by pointing out that the thread argument is unnecessary.

Thanks to nneonneo for -7 bytes from miscellaneous improvements.


答:
05AB1E, 2 bytes

Code:

```<code>FÕ
</code>```

Explanation:

```<code>F   # Do the following n times:
 Õ  #   ..Calculate the totient
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: Golf the repeated totient function

Body:
05AB1E, 2 bytes

Code:

FÕ

Explanation:

F   # Do the following n times:
 Õ  #   ..Calculate the totient

Uses the CP-1252 encoding. Try it online!.


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

Task

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

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

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

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

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

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

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

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

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

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

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

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

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

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

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

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

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

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

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Omam, 137 bytes

```the screams all sound the same
though the truth may vary
don't listen to a word i say
the screams all sound the same
this ship will carry```

Note that I haven't copied it. In fact, I added this code there today.

Title: Simple cat program

Body:
Omam, 137 bytes

the screams all sound the same
though the truth may vary
don't listen to a word i say
the screams all sound the same
this ship will carry

Note that I haven't copied it. In fact, I added this code there today.


答:
J, <s>6</s> 4 bytes

```<code>5&p:
</code>```

Straight-forward approach. Nests the totient function n times on an initial value of x.

Usage

```<code>   f =: 5&p:
   5 f 100
2
</code>```

Explanation

Normally, 5&p: is a monad that computes the totient of its argument. However, when used dyadically, it nests itself on an initial value of its LHS according to the number of times on its RHS.

Title: Golf the repeated totient function

Body:
J, <s>6</s> 4 bytes

5&p:

Straight-forward approach. Nests the totient function n times on an initial value of x.

Usage

   f =: 5&p:
   5 f 100
2

Explanation

Normally, 5&p: is a monad that computes the totient of its argument. However, when used dyadically, it nests itself on an initial value of its LHS according to the number of times on its RHS.


答:
Actually, 4 bytes

```<code>`▒`n
</code>```

Try it online!

This program takes x as the first input, and n as the second input.

Explanation:

```<code>`▒`n
`▒`n  call the following function n times:
 ▒      totient(x)
</code>```

Title: Golf the repeated totient function

Body:
Actually, 4 bytes

`▒`n

Try it online!

This program takes x as the first input, and n as the second input.

Explanation:

`▒`n
`▒`n  call the following function n times:
 ▒      totient(x)


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

答:
Dyalog APL, 8 bytes

```<code>⌊*∘1.5÷⊢
</code>```

⌊n³⁄₂∕n⌋ as follows:

*∘1.5 the power-1.5 function

⊢ the pass-through function

(*∘1.5) ÷ ⊢ is the power-1.5 divided by the number itself

⌊ floor

Uses ⎕DIV←1 which often is default.

For the fun of it, here is a generalized solution that lets you calculate any root without raising to any power < 1:

```<code>⌊⊣(*÷⊣)(1+(÷⊢))
</code>```

Title: Integer square root of integer

Body:
Dyalog APL, 8 bytes

⌊*∘1.5÷⊢

⌊n³⁄₂∕n⌋ as follows:

*∘1.5 the power-1.5 function

⊢ the pass-through function

(*∘1.5) ÷ ⊢ is the power-1.5 divided by the number itself

⌊ floor

Uses ⎕DIV←1 which often is default.

For the fun of it, here is a generalized solution that lets you calculate any root without raising to any power < 1:

⌊⊣(*÷⊣)(1+(÷⊢))


答:
Java (JDK), 136 bytes

n->java.util.stream.IntStream.range(0,900).map(l->l+=Math.pow(l%30+2,l/30+2)+Math.pow(l/30+2,l%30+2)-l).sorted().distinct().toArray()[n]
```

Try it online!

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:
Java (JDK), 136 bytes

n->java.util.stream.IntStream.range(0,900).map(l->l+=Math.pow(l%30+2,l/30+2)+Math.pow(l/30+2,l%30+2)-l).sorted().distinct().toArray()[n]

Try it online!


答:
Mathematica, <s>60</s> <s>48</s> 40 bytes

```<code>(Union@@Array[#^#2+#2^#&,{#,#},2])[[#]]&
</code>```

Uses one-based indexing. Union is used by applying it between each row of the 2D matrix created by the Array. There, Union will flatten the 2D matrix into a list while also removing any duplicates and placing the values in sorted order.

Saved 8 bytes thanks to @LLlAMnYP.

Usage

Title: Leyland Numbers

Body:
Mathematica, <s>60</s> <s>48</s> 40 bytes

(Union@@Array[#^#2+#2^#&,{#,#},2])[[#]]&

Uses one-based indexing. Union is used by applying it between each row of the 2D matrix created by the Array. There, Union will flatten the 2D matrix into a list while also removing any duplicates and placing the values in sorted order.

Saved 8 bytes thanks to @LLlAMnYP.

Usage


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

答:
Oracle SQL 11.2, <s>322</s> <s>304</s> 270 bytes

SELECT o FROM(SELECT REPLACE(SUBSTR(:1,1,1)||REPLACE(SYS_CONNECT_BY_PATH(a||SUBSTR(:1,LEVEL*2+1,1),','),','),'_')o,LEVEL l FROM(SELECT SUBSTR('+-*/_',LEVEL,1)a FROM DUAL CONNECT BY LEVEL<6)CONNECT BY LEVEL<LENGTH(:1)/2)WHERE:2=dbms_aw.eval_number(o)AND l>LENGTH(:1)/2-1;
```

<p>:1 is the list of digits<br>
:2 is the result searched</p>

<p>Un-golfed :</p>

<pre class="lang-sql prettyprint-override"><code>SELECT o
FROM   (
         SELECT REPLACE(SUBSTR(:1,1,1)||REPLACE(SYS_CONNECT_BY_PATH(a||SUBSTR(:1,LEVEL*2+1,1),','),','),'_')o,LEVEL l
         FROM ( -- Create one row per operator
                SELECT SUBSTR('+-*/_',LEVEL,1)a FROM DUAL CONNECT BY LEVEL<6
              ) CONNECT BY LEVEL<LENGTH(:1)/2  -- Create every combination of operators, one per ','
)
WHERE :2=dbms_aw.eval_number(o)  -- filter on result = evaluation
  AND l>LENGTH(:1)/2-1           -- keep only expressions using every digits
</code>```

Title: Find operations required to get result

Body:
Oracle SQL 11.2, <s>322</s> <s>304</s> 270 bytes

SELECT o FROM(SELECT REPLACE(SUBSTR(:1,1,1)||REPLACE(SYS_CONNECT_BY_PATH(a||SUBSTR(:1,LEVEL*2+1,1),','),','),'_')o,LEVEL l FROM(SELECT SUBSTR('+-*/_',LEVEL,1)a FROM DUAL CONNECT BY LEVEL<6)CONNECT BY LEVEL<LENGTH(:1)/2)WHERE:2=dbms_aw.eval_number(o)AND l>LENGTH(:1)/2-1;

:1 is the list of digits

:2 is the result searched

Un-golfed :

SELECT o
FROM   (
         SELECT REPLACE(SUBSTR(:1,1,1)||REPLACE(SYS_CONNECT_BY_PATH(a||SUBSTR(:1,LEVEL*2+1,1),','),','),'_')o,LEVEL l
         FROM ( -- Create one row per operator
                SELECT SUBSTR('+-*/_',LEVEL,1)a FROM DUAL CONNECT BY LEVEL<6
              ) CONNECT BY LEVEL<LENGTH(:1)/2  -- Create every combination of operators, one per ','
)
WHERE :2=dbms_aw.eval_number(o)  -- filter on result = evaluation
  AND l>LENGTH(:1)/2-1           -- keep only expressions using every digits


答:
Java, <s>358  343 337 316</s> 313 bytes

```<code>import static java.lang.System.*;class t extends Thread{public void run(){long s=nanoTime();try{sleep(999);}catch(Exception e){}t+=nanoTime()-s;}static long t,i,x;public static void main(String[]a)throws Exception{x=nanoTime();for(;++i<99;)new t().start();sleep(9000);out.println((nanoTime()-x)/1e9+" "+t/1e9);}}
</code>```

and ungolfed

```<code>import static java.lang.System.*;

class t extends Thread {
    public void run() {
        long s = nanoTime();
        try {
            sleep(999);
        } catch (Exception e) {
        }
        t += nanoTime() - s;
    }

    static long t,i,x;

    public static void main(String[] a) throws Exception {
        x = nanoTime();
        for (; ++i < 99;)
            new t().start();
        sleep(9000);
        out.println((nanoTime() - x) / 1e9 + " " + t / 1e9);
    }
}

</code>```

please don't try it at home, as this solution is not thread safe.

Edit:

I took @A Boschman's and @Adám's suggestions, and now my program require less than 10 seconds to run, and it's shorter by 15 bytes.

Body:
Java, <s>358  343 337 316</s> 313 bytes

import static java.lang.System.*;class t extends Thread{public void run(){long s=nanoTime();try{sleep(999);}catch(Exception e){}t+=nanoTime()-s;}static long t,i,x;public static void main(String[]a)throws Exception{x=nanoTime();for(;++i<99;)new t().start();sleep(9000);out.println((nanoTime()-x)/1e9+" "+t/1e9);}}

and ungolfed

import static java.lang.System.*;

class t extends Thread {
    public void run() {
        long s = nanoTime();
        try {
            sleep(999);
        } catch (Exception e) {
        }
        t += nanoTime() - s;
    }

    static long t,i,x;

    public static void main(String[] a) throws Exception {
        x = nanoTime();
        for (; ++i < 99;)
            new t().start();
        sleep(9000);
        out.println((nanoTime() - x) / 1e9 + " " + t / 1e9);
    }
}

please don't try it at home, as this solution is not thread safe.

Edit:

I took @A Boschman's and @Adám's suggestions, and now my program require less than 10 seconds to run, and it's shorter by 15 bytes.


问:
Golf the Inverse of Exponential Generating Function
Earlier, we talked about exponential generating functions (e.g.f.).

Task

You will take a few terms of a sequence.

Your task is to find another sequence with that many terms, whose e.g.f., when multiplied to the original e.g.f., would be exactly the constant function 1 accurate to that many terms.

That is, given a0=1, a1, a2, ..., an, find b0=1, b1, b2, ..., bn such that a0 + a1x + a2x^2/2! + a3x^3/3! + ... + anx^n/n! multiplied by b0 + b1x + b2x^2/2! + b3x^3/3! + ... + bnx^n/n! equals 1 + O(x^(n+1)).

Specs

They will start at the zeroth power and will be consecutive.

The first term is guaranteed to be 1.

All the terms are guaranteed to be integers.

There will not be negative powers.

Testcases

```<code>Input : 1,0,-1,0,1,0,-1,0 (this is actually cos x)
Output: 1,0, 1,0,5,0,61,0 (this is actually sec x)

Input : 1, 2, 4, 8, 16, 32 (e^(2x))
Output: 1,-2, 4,-8, 16,-32 (e^(-2x))

Input : 1,-1,0,0, 0,  0,  0 (1-x)
Output: 1, 1,2,6,24,120,720 (1/(1-x) = 1+x+x^2+...)
</code>```

答:
Julia, <s>91</s> <s>81</s> 77 bytes

```<code>!v=(b=[1;0v[r=2:end]];for i=r,j=0:i-2 b[i]-=binomial(i-1,j)v[i-j]b[j+1]end;b)
</code>```

Usage: ![1 0 -1 0 1 0 -1 0]

Saved 4 bytes thanks to Dennis!

This is a fairly straightforward implementation - it uses the fact that the "exponential" part causes a binomial to appear in the solution. Otherwise, it's just solving for the relevant coefficients.

Body:
Julia, <s>91</s> <s>81</s> 77 bytes

!v=(b=[1;0v[r=2:end]];for i=r,j=0:i-2 b[i]-=binomial(i-1,j)v[i-j]b[j+1]end;b)

Usage: ![1 0 -1 0 1 0 -1 0]

Saved 4 bytes thanks to Dennis!

This is a fairly straightforward implementation - it uses the fact that the "exponential" part causes a binomial to appear in the solution. Otherwise, it's just solving for the relevant coefficients.


答:
Swift 2, 43 bytes

```<code>let f={a in (0..<a).filter{$0*$0<=a}.last!}
</code>```

Try here. There is a caveat - it won't compile unless the function is called, ie f(255), as type inference is unable to infer the return type.

Title: Integer square root of integer

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

Body:
Swift 2, 43 bytes

let f={a in (0..<a).filter{$0*$0<=a}.last!}

Try here. There is a caveat - it won't compile unless the function is called, ie f(255), as type inference is unable to infer the return type.


Title: Integer square root of integer

Body:
Mathematica, 20

⌊#^1.5/1~Max~#⌋&


答:
Rust, 257, 247 bytes

I use the same times as Mego's Python answer.

Really the only slightly clever bit is using i-i to get a Duration of 0 seconds.

```<code>fn main(){let n=std::time::Instant::now;let i=n();let h:Vec<_>=(0..8).map(|_|std::thread::spawn(move||{let i=n();std::thread::sleep_ms(9000);i.elapsed()})).collect();let mut t=i-i;for x in h{t+=x.join().unwrap();}print!("{:?}{:?}",t,i.elapsed());}
</code>```

Prints:

```<code>Duration { secs: 71, nanos: 995877193 }Duration { secs: 9, nanos: 774491 }
</code>```

Ungolfed:

```<code>fn main(){
    let n = std::time::Instant::now;
    let i = n();
    let h :Vec<_> =
        (0..8).map(|_|
            std::thread::spawn(
                move||{
                    let i = n();
                    std::thread::sleep_ms(9000);
                    i.elapsed()
                }
            )
        ).collect();
    let mut t=i-i;
    for x in h{
        t+=x.join().unwrap();
    }
    print!("{:?}{:?}",t,i.elapsed());
}
</code>```

Edit:
good old for loop is a bit shorter

Body:
Rust, 257, 247 bytes

I use the same times as Mego's Python answer.

Really the only slightly clever bit is using i-i to get a Duration of 0 seconds.

fn main(){let n=std::time::Instant::now;let i=n();let h:Vec<_>=(0..8).map(|_|std::thread::spawn(move||{let i=n();std::thread::sleep_ms(9000);i.elapsed()})).collect();let mut t=i-i;for x in h{t+=x.join().unwrap();}print!("{:?}{:?}",t,i.elapsed());}

Prints:

Duration { secs: 71, nanos: 995877193 }Duration { secs: 9, nanos: 774491 }

Ungolfed:

fn main(){
    let n = std::time::Instant::now;
    let i = n();
    let h :Vec<_> =
        (0..8).map(|_|
            std::thread::spawn(
                move||{
                    let i = n();
                    std::thread::sleep_ms(9000);
                    i.elapsed()
                }
            )
        ).collect();
    let mut t=i-i;
    for x in h{
        t+=x.join().unwrap();
    }
    print!("{:?}{:?}",t,i.elapsed());
}

Edit:
good old for loop is a bit shorter


答:
PowerShell v4, 144 bytes

```<code>$d=date;gjb|rjb
1..20|%{sajb{$x=date;sleep 3;((date)-$x).Ticks/1e7}>$null}
while(gjb -s "Running"){}(gjb|rcjb)-join'+'|iex
((date)-$d).Ticks/1e7
</code>```

Sets $d equal to Get-Date, and clears out any existing job histories with Get-Job | Remove-Job. We then loop 1..20|%{...} and each iteration execute Start-Job passing it the script block {$x=date;sleep 3;((date)-$x).ticks/1e7} for the job (meaning each job will execute that script block). We pipe that output to >$null in order to suppress the feedback (i.e., job name, status, etc.) that gets returned.

The script block sets $x to Get-Date, then Start-Sleep for 3 seconds, then takes a new Get-Date reading, subtracts $x, gets the .Ticks, and divides by 1e7 to get the seconds (with precision).

Back in the main thread, so long as any job is still -Status "Running", we spin inside an empty while loop. Once that's done, we Get-Job to pull up objects for all the existing jobs, pipe those to Receive-Job which will pull up the equivalent of STDOUT (i.e., what they output), -join the results together with +, and pipe it to iex (Invoke-Expression and similar to eval). This will output the resultant sleep time plus overhead.

The final line is similar, in that it gets a new date, subtracts the original date stamp $d, gets the .Ticks, and divides by 1e7 to output the total execution time.

NB

OK, so this is a little bendy of the rules. Apparently on first execution, PowerShell needs to load a bunch of .NET assemblies from disk for the various thread operations as they're not loaded with the default shell profile. Subsequent executions, because the assemblies are already in memory, work fine. If you leave the shell window idle long enough, you'll get PowerShell's built-in garbage collection to come along and unload all those assemblies, causing the next execution to take a long time as it re-loads them. I'm not sure of a way around this.

You can see this in the execution times in the below runs. I started a fresh shell, navigated to my golfing directory, and executed the script. The first run was horrendous, but the second (executed immediately) worked fine. I then left the shell idle for a few minutes to let garbage collection come by, and then that run is again lengthy, but subsequent runs again work fine.

Example runs

```<code>Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.

PS H:\> c:

PS C:\> cd C:\Tools\Scripts\golfing

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
63.232359
67.8403415

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.0809705
8.8991164

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
62.5791712
67.3228933

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.1303589
8.5939405

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.3210352
8.6386886

PS C:\Tools\Scripts\golfing>
</code>```

Body:
PowerShell v4, 144 bytes

$d=date;gjb|rjb
1..20|%{sajb{$x=date;sleep 3;((date)-$x).Ticks/1e7}>$null}
while(gjb -s "Running"){}(gjb|rcjb)-join'+'|iex
((date)-$d).Ticks/1e7

Sets $d equal to Get-Date, and clears out any existing job histories with Get-Job | Remove-Job. We then loop 1..20|%{...} and each iteration execute Start-Job passing it the script block {$x=date;sleep 3;((date)-$x).ticks/1e7} for the job (meaning each job will execute that script block). We pipe that output to >$null in order to suppress the feedback (i.e., job name, status, etc.) that gets returned.

The script block sets $x to Get-Date, then Start-Sleep for 3 seconds, then takes a new Get-Date reading, subtracts $x, gets the .Ticks, and divides by 1e7 to get the seconds (with precision).

Back in the main thread, so long as any job is still -Status "Running", we spin inside an empty while loop. Once that's done, we Get-Job to pull up objects for all the existing jobs, pipe those to Receive-Job which will pull up the equivalent of STDOUT (i.e., what they output), -join the results together with +, and pipe it to iex (Invoke-Expression and similar to eval). This will output the resultant sleep time plus overhead.

The final line is similar, in that it gets a new date, subtracts the original date stamp $d, gets the .Ticks, and divides by 1e7 to output the total execution time.

NB

OK, so this is a little bendy of the rules. Apparently on first execution, PowerShell needs to load a bunch of .NET assemblies from disk for the various thread operations as they're not loaded with the default shell profile. Subsequent executions, because the assemblies are already in memory, work fine. If you leave the shell window idle long enough, you'll get PowerShell's built-in garbage collection to come along and unload all those assemblies, causing the next execution to take a long time as it re-loads them. I'm not sure of a way around this.

You can see this in the execution times in the below runs. I started a fresh shell, navigated to my golfing directory, and executed the script. The first run was horrendous, but the second (executed immediately) worked fine. I then left the shell idle for a few minutes to let garbage collection come by, and then that run is again lengthy, but subsequent runs again work fine.

Example runs

Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.

PS H:\> c:

PS C:\> cd C:\Tools\Scripts\golfing

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
63.232359
67.8403415

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.0809705
8.8991164

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
62.5791712
67.3228933

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.1303589
8.5939405

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.3210352
8.6386886

PS C:\Tools\Scripts\golfing>


答:
Ruby (with parallel gem), 123 116 bytes

```<code>require'parallel'
n=->{Time.now}
t=n[]
q=0
Parallel.each(1..10,:in_threads=>10){z=n[];sleep 6;q+=n[]-z}
puts n[]-t,q
</code>```

Edit: Added the "Time.now" reference from the Ruby answer by histocrat.

Body:
Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

Body:
Ruby (with parallel gem), 123 116 bytes

require'parallel'
n=->{Time.now}
t=n[]
q=0
Parallel.each(1..10,:in_threads=>10){z=n[];sleep 6;q+=n[]-z}
puts n[]-t,q

Edit: Added the "Time.now" reference from the Ruby answer by histocrat.


答:
Go - 189 bytes

Thanks @cat!

```<code>package main
import(."fmt";."time");var m,t=60001,make(chan int,m);func main(){s:=Now();for i:=0;i<m;i++{go func(){Sleep(Millisecond);t<-0}()};c:=0;for i:=0;i<m;i++{c++};Print(Since(s),c)}
</code>```

Outputs (ms):  160.9939ms,60001 (160ms to wait 60.001 seconds)

Body:
Go - 189 bytes

Thanks @cat!

package main
import(."fmt";."time");var m,t=60001,make(chan int,m);func main(){s:=Now();for i:=0;i<m;i++{go func(){Sleep(Millisecond);t<-0}()};c:=0;for i:=0;i<m;i++{c++};Print(Since(s),c)}

Outputs (ms):  160.9939ms,60001 (160ms to wait 60.001 seconds)


问:
Print your code backwards - reverse quine
Write a program that prints its own source code out backwards, in other words an eniuq.

Scoring:

+50 if you use pull data from the Internet.

+25 if you read your own source code.

+1 point per character

Lowest score wins.

Rules:

No using other files (e.g. reverse.txt)

Minimum code length is two characters.

Your program cannot be a palindrome.

答:
Help, WarDoq!, 2 bytes + 25 = 27

```<code> q
</code>```

The space is needed.

Minimum code length is two characters.

Body:
Help, WarDoq!, 2 bytes + 25 = 27

 q

The space is needed.

Minimum code length is two characters.


答:
Haskell, <s>49</s> <s>46</s> <s>44</s> 40 bytes

Thanks @xnor for another again named solution:

```<code>x%0=x
x%n=sum[1|1<-gcd x<$>[1..x]]%(n-1)
</code>```

Old version:

The following is an unnamed pointless function that takes two arguments: (Thanks @Lynn for another two bytes!)

```<code>(!!).iterate(\y->sum[1|t<-[1..y],gcd y t<2])
</code>```

To use it, you can e.g. assign it a name (f=(!!).(...) and then call it via f 10 1 (as an example for the first test case).

Explanation: The lambda function (\y->sum[1|t<-[1..y],gcd y t<2]) is the totient function. iterate f x produces an infinite list [x,f(x),f(f(x)),f(f(f(x))),...] and !! is just for accessing this list at a specific index.

Older version:

```<code>x#n=(iterate(\y->sum[1|t<-[1..y],gcd y t<2])x)!!n
</code>```

Usage e.g. for the first test case: 10#1.

Title: Golf the repeated totient function

Body:
You will take two positive integers n and x as input, and output Euler's totient function (number of positive integers less than x co-prime to x) applied n times.

Testcases

```<code>n x   result
1 10  4
2 10  2
3 10  1
1 100 40
2 100 16
3 100 8
4 100 4
5 100 2
6 100 1
</code>```

Body:
Haskell, <s>49</s> <s>46</s> <s>44</s> 40 bytes

Thanks @xnor for another again named solution:

x%0=x
x%n=sum[1|1<-gcd x<$>[1..x]]%(n-1)

Old version:

The following is an unnamed pointless function that takes two arguments: (Thanks @Lynn for another two bytes!)

(!!).iterate(\y->sum[1|t<-[1..y],gcd y t<2])

To use it, you can e.g. assign it a name (f=(!!).(...) and then call it via f 10 1 (as an example for the first test case).

Explanation: The lambda function (\y->sum[1|t<-[1..y],gcd y t<2]) is the totient function. iterate f x produces an infinite list [x,f(x),f(f(x)),f(f(f(x))),...] and !! is just for accessing this list at a specific index.

Older version:

x#n=(iterate(\y->sum[1|t<-[1..y],gcd y t<2])x)!!n

Usage e.g. for the first test case: 10#1.


答:
Python 2, <s>84</s> <s>78</s> 70 bytes

n,x=input();exec('k=m=1;'+'x-=(x%k<m%k)*x/k;m*=k*k;k+=1;'*x)*n;print x
```
<p><em>Thanks to @xnor for golfing off 8 bytes!</em></p>
<p>Test it on Ideone.</p>
<h3>Background</h3>
<p>By Euler's product formula,</p>
<p><img src="https://i.stack.imgur.com/xsXir.png" alt="Euler's product formula" /></p>
<p>where <strong>φ</strong> denotes Euler's totient function and <strong>p</strong> varies only over prime numbers.</p>
<p>To identify primes, we use a corollary of Wilson's theorem:</p>
<p><img src="https://i.stack.imgur.com/ordYr.png" alt="corollary of Wilson's theorem" /></p>
<h3>How it works</h3>
<p>After reading the input, we construct and execute a certain string. The executed code is roughly equivalent to the following.</p>
<pre class="lang-python prettyprint-override"><code>r = range(x)
for _ in range(n):
    k = 1
    m = 1
    for _ in r:
        x -= (x % k < m % k) * x / k
        m *= k**2
        k += 1
</code>```

The inner loop will set x = φ(x), so executing it n times stores the desired output in x.

At all times, the variable m will be equal to the square of the factorial of k - 1. In fact, we set k = 1 and m = 0!2 = 1 at the beginning of the inner loop.

k varies from its initial value 1 to the initial value of x and is incremented each time the sinner loop is executed. m is updated accordingly by multiplying it by the "old" value of k2.

For the actual calculation of x, recall that m%k will yield 1 if m is prime and 0 if not. This means that x%k<m%k will yield True if and only if both k is a prime number and x is divisible by k.

In this case, (x%k<m%k)*x/k yields x / k, and subtracting it from x replaces its previous value with x(1 - 1/k), as in Euler's product formula. Otherwise, (x%k<m%k)*x/k yields 0 and x remains unchanged.

Title: Golf the repeated totient function

Body:
Python 2, <s>84</s> <s>78</s> 70 bytes

n,x=input();exec('k=m=1;'+'x-=(x%k<m%k)*x/k;m*=k*k;k+=1;'*x)*n;print x

Thanks to @xnor for golfing off 8 bytes!

Test it on Ideone.

Background

By Euler's product formula,

where φ denotes Euler's totient function and p varies only over prime numbers.

To identify primes, we use a corollary of Wilson's theorem:

How it works

After reading the input, we construct and execute a certain string. The executed code is roughly equivalent to the following.

r = range(x)
for _ in range(n):
    k = 1
    m = 1
    for _ in r:
        x -= (x % k < m % k) * x / k
        m *= k**2
        k += 1

The inner loop will set x = φ(x), so executing it n times stores the desired output in x.

At all times, the variable m will be equal to the square of the factorial of k - 1. In fact, we set k = 1 and m = 0!2 = 1 at the beginning of the inner loop.

k varies from its initial value 1 to the initial value of x and is incremented each time the sinner loop is executed. m is updated accordingly by multiplying it by the "old" value of k2.

For the actual calculation of x, recall that m%k will yield 1 if m is prime and 0 if not. This means that x%k<m%k will yield True if and only if both k is a prime number and x is divisible by k.

In this case, (x%k<m%k)*x/k yields x / k, and subtracting it from x replaces its previous value with x(1 - 1/k), as in Euler's product formula. Otherwise, (x%k<m%k)*x/k yields 0 and x remains unchanged.


答:
Groovy, <s>158</s> 143 characters

d={new Date().getTime()}
s=d(j=0)
8.times{Thread.start{b=d(m=1000)
sleep 8*m
synchronized(j){j+=d()-b}}}addShutdownHook{print([(d()-s)/m,j/m])}
```

<p>Sample run:</p>

```bash-4.3$ groovy wait1minute.groovy
[8.031, 64.055]
```

Body:
Groovy, <s>158</s> 143 characters

d={new Date().getTime()}
s=d(j=0)
8.times{Thread.start{b=d(m=1000)
sleep 8*m
synchronized(j){j+=d()-b}}}addShutdownHook{print([(d()-s)/m,j/m])}

Sample run:

bash-4.3$ groovy wait1minute.groovy
[8.031, 64.055]


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

```

答:
Pyke, 22 bytes

```<code>0000 false              0
0001 p and q            &
0010 p and not q        >
0011 p                  Kz
0100 not p and q        <
0101 q                  Q
0110 xor                N
0111 p or q             |
1000 not p and not q    |!
1001 eq                 q
1010 not q              !
1011 p or not q         !&
1100 not p              K!
1101 not p or q         !|
1110 not p or not q     &!
1111 true               1
</code>```

Body:
Pyke, 22 bytes

0000 false              0
0001 p and q            &
0010 p and not q        >
0011 p                  Kz
0100 not p and q        <
0101 q                  Q
0110 xor                N
0111 p or q             |
1000 not p and not q    |!
1001 eq                 q
1010 not q              !
1011 p or not q         !&
1100 not p              K!
1101 not p or q         !|
1110 not p or not q     &!
1111 true               1


Title: Golf the repeated totient function

Body:
Hoon, 84 bytes

|*((pair) ?~(p q $(p (dec p), q (lent (skim (gulf 1 q) |=(@ =(1 d:(egcd +< q))))))))

Ungolfed:

|*  (pair)
  ?~  p
    q
  %=  $
    p  (dec p)
    q  (lent (skim (gulf 1 q) |=(@ =(1 d:(egcd +< q)))))
  ==


答:
Javascript (ES6), 212 203 145 bytes

This code creates 10 images with a time interval of exactly 6 seconds each, upon loading.

The execution time goes a tiny bit above it (due to overhead).

This code overwrites everything in the document!

P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,6e3) >'.repeat(i=10)```
</div>
</div>
</p>

<p>This assumes that you use a single-byte encoding for the backticks, which is required for the Javascript engine to do not trip.</p>

<hr>

<p>Alternativelly, if you don't want to spend 6 seconds waiting, here's a 1-byte-longer solution that finishes in less than a second:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,600) >'.repeat(i=100)</code>```

The difference is that this code waits 600ms across 100 images. This will give a massive ammount of overhead.

Old version (203 bytes):

This code creates 10 iframes with a time interval of exactly 6 seconds each, instead of creating 10 images.

for(P=performance,M=P.now(T=Y=i=0),D=document,X=_=>{T+=_,--i||alert([P.now()-M,T])};i<10;i++)I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)```
</div>
</div>
</p>

<hr>

<p>Original version (212 bytes):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>P=performance,M=P.now(T=Y=0),D=document,X=_=>{T+=_,Y++>8&&alert([P.now()-M,T])},[...''+1e9].map(_=>{I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)})</code>```

Body:
Javascript (ES6), 212 203 145 bytes

This code creates 10 images with a time interval of exactly 6 seconds each, upon loading.

The execution time goes a tiny bit above it (due to overhead).

This code overwrites everything in the document!

P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,6e3) >'.repeat(i=10)

This assumes that you use a single-byte encoding for the backticks, which is required for the Javascript engine to do not trip.

Alternativelly, if you don't want to spend 6 seconds waiting, here's a 1-byte-longer solution that finishes in less than a second:

P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,600) >'.repeat(i=100)

The difference is that this code waits 600ms across 100 images. This will give a massive ammount of overhead.

Old version (203 bytes):

This code creates 10 iframes with a time interval of exactly 6 seconds each, instead of creating 10 images.

for(P=performance,M=P.now(T=Y=i=0),D=document,X=_=>{T+=_,--i||alert([P.now()-M,T])};i<10;i++)I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)

Original version (212 bytes):

P=performance,M=P.now(T=Y=0),D=document,X=_=>{T+=_,Y++>8&&alert([P.now()-M,T])},[...''+1e9].map(_=>{I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)})


答:
Bash + GNU utilities, 85

\time -f%e bash -c 'for i in {1..8};{ \time -aoj -f%e sleep 8&};wait'
paste -sd+ j|bc
```

Forces the use of the time executable instead of the shell builtin by prefixing with a \.

Appends to a file j, which must be empty or non-existent at the start.

Body:
Bash + GNU utilities, 85

\time -f%e bash -c 'for i in {1..8};{ \time -aoj -f%e sleep 8&};wait'
paste -sd+ j|bc

Forces the use of the time executable instead of the shell builtin by prefixing with a \.

Appends to a file j, which must be empty or non-existent at the start.


答:
Julia, 36 bytes

n\x=n>0?~-n\sum(k->gcd(k,x)<2,1:x):x
```

Try it online!

Title: Golf the repeated totient function

Body:
Julia, 36 bytes

n\x=n>0?~-n\sum(k->gcd(k,x)<2,1:x):x

Try it online!


答:
PARI/GP, 33 bytes

Straightforward iteration:

```<code>f(n,x)=for(i=1,x,n=eulerphi(n));n
</code>```

Straightforward recursion:

```<code>f(n,x)=if(x,n,f(eulerphi(n),x-1))
</code>```

Title: Golf the repeated totient function

Body:
PARI/GP, 33 bytes

Straightforward iteration:

f(n,x)=for(i=1,x,n=eulerphi(n));n

Straightforward recursion:

f(n,x)=if(x,n,f(eulerphi(n),x-1))


答:
C, 268 bytes

```<code>#define c(a,b)0      // 0000
#define d(a,b)a&b    // 0001
#define e(a,b)a>b    // 0010
#define f(a,b)a      // 0011
#define g(a,b)a<b    // 0100
#define h(a,b)b      // 0101
#define i(a,b)a^b    // 0110
#define j(a,b)a|b    // 0111
#define k(a,b)!b>a   // 1000
#define l(a,b)a==b   // 1001
#define m(a,b)!b     // 1010
#define n(a,b)!b|a   // 1011
#define o(a,b)!a     // 1100
#define p(a,b)!a|b   // 1101
#define q(a,b)!b|!a  // 1110
#define r(a,b)1      // 1111
</code>```

Macros seem shorter than functions.

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:
C, 268 bytes

#define c(a,b)0      // 0000
#define d(a,b)a&b    // 0001
#define e(a,b)a>b    // 0010
#define f(a,b)a      // 0011
#define g(a,b)a<b    // 0100
#define h(a,b)b      // 0101
#define i(a,b)a^b    // 0110
#define j(a,b)a|b    // 0111
#define k(a,b)!b>a   // 1000
#define l(a,b)a==b   // 1001
#define m(a,b)!b     // 1010
#define n(a,b)!b|a   // 1011
#define o(a,b)!a     // 1100
#define p(a,b)!a|b   // 1101
#define q(a,b)!b|!a  // 1110
#define r(a,b)1      // 1111

Macros seem shorter than functions.


答:
Perl 6, <s> 47 45 44 43 42 41 </s> 39 bytes

<s>{($^x,{+(^$^x .grep: {$_ gcd$x==1})}...*)[$^n]}
{($^x,{+(^$^x Xgcd $x).grep: *==1}...*)[$^n]}
{($^x,{+grep *==1,(^$^x Xgcd $x)}...*)[$^n]}
{($^x,{+grep *==1,(^$^x Xgcd$x)}...*)[$^n]}
{($^x,{+grep 2>*,(^$^x Xgcd$x)}...*)[$^n]}
{($^x,{+grep 2>*,(^$_ Xgcd$_)}...*)[$^n]}</s>
{($^x,{sum 2 X>(^$_ Xgcd$_)}...*)[$^n]}```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{ # parameters are $n,$x ( declared as placeholder parameters )
  (

    $^x, # seed sequence generator with second argument

    { # parameter is $_
      sum
        2
        X[>] # crossed compared using &infix«>»
        (
          0 ..^ $_ # from 0 up to and excluding the parameter
          X[gcd]   # cross apply &infix:<gcd> with:
          $_       # the parameter
        )
    }

    ...  # keep applying that block

    *    # forever

  )[ $^n ] # grab the one at the index indicated by the first argument
}
</code>```

Test:

use v6.c;
use Test;

my @tests = (
  (1, 10) =>  4,
  (2, 10) =>  2,
  (3, 10) =>  1,
  (1,100) => 40,
  (2,100) => 16,
  (3,100) =>  8,
  (4,100) =>  4,
  (5,100) =>  2,
  (6,100) =>  1,
);

plan +@tests;

my &repeated-totient = {($^x,{sum 2 X>(^$_ Xgcd$_)}...*)[$^n]}

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is repeated-totient(|@input), $expected, .gist
}
```

<pre class="lang-none prettyprint-override"><code>1..9
ok 1 - (1 10) => 4
ok 2 - (2 10) => 2
ok 3 - (3 10) => 1
ok 4 - (1 100) => 40
ok 5 - (2 100) => 16
ok 6 - (3 100) => 8
ok 7 - (4 100) => 4
ok 8 - (5 100) => 2
ok 9 - (6 100) => 1
</code>```

Title: Golf the repeated totient function

Body:
Perl 6, <s> 47 45 44 43 42 41 </s> 39 bytes

<s>{($^x,{+(^$^x .grep: {$_ gcd$x==1})}...*)[$^n]}
{($^x,{+(^$^x Xgcd $x).grep: *==1}...*)[$^n]}
{($^x,{+grep *==1,(^$^x Xgcd $x)}...*)[$^n]}
{($^x,{+grep *==1,(^$^x Xgcd$x)}...*)[$^n]}
{($^x,{+grep 2>*,(^$^x Xgcd$x)}...*)[$^n]}
{($^x,{+grep 2>*,(^$_ Xgcd$_)}...*)[$^n]}</s>
{($^x,{sum 2 X>(^$_ Xgcd$_)}...*)[$^n]}

Explanation:

{ # parameters are $n,$x ( declared as placeholder parameters )
  (

    $^x, # seed sequence generator with second argument

    { # parameter is $_
      sum
        2
        X[>] # crossed compared using &infix«>»
        (
          0 ..^ $_ # from 0 up to and excluding the parameter
          X[gcd]   # cross apply &infix:<gcd> with:
          $_       # the parameter
        )
    }

    ...  # keep applying that block

    *    # forever

  )[ $^n ] # grab the one at the index indicated by the first argument
}

Test:

use v6.c;
use Test;

my @tests = (
  (1, 10) =>  4,
  (2, 10) =>  2,
  (3, 10) =>  1,
  (1,100) => 40,
  (2,100) => 16,
  (3,100) =>  8,
  (4,100) =>  4,
  (5,100) =>  2,
  (6,100) =>  1,
);

plan +@tests;

my &repeated-totient = {($^x,{sum 2 X>(^$_ Xgcd$_)}...*)[$^n]}

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is repeated-totient(|@input), $expected, .gist
}

1..9
ok 1 - (1 10) => 4
ok 2 - (2 10) => 2
ok 3 - (3 10) => 1
ok 4 - (1 100) => 40
ok 5 - (2 100) => 16
ok 6 - (3 100) => 8
ok 7 - (4 100) => 4
ok 8 - (5 100) => 2
ok 9 - (6 100) => 1


答:
Ruby, 92

```<code>n=->{Time.now}
t=n[]
a=0
(0..9).map{Thread.new{b=n[];sleep 6;a+=n[]-b}}.map &:join
p n[]-t,a
</code>```

Body:
Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

Body:
Ruby, 92

n=->{Time.now}
t=n[]
a=0
(0..9).map{Thread.new{b=n[];sleep 6;a+=n[]-b}}.map &:join
p n[]-t,a


问:
The Ever Amplifying Zigzag
Write a program or function that takes in a positive integer N and outputs the first N numbers of this amplifying zigzag pattern, using only the lines needed:

```<code>                                         26
                                       25  27                                      .
         10                          24      28                                  .
        9  11                      23          29                              .
 2     8     12                  22              30                          44
1 3   7        13              21                  31                      43
   4 6           14          20                      32                  42
    5              15      19                          33              41
                     16  18                              34          40
                       17                                  35      39
                                                             36  38
                                                               37
</code>```

So, if N is 1 the output is

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

If N is 2, the output is

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

If N is 3 the output is

```<code> 2
1 3
</code>```

If N is 4 the output is

```<code> 2
1 3
   4
</code>```

If N is 10 the output is

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

If N is 19 the output is

```<code>         10
        9  11
 2     8     12
1 3   7        13
   4 6           14
    5              15      19
                     16  18
                       17
</code>```

and so on.

Notes

Each peak or trough of the zigzag reaches its point one more line away from the line with the 1 on it than the previous peak or trough.

N is not limited to 44. The zigzag grows in the same pattern and larger N should be supported.

Numbers with multiple digits should only "touch" at their corners, as depicted. Make sure this works when N is 100 and above.

There should be no empty (or space only) lines in the output except one optional trailing newline.

Any line may have any amount of trailing spaces.

Scoring

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

答:
Haskell, <s>144</s> 142 bytes

```<code>g n|k<-take n$scanl(+)0$[1..]>>= \x->(-1)^x<$[2..2*x]=unlines[[1..n]>>= \x->show x#(k!!(x-1)==y)|y<-[minimum k..maximum k]]
s#g|g=s|1<2=' '<$s
</code>```

Usage example:

```<code>*Main> putStr $ g 19
         10
        9  11
 2     8     12
1 3   7        13
   4 6           14
    5              15      19
                     16  18
                       17
</code>```

How it works:

```<code>s#g|g=s|1<2=' '<$s              -- # is a helper function that expects a string s
                                -- and a boolean g. It returns s if g is True, else
                                -- as many spaces as there a characters in s

k<-take n$                      -- bind k to the first n elements of
 [1..]>>= \x->(-1)^x<$[2..2*x]  -- 2*x-1 copies of (-1)^x for each x in [1,2,3,...]
                                -- i.e. [-1, 1,1,1, -1,-1,-1,-1,-1, 1,1,1,1,1,1,1..]
 scanl(+)0                      -- build partial sums, starting with 0
                                -- i.e. [0,-1,0,1,2,1,0,-1,-2,-3,-2,-1...]
                                -- -> k is the list of y coordinates for the
                                --    numbers 1,2,3,...

 [  |y<-[minimum k..maximum k]] -- for all y coordinates in k
      \x->show x#(k!!(x-1)==y)  -- map the # function
  [1..n]>>=                     -- over [1..n] (the x coordinates)
                                -- where # is called with
                                --  s -> a string representation of x
                                --  g -> True if k at index x equals the current y
unlines                         -- join with newlines
</code>```

Edit: Thanks @Lynn for two bytes!

Title: The Ever Amplifying Zigzag

Body:
Haskell, <s>144</s> 142 bytes

g n|k<-take n$scanl(+)0$[1..]>>= \x->(-1)^x<$[2..2*x]=unlines[[1..n]>>= \x->show x#(k!!(x-1)==y)|y<-[minimum k..maximum k]]
s#g|g=s|1<2=' '<$s

Usage example:

*Main> putStr $ g 19
         10
        9  11
 2     8     12
1 3   7        13
   4 6           14
    5              15      19
                     16  18
                       17

How it works:

s#g|g=s|1<2=' '<$s              -- # is a helper function that expects a string s
                                -- and a boolean g. It returns s if g is True, else
                                -- as many spaces as there a characters in s

k<-take n$                      -- bind k to the first n elements of
 [1..]>>= \x->(-1)^x<$[2..2*x]  -- 2*x-1 copies of (-1)^x for each x in [1,2,3,...]
                                -- i.e. [-1, 1,1,1, -1,-1,-1,-1,-1, 1,1,1,1,1,1,1..]
 scanl(+)0                      -- build partial sums, starting with 0
                                -- i.e. [0,-1,0,1,2,1,0,-1,-2,-3,-2,-1...]
                                -- -> k is the list of y coordinates for the
                                --    numbers 1,2,3,...

 [  |y<-[minimum k..maximum k]] -- for all y coordinates in k
      \x->show x#(k!!(x-1)==y)  -- map the # function
  [1..n]>>=                     -- over [1..n] (the x coordinates)
                                -- where # is called with
                                --  s -> a string representation of x
                                --  g -> True if k at index x equals the current y
unlines                         -- join with newlines

Edit: Thanks @Lynn for two bytes!


问:
Excludivisible numbers
Given an integer N, output the Nth positive number K with the following property in decimal base:

For each digit I at position P of K, the number formed from K by removing the Pth digit (i.e. I) is divisible by I.

Example and remarks

324 is such a number:

3 divides 24

2 divides 34

4 divides 32

Note 1: we assume that the empty number is divisible by anything, like 0. Therefore 1, 2, 3, 4, 5, 6, 7, 8 and 9 are valid.

Note 2: K cannot contain the digit 0, since you cannot divide by 0.

Inputs and outputs

You may take the input as a function argument, through STDIN, etc.

You may return the output from a function, through STDOUT, etc.

You may index those numbers starting from 0 (in which case N >= 0) or from 1 (in which case N > 0), whichever suits you more.

Test cases

Those examples are indexed from 0, so if you indexed from 1, then add 1 to the numbers in the N column.

```<code>N    Output
0    1
4    5
8    9
15   77
16   88
23   155
42   742
47   1113
121  4244
144  6888
164  9999
</code>```

Scoring

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

答:
Ruby, 90

```<code>f=->n,s=?0{0while s.next![?0]||s[1]&&/t/=~s.gsub(/\d/){eval"#$`#$'%#$&>0"};n<1?s:f[n-1,s]}
</code>```

Similar approach to Neil's Javascript answer, but significantly longer due to a lack of implicit type conversion (except that booleans do get converted into strings by gsub, which is nice).

Title: Excludivisible numbers

Body:
Ruby, 90

f=->n,s=?0{0while s.next![?0]||s[1]&&/t/=~s.gsub(/\d/){eval"#$`#$'%#$&>0"};n<1?s:f[n-1,s]}

Similar approach to Neil's Javascript answer, but significantly longer due to a lack of implicit type conversion (except that booleans do get converted into strings by gsub, which is nice).


问:
Convert from base 10 to base 2 without built-in base conversions
Background:

You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.

Problem:

Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is code-golf, the shortest answer in bytes will win.

Input will be anything from -32768 to 32767 (include sign byte handling in your code)

答:
Apps Script + Google Sheets, <s>147</s> <s>144</s> 121 bytes

Script

```<code>function j(decNumb){var str='';do{str=String(decNumb%2)+str;decNumb=decNumb/2|0;}while(decNumb>=1);return parseInt(str);}
</code>```

Sheet

```<code>=j(b1)
</code>```

Modified version of this script by ZygD.

Body:
Apps Script + Google Sheets, <s>147</s> <s>144</s> 121 bytes

Script

function j(decNumb){var str='';do{str=String(decNumb%2)+str;decNumb=decNumb/2|0;}while(decNumb>=1);return parseInt(str);}

Sheet

=j(b1)

Modified version of this script by ZygD.


答:
IA-32 machine code, 63 bytes

Hexdump of the code, with the disassembly:

```<code>0000  33 c0     xor eax, eax;
      c3        ret;

0001  91        xchg eax, ecx;
      23 c2     and eax, edx;
      c3        ret;

0010  3b d1     cmp edx, ecx;
      d6        _emit 0xd6;
      c3        ret;

0011  91        xchg eax, ecx;
      c3        ret;

0100  3b ca     cmp ecx, edx;
      d6        _emit 0xd6;
      c3        ret;

0101  92        xchg eax, edx;
      c3        ret;

0110  91        xchg eax, ecx;
      33 c2     xor eax, edx;
      c3        ret;

0111  8d 04 11  lea eax, [ecx + edx];
      c3        ret;

1000  91        xchg eax, ecx; // code provided by l4m2
      09 d0     or eax, edx;
      48        dec eax;
      c3        ret;

1001  3b ca     cmp ecx, edx;
      0f 94 c0  sete al;
      c3        ret;

1010  92        xchg eax, edx;
      48        dec eax;
      c3        ret;

1011  39 d1     cmp ecx, edx; // code provided by l4m2
      d6        _emit 0xd6;
      40        inc aex;
      c3        ret;

1100  91        xchg eax, ecx;
      48        dec eax;
      c3        ret;

1101  3b d1     cmp edx, ecx; // code inspired by l4m2
      d6        _emit 0xd6;
      40        inc aex;
      c3        ret;

1110  8d 44 11 fe   lea eax, [ecx+edx-2] // code provided by l4m2
      c3        ret;

1111  91        xchg eax, ecx;
      40        inc eax;
      c3        ret;
</code>```

The code is longer than it could be, because it uses a standard coding convention: input in ecx and edx, and output in al. This may be expressed in C as

```<code>unsigned char __fastcall func(int, int);
</code>```

It seems that MS Visual Studio doesn't understand the undocumented SALC opcode, so I had to use its code, instead of name.

Thanks you l4m2 for improving some of the code samples!

Body:
IA-32 machine code, 63 bytes

Hexdump of the code, with the disassembly:

0000  33 c0     xor eax, eax;
      c3        ret;

0001  91        xchg eax, ecx;
      23 c2     and eax, edx;
      c3        ret;

0010  3b d1     cmp edx, ecx;
      d6        _emit 0xd6;
      c3        ret;

0011  91        xchg eax, ecx;
      c3        ret;

0100  3b ca     cmp ecx, edx;
      d6        _emit 0xd6;
      c3        ret;

0101  92        xchg eax, edx;
      c3        ret;

0110  91        xchg eax, ecx;
      33 c2     xor eax, edx;
      c3        ret;

0111  8d 04 11  lea eax, [ecx + edx];
      c3        ret;

1000  91        xchg eax, ecx; // code provided by l4m2
      09 d0     or eax, edx;
      48        dec eax;
      c3        ret;

1001  3b ca     cmp ecx, edx;
      0f 94 c0  sete al;
      c3        ret;

1010  92        xchg eax, edx;
      48        dec eax;
      c3        ret;

1011  39 d1     cmp ecx, edx; // code provided by l4m2
      d6        _emit 0xd6;
      40        inc aex;
      c3        ret;

1100  91        xchg eax, ecx;
      48        dec eax;
      c3        ret;

1101  3b d1     cmp edx, ecx; // code inspired by l4m2
      d6        _emit 0xd6;
      40        inc aex;
      c3        ret;

1110  8d 44 11 fe   lea eax, [ecx+edx-2] // code provided by l4m2
      c3        ret;

1111  91        xchg eax, ecx;
      40        inc eax;
      c3        ret;

The code is longer than it could be, because it uses a standard coding convention: input in ecx and edx, and output in al. This may be expressed in C as

unsigned char __fastcall func(int, int);

It seems that MS Visual Studio doesn't understand the undocumented SALC opcode, so I had to use its code, instead of name.

Thanks you l4m2 for improving some of the code samples!