问:
Nine Nines of Uptime
Uptime is a very important metric, as we all know, so we'd like to measure the uptime since our service was first launched. The SLA specifies an uptime of a certain number of nines, such as 3 nines for at least 99.9% uptime, or 1 nine for at least 90% uptime, and you're wondering if you've actually met the SLA or not. Since you know the service went down last friday night when someone pushed to production, and since this is basically standard practice here, you figure there's no need for your code to handle 100% uptime as a special case.

Everytime a server stops or starts, Nagios sends you an email. The service in question has some level of fault tolerance, so only m servers have to be online for the service to be available. You just wrote a quick script to extract the important information from these emails. Now it's time for the fun part, and you're in the mood for golfing.

Your task is to write a program or function that analyzes the input, figures out the uptime, and prints the largest integer number of nines achieved by the service.

Input:

The number of servers required to be running for the service to be considered online: m > 0.

Followed by at least one line, one for each server. Each line contains start/stop times for that server. Since we've measured this since the service was launched, the first number is the time the server started the first time. The second time is a stop time, the third another start time etc.

No single server is ever started and stopped at the same time.

This means that if the server is currently running, you haven't gotten an email about it shutting down yet, so the number of numbers on that line would be odd.

The lines are sorted, but the ordering between different lines is not enforced.

The input is EOF-terminated. The last character of the input will be \n followed by EOF (ctrl+D).

The time starts at time 0 and ends at the last recorded start/stop of a single server, since that's all the information we have so far. This can be done by adding max(last number on each line) to the end of all odd-length lines.

Time is discrete.

All input numbers are guaranteed to fit inside a 32bit integer.

The service will never have 100% uptime.

If you would like to add an integer telling you how many servers there are, you may do so. You may also add an integer in the beginning of each server line telling you how many measurements there are for that server. See example in first testcase. You may also use whatever native format you'd like.

Output:

The output consists of a single integer; the highest number of nines that you can guarantee you had in hindsight, i.e. 3 for at least 99.9% uptime or 4 for at least 99.99% uptime.

Testcases:

First:

```<code>1
0 5 8 10
0 1 7

-> 1
</code>```

First, with counts (if you prefer that):

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

-> 1
</code>```

Second:

```<code>1
0 999 1001 2000

-> 3
</code>```

Third:

```<code>3
0 42

-> 0
</code>```

Reference implementation: (Python 2)

```<code>"""
Slow and huge, but useful for checking smaller inputs.

input: m, followed by n lines of start and stop times, all servers are turned off in the beginning, all numbers fit inside 32bit signed integers, counts are optional
output: number of nines of uptime

example:
1
0 5 8 9
0 1 7
parsed:
1st node: on 0:5, 7:9
2nd node: on 0:1, 6:9
at least one server is running during:
0:5, 7:9
known time interval: 0:9, only timestep 6 is down, so 90% uptime during the part we can see.
output:
1

"""

import sys

def rangeify(l):
    res = []
    for i in range(0, len(l), 2):
        res += range(l[i], l[i + 1] + 1)
    return res

def parse():
    m = input()
    lines = [map(int, x.split()) for x in sys.stdin.read().split("\n")[:-1]]
    if not lines:
        return [], m
    top = max(map(max, lines))
    nlines = [x + [top] if len(x) % 2 else x for x in lines]

    n2lines = map(rangeify, nlines)
    return n2lines, m

def flatten(ls):
    res = []
    for l in ls:
        res += l
    return sorted(res)

def join(ups):
    res = {}
    for up in ups:
        if up not in res:
            res[up] = 0
        res[up] += 1
    return res

def bin(ups, m):
    res = []
    for up in range(max(ups)+1):
        res += [up in ups and ups[up] >= m]
    return res

def nines(a):
    s = ("%.15f" % a)[2:]
    s2 = s.lstrip("9")
    return len(s) - len(s2)

def solve(l, m):
    if len(l) < m:
        return nines(0)
    b = bin(join(flatten(l)), m)
    return nines(sum(b) / float(len(b)))

print solve(*parse())
</code>```

答:
JavaScript (ES6), 161 bytes

```<code>(m,a)=>a.map(b=>b.map(n=>l=n>l?n:l),l=0)|a.map(b=>c.map((_,i)=>{k=b[j]==i;j+=k;n^=k;c[i]+=n|k},j=n=0),c=Array(++l).fill(0))|Math.log10(l/c.filter(n=>n<m).length)
</code>```

Accepts an integer representing the minimum number of concurrent servers and an array of arrays representing the start and stop times of each server. Edit: Now uses inclusive ranges, so correctly returns 1 for the first example.

Title: Nine Nines of Uptime

Body:
JavaScript (ES6), 161 bytes

(m,a)=>a.map(b=>b.map(n=>l=n>l?n:l),l=0)|a.map(b=>c.map((_,i)=>{k=b[j]==i;j+=k;n^=k;c[i]+=n|k},j=n=0),c=Array(++l).fill(0))|Math.log10(l/c.filter(n=>n<m).length)

Accepts an integer representing the minimum number of concurrent servers and an array of arrays representing the start and stop times of each server. Edit: Now uses inclusive ranges, so correctly returns 1 for the first example.


问:
Greatest Number in a Range When The Sum of Squares of its Prime Factors are Subtracted
The formula

Take for instance the number 300

The prime factors of 300 are [2, 3, 5] (unique numbers that are
factors of 300 and prime)

Squaring each of those numbers will give
you [4, 9, 25]

Summing that list will give you 4 + 9 + 25 = 38

Finally subtract that sum (38) from your original number 300-38 = 262 (this is the result)

Input

Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.

Output

Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)

Test Cases

```<code>Input: 3       Output: 2, -2
Input: 10      Output: 8, 4
Input: 50      Output: 48, 35
Input: 1000    Output: 1000, 971
Input: 9999    Output: 9984, 9802
</code>```

Worked Through Example

Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)

```<code>Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2   [2]       [4]         4              -2
3   [3]       [9]         9              -6
4   [2]       [4]         4               0
5   [5]       [25]        25             -20
6   [2, 3]    [4, 9]      13             -7
7   [7]       [49]        49             -42
8   [2]       [4]         4               4
9   [3]       [9]         9               0
10  [2, 5]    [4, 25]     29             -19
</code>```

As you can see the greatest result is 4, which was a result of inputting the value 8 into the formula. That means the output for an input of 10 should be 8, 4

Scoring & Rules

The default rules for inputs and outputs apply: Default for Code Golf: Input/Output methods

The standard loopholes are forbidden: Loopholes that are forbidden by default

Submissions can be functions or full programs

Shortest code in bytes wins

答:
Haskell, 91 bytes

```<code>f m=reverse$maximum[[n-sum[p^2|p<-[2..n],mod n p<1,mod(product[1..p-1]^2)p>0],n]|n<-[2..m]]
</code>```

Usage example: f 50-> [48,35].

Prime factor functions are available only via import Data.Numbers.Primes which costs too many bytes, so I'm using @Lynn's prime checker. The rest is straight forward: for input m loop n through [2..m] and in an inner loop p through [2..n]. Keep all p that are prime and divide n, square and sum.

ContentLicense: CC BY-SA 3.0

Body:
Haskell, 91 bytes

f m=reverse$maximum[[n-sum[p^2|p<-[2..n],mod n p<1,mod(product[1..p-1]^2)p>0],n]|n<-[2..m]]

Usage example: f 50-> [48,35].

Prime factor functions are available only via import Data.Numbers.Primes which costs too many bytes, so I'm using @Lynn's prime checker. The rest is straight forward: for input m loop n through [2..m] and in an inner loop p through [2..n]. Keep all p that are prime and divide n, square and sum.


问:
AppleSauce Fader
Back in the day, all the 1337 kids used text faders in chatrooms. I don't know about you guys, but I want to feel cool like they did. The only problem is that their old scripts and applications were heavily coupled to the software they were made for, so I can't just make use of this amazing functionality wherever I want. I also want the solution to be easily portable so you're going to need to make the code as small as possible so that it will fit on my floppy disk (I'd rather only carry one floppy but if your source code is too big I can carry more than one :P).

Input

A list of colors (rgb, hex, names, etc)

Text to format

Your program should expect the list of colors to contain at least 2 colors.

Text to format can be any length greater than zero and characters will be limited to printable ascii. (Hint: Longer text inputs may require you to reuse intermediate colors for consecutive characters)

Output

The output text should not differ from the input text in any way other than font  and/or markup/styling (Note: if your output contains html markup then you'll need to html encode the input). You may output text with markup/styling (html style tags, console colors, etc.) or a picture of the faded text. All color hexes should be present in the output unless the input does not contain enough characters to meet this requirement. If this is the case, then consult the priority rules to determine which color hexes should be present in your output. The order or these colors in your output should still be input order.

Color Priority Rules

In the event that the input is one character, the first color will be used

In the event that there are only two characters, the first and last color will be used

In the event that there are more than three colors and more colors than characters, the first and last colors should be prioritized, then the rest of the colors in their inputted order.

In the event that there are more characters than colors, the characters should fade from one color to the next using intermediate colors

Examples (Priority rules 1-3 respectively):

# Colors | Color0 | ... | Colorn | Text

3 ff0000 0000ff ffff00 M ->

3 ff0000 0000ff ffff00 hi ->

4 ff0000 0000ff ffff00 0fff00 sup ->

To be clear, the text color should fade from one color hex to the next. The fade does not have to be perfectly uniform but it shouldn't be an abrupt color change unless there aren't enough characters to fade nicely. Generally this fade is achieved by choosing intermediate colors for each of the characters by incrementing/decrementing the rgb values by some interval determined by the number of characters you have to work with and the difference between the colors. For example if we needed a single color between  (#ff0000) and  (#000000), we might choose  as it sits right in the middle.  Optimal output will look rather pretty.

Example (Priority rule 4):

3 ff0000 ff7f00 f0ff00 To be or not to be, that is the question... ->

-OR-

```<code><span style="color:#ff0000;">T</span><span style="color:#ff0600;">o</span><span style="color:#ff0c00;"> </span><span style="color:#ff1200;">b</span><span style="color:#ff1800;">e</span><span style="color:#ff1e00;"> </span><span style="color:#ff2400;">o</span><span style="color:#ff2a00;">r</span><span style="color:#ff3000;"> </span><span style="color:#ff3600;">n</span><span style="color:#ff3c00;">o</span><span style="color:#ff4300;">t</span><span style="color:#ff4900;"> </span><span style="color:#ff4f00;">t</span><span style="color:#ff5500;">o</span><span style="color:#ff5b00;"> </span><span style="color:#ff6100;">b</span><span style="color:#ff6700;">e</span><span style="color:#ff6d00;">,</span><span style="color:#ff7300;"> </span><span style="color:#ff7900;">t</span><span style="color:#ff7f00;">h</span><span style="color:#fe8500;">a</span><span style="color:#fe8b00;">t</span><span style="color:#fd9100;"> </span><span style="color:#fc9700;">i</span><span style="color:#fb9d00;">s</span><span style="color:#fba400;"> </span><span style="color:#faaa00;">t</span><span style="color:#f9b000;">h</span><span style="color:#f9b600;">e</span><span style="color:#f8bc00;"> </span><span style="color:#f7c200;">q</span><span style="color:#f6c800;">u</span><span style="color:#f6ce00;">e</span><span style="color:#f5d400;">s</span><span style="color:#f4da00;">t</span><span style="color:#f4e100;">i</span><span style="color:#f3e700;">o</span><span style="color:#f2ed00;">n</span><span style="color:#f1f300;">.</span><span style="color:#f1f900;">.</span><span style="color:#f0ff00;">.</span>
</code>```

In your answer please specify how your output should be displayed (as html, in a console, as an image, etc.).

* All black backgrounds are only for color emphasis and are not required

Scoring

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

If you manage to add fade to individual characters then I'll forever think you're cool (but no bonus to score as this will not be fair for some langs)

答:
Pyth, 126 bytes

Obligatory root-mean-square average instead of direct arithmetic mean.

```<code>L%"<span style=\"color:#%s\">%s</span>",smt.H+256s*255@d2ebhbMm+hG*-eGhGcdHH=Q^RL2Q+smsyMC,hdCgRlhdCedC,ctlQPzC,QtQy,ez?tlzeQh
</code>```

Try it online!

Sample output:

Title: AppleSauce Fader

Body:
Pyth, 126 bytes

Obligatory root-mean-square average instead of direct arithmetic mean.

L%"<span style=\"color:#%s\">%s</span>",smt.H+256s*255@d2ebhbMm+hG*-eGhGcdHH=Q^RL2Q+smsyMC,hdCgRlhdCedC,ctlQPzC,QtQy,ez?tlzeQh

Try it online!

Sample output:


答:
Pyth - 26 bytes

```<code>/`.Omgsm%lf<dTk2.QQeSs.Q`9
</code>```

Try it online here.

Title: Nine Nines of Uptime

Body:
Uptime is a very important metric, as we all know, so we'd like to measure the uptime since our service was first launched. The SLA specifies an uptime of a certain number of nines, such as 3 nines for at least 99.9% uptime, or 1 nine for at least 90% uptime, and you're wondering if you've actually met the SLA or not. Since you know the service went down last friday night when someone pushed to production, and since this is basically standard practice here, you figure there's no need for your code to handle 100% uptime as a special case.

Everytime a server stops or starts, Nagios sends you an email. The service in question has some level of fault tolerance, so only m servers have to be online for the service to be available. You just wrote a quick script to extract the important information from these emails. Now it's time for the fun part, and you're in the mood for golfing.

Your task is to write a program or function that analyzes the input, figures out the uptime, and prints the largest integer number of nines achieved by the service.

Input:

The number of servers required to be running for the service to be considered online: m > 0.

Followed by at least one line, one for each server. Each line contains start/stop times for that server. Since we've measured this since the service was launched, the first number is the time the server started the first time. The second time is a stop time, the third another start time etc.

No single server is ever started and stopped at the same time.

This means that if the server is currently running, you haven't gotten an email about it shutting down yet, so the number of numbers on that line would be odd.

The lines are sorted, but the ordering between different lines is not enforced.

The input is EOF-terminated. The last character of the input will be \n followed by EOF (ctrl+D).

The time starts at time 0 and ends at the last recorded start/stop of a single server, since that's all the information we have so far. This can be done by adding max(last number on each line) to the end of all odd-length lines.

Time is discrete.

All input numbers are guaranteed to fit inside a 32bit integer.

The service will never have 100% uptime.

If you would like to add an integer telling you how many servers there are, you may do so. You may also add an integer in the beginning of each server line telling you how many measurements there are for that server. See example in first testcase. You may also use whatever native format you'd like.

Output:

The output consists of a single integer; the highest number of nines that you can guarantee you had in hindsight, i.e. 3 for at least 99.9% uptime or 4 for at least 99.99% uptime.

Testcases:

First:

```<code>1
0 5 8 10
0 1 7

-> 1
</code>```

First, with counts (if you prefer that):

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

-> 1
</code>```

Second:

```<code>1
0 999 1001 2000

-> 3
</code>```

Third:

```<code>3
0 42

-> 0
</code>```

Reference implementation: (Python 2)

```<code>"""
Slow and huge, but useful for checking smaller inputs.

input: m, followed by n lines of start and stop times, all servers are turned off in the beginning, all numbers fit inside 32bit signed integers, counts are optional
output: number of nines of uptime

example:
1
0 5 8 9
0 1 7
parsed:
1st node: on 0:5, 7:9
2nd node: on 0:1, 6:9
at least one server is running during:
0:5, 7:9
known time interval: 0:9, only timestep 6 is down, so 90% uptime during the part we can see.
output:
1

"""

import sys

def rangeify(l):
    res = []
    for i in range(0, len(l), 2):
        res += range(l[i], l[i + 1] + 1)
    return res

def parse():
    m = input()
    lines = [map(int, x.split()) for x in sys.stdin.read().split("\n")[:-1]]
    if not lines:
        return [], m
    top = max(map(max, lines))
    nlines = [x + [top] if len(x) % 2 else x for x in lines]

    n2lines = map(rangeify, nlines)
    return n2lines, m

def flatten(ls):
    res = []
    for l in ls:
        res += l
    return sorted(res)

def join(ups):
    res = {}
    for up in ups:
        if up not in res:
            res[up] = 0
        res[up] += 1
    return res

def bin(ups, m):
    res = []
    for up in range(max(ups)+1):
        res += [up in ups and ups[up] >= m]
    return res

def nines(a):
    s = ("%.15f" % a)[2:]
    s2 = s.lstrip("9")
    return len(s) - len(s2)

def solve(l, m):
    if len(l) < m:
        return nines(0)
    b = bin(join(flatten(l)), m)
    return nines(sum(b) / float(len(b)))

print solve(*parse())
</code>```

Body:
Pyth - 26 bytes

/`.Omgsm%lf<dTk2.QQeSs.Q`9

Try it online here.


问:
Mean bits: an average challenge
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

var QUESTION_ID=80586,OVERRIDE_USER=20283;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+)(?=[^\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:400px;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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

答:
Pyth, 6 bytes

```<code>.Oml.B
</code>```

Try it online here.

```<code>.Oml.BdUQ              Filling in implict vars

.O                     Average of list
 m   UQ                Map over [0..input)
  l                    Length of
   .B                  Binary string representation of int
    d                  Lambda var
</code>```

Title: Mean bits: an average challenge

Body:
Pyth, 6 bytes

.Oml.B

Try it online here.

.Oml.BdUQ              Filling in implict vars

.O                     Average of list
 m   UQ                Map over [0..input)
  l                    Length of
   .B                  Binary string representation of int
    d                  Lambda var


答:
Python 3, 46 Bytes

```<code>lambda x:sum(len(bin(i))-2for i in range(x))/x
</code>```

Call it like

```<code>f = lambda x: sum(len(bin(i))-2for i in range(x))/x
print(f(6))
# 2.0
</code>```

I had to revert the map revision because it failed for input of 5

Title: Mean bits: an average challenge

Body:
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

var QUESTION_ID=80586,OVERRIDE_USER=20283;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+)(?=[^\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:400px;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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Body:
Python 3, 46 Bytes

lambda x:sum(len(bin(i))-2for i in range(x))/x

Call it like

f = lambda x: sum(len(bin(i))-2for i in range(x))/x
print(f(6))
# 2.0

I had to revert the map revision because it failed for input of 5


问:
Include a JavaScript script with JavaScript
To dynamically include a JavaScript file in a web page, you'd normally insert a

答:
89 bytes

```<code>n=[];for(i in d=document)n.push(i);d.body[n[173]](d[n[41]]`script`).src=`//goo.gl/rPQ0Jk`
</code>```

This is incredibly browser-dependent. Actually even worse than that, it pretty much only works on codegolf.stackexchange.com, in the browser console, in FireFox. Ah well.

Please don't get too mad when it (likely) doesn't work on your particular browser configuration, since if it is even slightly different from mine it could fail.

(yeah, probably invalid because of that. Not going to win anyway.)

Body:
89 bytes

n=[];for(i in d=document)n.push(i);d.body[n[173]](d[n[41]]`script`).src=`//goo.gl/rPQ0Jk`

This is incredibly browser-dependent. Actually even worse than that, it pretty much only works on codegolf.stackexchange.com, in the browser console, in FireFox. Ah well.

Please don't get too mad when it (likely) doesn't work on your particular browser configuration, since if it is even slightly different from mine it could fail.

(yeah, probably invalid because of that. Not going to win anyway.)


答:
Octave, 29 bytes

```<code>@(n)1+sum(fix(log2(1:n-1)))/n
</code>```

Explanation

```<code>              log2(1:n-1)       % log2 of numbers in range [1..n-1]
                                % why no 0? because log2(0) = -Inf  :/
          fix(           )      % floor (more or less, for positive numbers)
      sum(                )     % sum... wait, didn't we miss a +1 somewhere?
                                % and what about that missing 0?
                           /n   % divide by n for the mean
    1+                          % and add (1/n) for each of the n bit lengths
                                % (including 0!)
</code>```

Sample run on ideone.

Title: Mean bits: an average challenge

Body:
Octave, 29 bytes

@(n)1+sum(fix(log2(1:n-1)))/n

Explanation

              log2(1:n-1)       % log2 of numbers in range [1..n-1]
                                % why no 0? because log2(0) = -Inf  :/
          fix(           )      % floor (more or less, for positive numbers)
      sum(                )     % sum... wait, didn't we miss a +1 somewhere?
                                % and what about that missing 0?
                           /n   % divide by n for the mean
    1+                          % and add (1/n) for each of the n bit lengths
                                % (including 0!)

Sample run on ideone.


答:
Ruby, <s>44</s> 34 bytes

Now starring the formula used by @Sp3000

```<code>->x{(2.0-2**b=x.to_s(2).size)/x+b}
</code>```

Old version:

```<code>->x{r=0.0;x.times{|i|r+=i.to_s(2).size};r/x}
</code>```

Title: Mean bits: an average challenge

Body:
Ruby, <s>44</s> 34 bytes

Now starring the formula used by @Sp3000

->x{(2.0-2**b=x.to_s(2).size)/x+b}

Old version:

->x{r=0.0;x.times{|i|r+=i.to_s(2).size};r/x}


答:
Minkolang 0.15, 23 bytes

```<code>n$z1z[i1+2l$M$Y+]kz$:N.
</code>```

Try it here!

Explanation

```<code>n$z                       Take number from input and store it in register (n)
   1                      Push 1 onto the stack
    z[                    For loop that repeats n times
      i1+                 Loop counter + 1
         2l$M             log_2
             $Y           Ceiling
               +          Add top two elements of stack
                ]         Close for loop
                 z$:      Float divide by n
                    N.    Output as number and stop.
</code>```

Pretty straightfoward implementation.

Title: Mean bits: an average challenge

Body:
Minkolang 0.15, 23 bytes

n$z1z[i1+2l$M$Y+]kz$:N.

Try it here!

Explanation

n$z                       Take number from input and store it in register (n)
   1                      Push 1 onto the stack
    z[                    For loop that repeats n times
      i1+                 Loop counter + 1
         2l$M             log_2
             $Y           Ceiling
               +          Add top two elements of stack
                ]         Close for loop
                 z$:      Float divide by n
                    N.    Output as number and stop.

Pretty straightfoward implementation.


答:
JavaScript ES5, 55 bytes

```<code>n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`)
</code>```

Explanation

```<code>n =>   // anonymous function w/ arg `n`
  for( // loop
      o=0,  // initalize bit counter to zero
      p=n   // copy the input
    ;n-- // will decrease input every iteration, will decrease until it's zero
    ;o+=    // add to the bitcounter
        n.toString(2)  // the binary representation of the current itearations's
                     .length // length
        /p   // divided by input copy (to avergage)
   );o       // return o variable
</code>```

Title: Mean bits: an average challenge

Body:
JavaScript ES5, 55 bytes

n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`)

Explanation

n =>   // anonymous function w/ arg `n`
  for( // loop
      o=0,  // initalize bit counter to zero
      p=n   // copy the input
    ;n-- // will decrease input every iteration, will decrease until it's zero
    ;o+=    // add to the bitcounter
        n.toString(2)  // the binary representation of the current itearations's
                     .length // length
        /p   // divided by input copy (to avergage)
   );o       // return o variable


答:
Python 3, 43 bytes

def f(n):x=len(bin(n))-2;return(2-2**x)/n+x
```

<p>Makes use of the formula on the OEIS page. Surprisingly, a named function is somehow cheaper here because of the assignment to <code>x</code>.</p>

<p>Alternative approach for 46 bytes:</p>

<pre class="lang-py prettyprint-override"><code>lambda n:-~sum(map(int.bit_length,range(n)))/n
</code>```

Unfortunately, the -~ is necessary since (0).bit_length() is 0, but even then it'd be a byte too long.

Title: Mean bits: an average challenge

Body:
Python 3, 43 bytes

def f(n):x=len(bin(n))-2;return(2-2**x)/n+x

Makes use of the formula on the OEIS page. Surprisingly, a named function is somehow cheaper here because of the assignment to x.

Alternative approach for 46 bytes:

lambda n:-~sum(map(int.bit_length,range(n)))/n

Unfortunately, the -~ is necessary since (0).bit_length() is 0, but even then it'd be a byte too long.


答:
Julia, 28 bytes

```<code>n->mean(ceil(log2([2;2:n])))
</code>```

Since bin doesn't automatically map over arrays, we're using ceil(log2(n)) to get the number of bits in n-1. This works out nicely because Julia's a:b notation is inclusive on both ends, so 2:n is a range from 2 to n, but we're really calculating the number of bits for numbers in the range 1:n-1. Unfortunately though, we need to tack on an extra 2 to account for 0.

Try it online!

Title: Mean bits: an average challenge

Body:
Julia, 28 bytes

n->mean(ceil(log2([2;2:n])))

Since bin doesn't automatically map over arrays, we're using ceil(log2(n)) to get the number of bits in n-1. This works out nicely because Julia's a:b notation is inclusive on both ends, so 2:n is a range from 2 to n, but we're really calculating the number of bits for numbers in the range 1:n-1. Unfortunately though, we need to tack on an extra 2 to account for 0.

Try it online!


答:
Jelly, 6 bytes

```<code>R’BFL÷
</code>```

Try it online!

```<code>R’BFL÷  Main monadic chain. Argument: n

R       yield [1, 2, ..., n]
 ’      decrement; yield [0, 1, ..., n-1]
  B     convert to binary; yield [[0], [1], [1,0], [1,1], ...]
   F    flatten list; yield [0, 1, 1, 0, 1, 1, ...]
    L   length of list
     ÷  divide [by n]
</code>```

Title: Mean bits: an average challenge

Body:
Jelly, 6 bytes

R’BFL÷

Try it online!

R’BFL÷  Main monadic chain. Argument: n

R       yield [1, 2, ..., n]
 ’      decrement; yield [0, 1, ..., n-1]
  B     convert to binary; yield [[0], [1], [1,0], [1,1], ...]
   F    flatten list; yield [0, 1, 1, 0, 1, 1, ...]
    L   length of list
     ÷  divide [by n]


答:
MATL, 9 bytes

```<code>q:ZlksG/Q
</code>```

Try it Online!

Modified version with all test cases

Explanation

```<code>    % Implicitly grab input (N)
q:  % Create array from 1:N-1
Zl  % Compute log2 for each element of the array
k   % Round down to the nearest integer
s   % Sum all values in the array
G   % Explicitly grab input again
/   % Divide by the input
Q   % Add 1 to account for 0 in [0, ... N - 1]
    % Implicitly display the result
</code>```

Title: Mean bits: an average challenge

Body:
MATL, 9 bytes

q:ZlksG/Q

Try it Online!

Modified version with all test cases

Explanation

    % Implicitly grab input (N)
q:  % Create array from 1:N-1
Zl  % Compute log2 for each element of the array
k   % Round down to the nearest integer
s   % Sum all values in the array
G   % Explicitly grab input again
/   % Divide by the input
Q   % Add 1 to account for 0 in [0, ... N - 1]
    % Implicitly display the result


答:
J, <s>21</s> <s>17</s> 15 bytes

From 17 bytes to 15 bytes thanks to @Dennis.

```<code>+/@:%~#@#:"0@i.
</code>```

Can anyone help me golf this?...

Ungolfed version

```<code>range        =: i.
length       =: #
binary       =: #:
sum          =: +/
divide       =: %
itself       =: ~
of           =: @
ofall        =: @:
binarylength =: length of binary "0
average      =: sum ofall divide itself
f            =: average binarylength of range
</code>```

Title: Mean bits: an average challenge

Body:
J, <s>21</s> <s>17</s> 15 bytes

From 17 bytes to 15 bytes thanks to @Dennis.

+/@:%~#@#:"0@i.

Can anyone help me golf this?...

Ungolfed version

range        =: i.
length       =: #
binary       =: #:
sum          =: +/
divide       =: %
itself       =: ~
of           =: @
ofall        =: @:
binarylength =: length of binary "0
average      =: sum ofall divide itself
f            =: average binarylength of range


问:
Is this figure connected?
You are given a list of (x,y) grid coordinates.  Your function should decide whether the figure obtained by coloring in the squares of the grid with the given coordinates is connected or not.

Squares adjacent diagonally are not considered connected.

Example input:

```<code>(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),
(1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)
</code>```

which looks like:

```<code>****
*
****
   *
****
</code>```

Output:

```<code>YES
</code>```

Example input:

```<code>(0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3),
(4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6)
</code>```

which looks like:

```<code>  ***
    *
*** *
*   *
* ***
*
***
</code>```

Output:

```<code>NO
</code>```

Your function must take as input a list of pairs of integers (e.g. in C++, maybe vector<pair<int,int>>) and return a boolean.  You may not assume any particular ordering of the input points.  The coordinates will be between 0 and 99 inclusive.

Smallest code wins.

ContentLicense: CC BY-SA 2.5

Title: Is this figure connected?

Body:
Perl, 130 <s>133</s>

A simple mark-and-sweep depth-first traversal, made much longer than I'd like by Perl sigils.

sub g{my($a,$b)=@_;g($a-1,$b),g(
$a+1,$b),g($a,$b-1),g($a,$b+1)if
delete$m{$a,$b}}sub f{($a,$b)=@_;
$m{pop,pop}++while@_;g$a,$b;!%m}

Sample use:

say f( (0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),
       (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4) )
  ? 'YES' : 'NO';
say f( (0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3),
       (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6) )
  ? 'YES' : 'NO';


答:
Julia, 27 bytes

n->endof(prod(bin,0:n-1))/n
```

Try it online!

How it works

Since * is string concatenation in Julia, prod can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so prod(bin,0:n-1) is the string of the binary representation of all integers in the desired range. Taking the length with endof and dividing by n yields the mean.

Title: Mean bits: an average challenge

Body:
Julia, 27 bytes

n->endof(prod(bin,0:n-1))/n

Try it online!

How it works

Since * is string concatenation in Julia, prod can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so prod(bin,0:n-1) is the string of the binary representation of all integers in the desired range. Taking the length with endof and dividing by n yields the mean.


问:
Goldbach's conjecture
Write a program that prompts the user for an even integer greater than 2.

Given Goldbach’s conjecture that every even integer greater than 2 can
be expressed as the sum of two primes, print out two prime numbers which, when
added together, provide the requested even number.
Edit: the program only has to print A PAIR of primes, not all.
For example:

4 : 2 + 2

6: 3 + 3

8: 3 + 5

10: 5 + 5 or 3 + 7

Title: Goldbach's conjecture

Body:
Perl 5, 58 bytes

57, plus 1 for -nE

/^(11+?)(?!(11+)\2+$)1*(?=\1$)(?!(11+)\3+$)/;say for$1,$&

Input and output are in unary. Example:

$ perl -nE'/^(11+?)(?!(11+)\2+$)1*(?=\1$)(?!(11+)\3+$)/;say for$1,$&'
1111111111
111
1111111

Hat-tip.


答:
MATL, 9 bytes

```<code>:qBYszQG/
</code>```

Try it online!

Explanation

```<code>:qBYszQG/
:               % take vector [1..n]
 q              % decrement by 1 to get [0..n-1]
  B             % convert from decimal to binary
   Ys           % cumulative sum (fills in 0's after first 1)
     z          % number of nonzero elements
      Q         % increment by 1 to account for zero
       G        % paste original input (n)
        /       % divide for the mean
</code>```

Title: Mean bits: an average challenge

Body:
MATL, 9 bytes

:qBYszQG/

Try it online!

Explanation

:qBYszQG/
:               % take vector [1..n]
 q              % decrement by 1 to get [0..n-1]
  B             % convert from decimal to binary
   Ys           % cumulative sum (fills in 0's after first 1)
     z          % number of nonzero elements
      Q         % increment by 1 to account for zero
       G        % paste original input (n)
        /       % divide for the mean


答:
Hoon, 71 bytes

```<code>|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
</code>```

...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells.

Create a function that takes an atom, r. Create a list from [0..(r - 1)], map over the list taking the binary logarithm of the number, then fold over that list with ++add. Convert both the output of the fold and r to @rq (quad-precision floating point numbers) with ++sun:rq, and then divide one by the other.

The oddest thing in this snippet is the :.^rq at the end. a:b in Hoon means "evaluate a in the context of b". ++rq is the core that contains the entire quad-precision implementation, like a library. So running (sun 5):rq is the same thing as doing (sun:rq 5).

Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm ++rq to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with only the arms defined in ++rq. Unluckily, rq redefines ++add to be floating-point add instead, along with not having r in its context. . (the entire current context) does, however.

When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of a:[. rq] it would look in the entire current context for a before moving on to looking in rq. So add will look up the function that works on atoms instead of floating-point numbers...but so will div. Hoon also has a feature where using ^name will ignore the first found reference, and look for the second.

From there, it's simply using the syntatic sugar of a^b being equal to [a b] to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of ++div:rq.

```<code>> %.  7
  |=
  r/@
  (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
.~~~2.1428571428571428571428571428571428
</code>```

Title: Mean bits: an average challenge

Body:
Hoon, 71 bytes

|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq

...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells.

Create a function that takes an atom, r. Create a list from [0..(r - 1)], map over the list taking the binary logarithm of the number, then fold over that list with ++add. Convert both the output of the fold and r to @rq (quad-precision floating point numbers) with ++sun:rq, and then divide one by the other.

The oddest thing in this snippet is the :.^rq at the end. a:b in Hoon means "evaluate a in the context of b". ++rq is the core that contains the entire quad-precision implementation, like a library. So running (sun 5):rq is the same thing as doing (sun:rq 5).

Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm ++rq to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with only the arms defined in ++rq. Unluckily, rq redefines ++add to be floating-point add instead, along with not having r in its context. . (the entire current context) does, however.

When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of a:[. rq] it would look in the entire current context for a before moving on to looking in rq. So add will look up the function that works on atoms instead of floating-point numbers...but so will div. Hoon also has a feature where using ^name will ignore the first found reference, and look for the second.

From there, it's simply using the syntatic sugar of a^b being equal to [a b] to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of ++div:rq.

> %.  7
  |=
  r/@
  (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
.~~~2.1428571428571428571428571428571428


答:
Jelly, 8 bytes (non-competing)

```<code>_ÆRfÆR.ị
</code>```

Try it online! or verify all test cases.

How it works

```<code>_ÆRfÆR.ị  Main link. Argument: n (integer)

 ÆR       Prime range; yield all primes in [1, ..., n].
_         Subtract all primes from n.
   fÆR    Filter; intersect the list of differences with the prime range.
      .ị  At-index 0.5; yield the last and first element.
</code>```

Title: Goldbach's conjecture

Body:
Write a program that prompts the user for an even integer greater than 2.

Given Goldbach’s conjecture that every even integer greater than 2 can
be expressed as the sum of two primes, print out two prime numbers which, when
added together, provide the requested even number.
Edit: the program only has to print A PAIR of primes, not all.
For example:

4 : 2 + 2

6: 3 + 3

8: 3 + 5

10: 5 + 5 or 3 + 7

Body:
Jelly, 8 bytes (non-competing)

_ÆRfÆR.ị

Try it online! or verify all test cases.

How it works

_ÆRfÆR.ị  Main link. Argument: n (integer)

 ÆR       Prime range; yield all primes in [1, ..., n].
_         Subtract all primes from n.
   fÆR    Filter; intersect the list of differences with the prime range.
      .ị  At-index 0.5; yield the last and first element.


答:
Actually, 7 bytes:

```<code>;r♂├Σl/
</code>```

Try it online!

Explanation:

```<code>;r♂├Σl/
;        duplicate input
 r       push range(0, n) ([0, n-1])
  ♂├     map binary representation
    Σ    sum (concatenate strings)
     l/  divide length of string (total # of bits) by n
</code>```

If it weren't for a bug that I just discovered, this solution would work for 6 bytes:

```<code>r♂├♂læ
</code>```

æ is the builtin mean command.

Title: Mean bits: an average challenge

Body:
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

var QUESTION_ID=80586,OVERRIDE_USER=20283;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+)(?=[^\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:400px;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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Body:
Actually, 7 bytes:

;r♂├Σl/

Try it online!

Explanation:

;r♂├Σl/
;        duplicate input
 r       push range(0, n) ([0, n-1])
  ♂├     map binary representation
    Σ    sum (concatenate strings)
     l/  divide length of string (total # of bits) by n

If it weren't for a bug that I just discovered, this solution would work for 6 bytes:

r♂├♂læ

æ is the builtin mean command.


答:
Julia, <s>50</s> 49 bytes

~=primes;n=ARGS[]|>int
(n-~n)∩~n|>extrema|>show
```

<p>Try it online!</p>

<p>If a function were acceptable, the code could be shortened to <strong>32 bytes</strong>:</p>

<pre class="lang-julia prettyprint-override"><code>~=primes
!n=(n-~n)∩~n|>extrema
</code>```

How it works

~=primes creates an alias for the built-in primes function which returns a list of all prime numbers up to its argument. n=ARGS[]|>int parses the first command-line argument as saves it in n.

To find a suitable pair of primes, we first compute the aforementioned prime range with ~n. Then, n-~n yields all differences of these primes and n.

By intersecting (∩) the result with the prime range itself, we make sure that the remaining primes p are such that n - p is also a prime.

Finally, extrema takes the lowest and highest prime in the intersection, so their sum must be n.

Title: Goldbach's conjecture

Body:
Julia, <s>50</s> 49 bytes

~=primes;n=ARGS[]|>int
(n-~n)∩~n|>extrema|>show

Try it online!

If a function were acceptable, the code could be shortened to 32 bytes:

~=primes
!n=(n-~n)∩~n|>extrema

How it works

~=primes creates an alias for the built-in primes function which returns a list of all prime numbers up to its argument. n=ARGS[]|>int parses the first command-line argument as saves it in n.

To find a suitable pair of primes, we first compute the aforementioned prime range with ~n. Then, n-~n yields all differences of these primes and n.

By intersecting (∩) the result with the prime range itself, we make sure that the remaining primes p are such that n - p is also a prime.

Finally, extrema takes the lowest and highest prime in the intersection, so their sum must be n.


问:
Find a function with cycles of every length
A function is said to have a cycle of length n if there exists an x in its domain such that fn(x) = x and fm(x) ≠ x for 0 < m < n, where the superscript n denotes n-fold application of f. Note that a cycle of length 1 is a fixed point f(x) = x.

Your task is to implement a bijective function from the integers to themselves, which has exactly one cycle of every positive length n. A bijective function is a one-to-one correspondence, i.e. every integer mapped to exactly once. Having exactly one cycle of length n means that there are exactly n distinct numbers x for which fn(x) = x and fm(x) ≠ x for 0 < m < n.

Here is an example of what such a function might look like around x = 0:

```<code>x     ... -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7 ...
f(x)  ...  2  4  6 -3 -1  1 -4  0 -2  5  7 -7 -6  3 -5 ...
</code>```

This excerpt contains cycles of length 1 to 5:

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

Note that above I'm using "function" only in the mathematical sense. You may write either a function or a full program in your language of choice, as long as it takes a single (signed) integer as input and returns a single (signed) integer. As usual you may take input via STDIN, command-line argument, function argument etc. and output via STDOUT, function return value or function (out) argument etc.

Of course, many languages don't (easily) support arbitrary-precision integers. It's fine if your implementation only works on the range of your language's native integer type, as long as that covers at least the range [-127, 127] and that it would work for arbitrary integers if the language's integer type was replaced with arbitrary-precision integers.

Standard code-golf rules apply.

答:
Python 3, 110 bytes

I still have not figured out how to get a lambda in there

if n is a triangle number [1,3,6,10,15,21,28,etc...] then f(n) is the order in the list multiplied by negative one. if the number is negative, give it 1+the next smallest triangle number. else, increment.

Example: 5 is not a triangle number, so add 1.

Next iteration, we have 6. 6 is a triangle number, and it is the 3rd in the list, so out comes -3.

The program gives these lists

length 1:[0]

length 2:[1,-1]

length 3:[2,3,-2]

length 4:[4,5,6,-3]

length 5:[7,8,9,10,-4]

```<code>x=int(input())
if x<0:print((x**2+x)/2+1)
else:
 a=((8*x+1)**.5-1)/2
 if a%1:print(x+1)
 else:print(-a)
</code>```

Edit: Thanks again to @TuukkaX for removing excess charcters.

Body:
Python 3, 110 bytes

I still have not figured out how to get a lambda in there

if n is a triangle number [1,3,6,10,15,21,28,etc...] then f(n) is the order in the list multiplied by negative one. if the number is negative, give it 1+the next smallest triangle number. else, increment.

Example: 5 is not a triangle number, so add 1.

Next iteration, we have 6. 6 is a triangle number, and it is the 3rd in the list, so out comes -3.

The program gives these lists

length 1:[0]

length 2:[1,-1]

length 3:[2,3,-2]

length 4:[4,5,6,-3]

length 5:[7,8,9,10,-4]

x=int(input())
if x<0:print((x**2+x)/2+1)
else:
 a=((8*x+1)**.5-1)/2
 if a%1:print(x+1)
 else:print(-a)

Edit: Thanks again to @TuukkaX for removing excess charcters.


答:
Python 2, <s>75</s> 71 bytes

n=input();k=m=1;p={0}
while{n-k,k}-p:m*=k*k;k+=1;p|={m%k*k}
print n-k,k
```

Test it on Ideone.

How it works

We use a corollary of Wilson's theorem:

At all times, the variable m is equal to the square of the factorial of k - 1; k starts at value 1 and m at value 0!² = 1. The set p will consist of 0 and all prime numbers up to the current value of k.

In each iteration, we first check if both n - k and k belong to p, which is true if and only if the set difference of {n-k, k} and p is empty. If it is, the condition is falsy and the loop continues.

Note that k > 0, and {n - k, k} will satisfy the condition for some positive value of n - k (assuming that Goldbach's conjecture is true), so the 0 in p won't lead to false positives.

In the loop, we update k and m. The new value of m is m × k² = (k - 1)!² × k² = k!², and the new value of k is k + 1, so m = (k - 1)!² still holds before and after the update.

Then, we perform set union to add the value of m % k × k to p. By the corollary of Wilson's theorem, this will add 1 × k = k if k is prime and 0 × k = 0 if not.

When the loop ends, we print the last values of n - k and k, which will be primes with sum n.

Title: Goldbach's conjecture

Body:
Python 2, <s>75</s> 71 bytes

n=input();k=m=1;p={0}
while{n-k,k}-p:m*=k*k;k+=1;p|={m%k*k}
print n-k,k

Test it on Ideone.

How it works

We use a corollary of Wilson's theorem:

At all times, the variable m is equal to the square of the factorial of k - 1; k starts at value 1 and m at value 0!² = 1. The set p will consist of 0 and all prime numbers up to the current value of k.

In each iteration, we first check if both n - k and k belong to p, which is true if and only if the set difference of {n-k, k} and p is empty. If it is, the condition is falsy and the loop continues.

Note that k > 0, and {n - k, k} will satisfy the condition for some positive value of n - k (assuming that Goldbach's conjecture is true), so the 0 in p won't lead to false positives.

In the loop, we update k and m. The new value of m is m × k² = (k - 1)!² × k² = k!², and the new value of k is k + 1, so m = (k - 1)!² still holds before and after the update.

Then, we perform set union to add the value of m % k × k to p. By the corollary of Wilson's theorem, this will add 1 × k = k if k is prime and 0 × k = 0 if not.

When the loop ends, we print the last values of n - k and k, which will be primes with sum n.


问:
Female and Male Sequences
This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.

Really looking forward to the answers!

In his book "Gödel, Escher, Bach: An Eternal Golden Braid", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see this Wikipedia page.

One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:

for n > 0.

Here's the Female sequence and the Male sequence.

Your task is, when given an integer n as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to n, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.

Sample inputs and outputs:
Input: 5
Output: [1, 1, 2, 2, 3]  [0, 0, 1, 2, 2]

Input: 10
Output: [1, 1, 2, 2, 3, 3, 4, 5, 5, 6]  [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]

NOTE: The separation between lists signifies a line break.

This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.

Leaderboard

var QUESTION_ID=80608,OVERRIDE_USER=49561;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+)(?=[^\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

```

答:
Pyth, 24 bytes

It is probably impossible to use reduce to reduce the byte-count.

Straightforward implementation.

```<code>L&b-b'ytbL?b-by'tb1'MQyM
</code>```

Try it online!

How it works

```<code>L&b-b'ytb  defines a function y, which is actually the male sequence.

L          def male(b):
 &b            if not b: return b
   -b          else: return b-
     'ytb            female(male(b-1))

L?b-by'tb1 defines a function ', which is actually the female sequence.

L          def female(b):
 ?b            if b:
   -by'tb          return b-male(female(b-1))
         1     else: return 1

'MQ        print(female(i) for i from 0 to input)
yMQ        print(male(i) for i from 0 to input)
</code>```

Title: Female and Male Sequences

Body:
Pyth, 24 bytes

It is probably impossible to use reduce to reduce the byte-count.

Straightforward implementation.

L&b-b'ytbL?b-by'tb1'MQyM

Try it online!

How it works

L&b-b'ytb  defines a function y, which is actually the male sequence.

L          def male(b):
 &b            if not b: return b
   -b          else: return b-
     'ytb            female(male(b-1))

L?b-by'tb1 defines a function ', which is actually the female sequence.

L          def female(b):
 ?b            if b:
   -by'tb          return b-male(female(b-1))
         1     else: return 1

'MQ        print(female(i) for i from 0 to input)
yMQ        print(male(i) for i from 0 to input)


答:
CJam, <s>13</s> <s>12</s> 11 bytes

One byte saved thanks to @Sp3000, and another thanks to @jimmy23013

```<code>rd_,2fbs,\/
</code>```

Try it online!

Explanation

Straightforward. Applies the definition.

```<code>rd      e# read input and convert to double
_       e# duplicate
,       e# range from 0 to input minus 1
2fb     e# convert each element of the array to binary
s       e# convert to string. This flattens the array
,       e# length of array
\       e# swap
/       e# divide
</code>```

Title: Mean bits: an average challenge

Body:
CJam, <s>13</s> <s>12</s> 11 bytes

One byte saved thanks to @Sp3000, and another thanks to @jimmy23013

rd_,2fbs,\/

Try it online!

Explanation

Straightforward. Applies the definition.

rd      e# read input and convert to double
_       e# duplicate
,       e# range from 0 to input minus 1
2fb     e# convert each element of the array to binary
s       e# convert to string. This flattens the array
,       e# length of array
\       e# swap
/       e# divide


答:
Perl 5.10, <s>85</s> 80 bytes

Meh, dunno if I have more ideas to golf this down...

```<code>@a=1;@b=0;for(1..<>-1){push@a,$_-$b[$a[$_-1]];push@b,$_-$a[$b[$_-1]]}say"@a\n@b"
</code>```

Try it online !

I had to add use 5.10.0 on Ideone in order for it to accept the say function, but it doesn't count towards the byte count.

It's a naive implementation of the algorithm, @a being the "female" list and @b the "male" list.

Crossed-out 85 is still 85 ?

Title: Female and Male Sequences

Body:
This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.

Really looking forward to the answers!

In his book "Gödel, Escher, Bach: An Eternal Golden Braid", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see this Wikipedia page.

One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:

for n > 0.

Here's the Female sequence and the Male sequence.

Your task is, when given an integer n as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to n, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.

Sample inputs and outputs:
Input: 5
Output: [1, 1, 2, 2, 3]  [0, 0, 1, 2, 2]

Input: 10
Output: [1, 1, 2, 2, 3, 3, 4, 5, 5, 6]  [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]

NOTE: The separation between lists signifies a line break.

This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.

Leaderboard

var QUESTION_ID=80608,OVERRIDE_USER=49561;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+)(?=[^\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:
Perl 5.10, <s>85</s> 80 bytes

Meh, dunno if I have more ideas to golf this down...

@a=1;@b=0;for(1..<>-1){push@a,$_-$b[$a[$_-1]];push@b,$_-$a[$b[$_-1]]}say"@a\n@b"

Try it online !

I had to add use 5.10.0 on Ideone in order for it to accept the say function, but it doesn't count towards the byte count.

It's a naive implementation of the algorithm, @a being the "female" list and @b the "male" list.

Crossed-out 85 is still 85 ?


答:
ES6, <s>89</s> <s>85</s> 83 bytes

2 bytes saved thanks to @Bálint

```<code>x=>{F=[n=1],M=[0];while(n<x){M.push(n-F[M[n-1]]);F.push(n-M[F[n++-1]])}return[F,M]}
</code>```

Naïve implementation.

Explanation:

```<code>x => {
    F = [n = 1], //female and term number
    M = [0]; //male
    while (n < x) {
        M.push(n - F[M[n - 1]]); //naïve
        F.push(n - M[F[n++ - 1]]); //post-decrement means n++ acts as n in the calculation
    }
    return [F, M];
}
</code>```

Title: Female and Male Sequences

Body:
ES6, <s>89</s> <s>85</s> 83 bytes

2 bytes saved thanks to @Bálint

x=>{F=[n=1],M=[0];while(n<x){M.push(n-F[M[n-1]]);F.push(n-M[F[n++-1]])}return[F,M]}

Naïve implementation.

Explanation:

x => {
    F = [n = 1], //female and term number
    M = [0]; //male
    while (n < x) {
        M.push(n - F[M[n - 1]]); //naïve
        F.push(n - M[F[n++ - 1]]); //post-decrement means n++ acts as n in the calculation
    }
    return [F, M];
}


答:
Brachylog, 65 bytes

```<code>:{:1-:0re.}fL:2aw,@Nw,L:3aw
0,1.|:1-:2&:3&:?--.
0.|:1-:3&:2&:?--.
</code>```

My attempt at combining both predicates for male and female into one actually made the code longer.

You could use the following one liner which has the same number of bytes:

```<code>:{:1-:0re.}fL:{0,1.|:1-:2&:3&:?--.}aw,@Nw,L:{0.|:1-:3&:2&:?--.}aw
</code>```

Note: This works with the Prolog transpiler, not the old Java one.

Explanation

Main predicate:

```<code>:{:1-:0re.}fL                Build a list L of integers from 0 to Input - 1
             :2aw            Apply predicate 2 to each element of L, write the resulting list
                 ,@Nw        Write a line break
                     ,L:3aw  Apply predicate 3 to each element of L, write the resulting list
</code>```

Predicate 2 (female):

```<code>0,1.                         If Input = 0, unify Output with 1
    |                        Else
     :1-                     Subtract 1 from Input
        :2&                  Call predicate 2 with Input - 1 as argument
           :3&               Call predicate 3 with the Output of the previous predicate 2
              :?-            Subtract Input from the Output of the previous predicate 3
                 -.          Unify the Output with the opposite of the subtraction
</code>```

Predicate 3 (male):

```<code>0.                           If Input = 0, unify Output with 0
  |                          Else
   :1-                       Subtract 1 from Input
      :3&                    Call predicate 3 with Input - 1 as argument
         :2&                 Call predicate 2 with the Output of the previous predicate 3
            :?-              Subtract Input from the Output of the previous predicate 3
               -.            Unify the Output with the opposite of the subtraction
</code>```

Title: Female and Male Sequences

Body:
Brachylog, 65 bytes

:{:1-:0re.}fL:2aw,@Nw,L:3aw
0,1.|:1-:2&:3&:?--.
0.|:1-:3&:2&:?--.

My attempt at combining both predicates for male and female into one actually made the code longer.

You could use the following one liner which has the same number of bytes:

:{:1-:0re.}fL:{0,1.|:1-:2&:3&:?--.}aw,@Nw,L:{0.|:1-:3&:2&:?--.}aw

Note: This works with the Prolog transpiler, not the old Java one.

Explanation

Main predicate:

:{:1-:0re.}fL                Build a list L of integers from 0 to Input - 1
             :2aw            Apply predicate 2 to each element of L, write the resulting list
                 ,@Nw        Write a line break
                     ,L:3aw  Apply predicate 3 to each element of L, write the resulting list

Predicate 2 (female):

0,1.                         If Input = 0, unify Output with 1
    |                        Else
     :1-                     Subtract 1 from Input
        :2&                  Call predicate 2 with Input - 1 as argument
           :3&               Call predicate 3 with the Output of the previous predicate 2
              :?-            Subtract Input from the Output of the previous predicate 3
                 -.          Unify the Output with the opposite of the subtraction

Predicate 3 (male):

0.                           If Input = 0, unify Output with 0
  |                          Else
   :1-                       Subtract 1 from Input
      :3&                    Call predicate 3 with Input - 1 as argument
         :2&                 Call predicate 2 with the Output of the previous predicate 3
            :?-              Subtract Input from the Output of the previous predicate 3
               -.            Unify the Output with the opposite of the subtraction


答:
Oracle SQL 11.2, 202 bytes

WITH v(x,y,s)AS(SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1 UNION ALL SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1),p AS(SELECT x FROM v WHERE x-s=2)SELECT a.x,b.x FROM p a,p b WHERE:1=a.x+b.x;
```

<p>Un-golfed</p>

<pre class="lang-sql prettyprint-override"><code>WITH v(x,y,s) AS
(
  SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1
  UNION ALL
  SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1
)
,p AS (SELECT x FROM v WHERE x-s=2)
SELECT a.x,b.x
FROM p a,p b
WHERE :1=a.x+b.x;
</code>```

Title: Goldbach's conjecture

Body:
Oracle SQL 11.2, 202 bytes

WITH v(x,y,s)AS(SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1 UNION ALL SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1),p AS(SELECT x FROM v WHERE x-s=2)SELECT a.x,b.x FROM p a,p b WHERE:1=a.x+b.x;

Un-golfed

WITH v(x,y,s) AS
(
  SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1
  UNION ALL
  SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1
)
,p AS (SELECT x FROM v WHERE x-s=2)
SELECT a.x,b.x
FROM p a,p b
WHERE :1=a.x+b.x;


Title: Mean bits: an average challenge

Body:
JavaScript (ES7), <s>38</s> 32 bytes

n=>(l=-~Math.log2(n))-(2**l-2)/n

Using @sp3000's formula (previous version was a recursive solution). ES6 version for 34 bytes:

n=>(l=-~Math.log2(n))-((1<<l)-2)/n

Explanation of formula: Consider the case of N=55. If we write the binary numbers (vertically to save space), we get:

                                11111111111111111111111
                111111111111111100000000000000001111111
        11111111000000001111111100000000111111110000000
    111100001111000011110000111100001111000011110000111
  11001100110011001100110011001100110011001100110011001
0101010101010101010101010101010101010101010101010101010

The size of this rectangle is nl so the average is just l but we need to exclude the blanks. Each row of blanks is twice as long as the previous so the total is 2 + 4 + 8 + 16 + 32 = 64 - 2 = 2l - 2.


答:
Ruby, <s>104</s> <s>92</s> <s>97</s> 82 bytes

f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
```

<p><strong>Edit:</strong> <code>f</code> and <code>m</code> are now one function thanks to HopefullyHelpful. I changed the second function to print <code>f</code> then <code>m</code>. The whitespace after <code>p</code> is significant, as otherwise the function prints <code>(0...n)</code> instead of the result of <code>map</code>.</p>

<p>The third function prints first an array of the first n terms of <code>f</code>, followed by an array of the first n terms of <code>m</code></p>

<p>These functions are called like this:</p>

<pre class="lang-ruby prettyprint-override"><code>> f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
> s=->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
> s[10]
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]
</code>```

Title: Female and Male Sequences

Body:
Ruby, <s>104</s> <s>92</s> <s>97</s> 82 bytes

f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}

Edit: f and m are now one function thanks to HopefullyHelpful. I changed the second function to print f then m. The whitespace after p is significant, as otherwise the function prints (0...n) instead of the result of map.

The third function prints first an array of the first n terms of f, followed by an array of the first n terms of m

These functions are called like this:

> f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
> s=->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
> s[10]
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]


答:
05AB1E, <s>9</s> 7 bytes

Code:

```<code>L<bJg¹/
</code>```

Explanation:

```<code>L<         # range from 0..input-1
  b        # convert numbers to binary
   J       # join list of binary numbers into a string
    g      # get length of string (number of bits)
     ¹/    # divide by input
</code>```

Try it online

Edit: saved 2 bytes thanks to @Adnan

Title: Mean bits: an average challenge

Body:
05AB1E, <s>9</s> 7 bytes

Code:

L<bJg¹/

Explanation:

L<         # range from 0..input-1
  b        # convert numbers to binary
   J       # join list of binary numbers into a string
    g      # get length of string (number of bits)
     ¹/    # divide by input

Try it online

Edit: saved 2 bytes thanks to @Adnan


答:
Java, <s>135</s> <s>95</s> 90 bytes

```<code>float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);}
</code>```

Title: Mean bits: an average challenge

Body:
Java, <s>135</s> <s>95</s> 90 bytes

float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);}


答:
J, 47 bytes

```<code>f=:1:`(-m@f@<:)@.*
m=:0:`(-f@m@<:)@.*
(f,:m)@i.
</code>```

Uses the recursive definition. The first two lines define the verbs f and m which represent the female and male functions, respectively. The last line is a verb that takes a single argument n and outputs the first n terms of the female and male sequences.

Usage

```<code>   (f,:m)@i. 5
1 1 2 2 3
0 0 1 2 2
   (f,:m)@i. 10
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6
</code>```

Title: Female and Male Sequences

Body:
J, 47 bytes

f=:1:`(-m@f@<:)@.*
m=:0:`(-f@m@<:)@.*
(f,:m)@i.

Uses the recursive definition. The first two lines define the verbs f and m which represent the female and male functions, respectively. The last line is a verb that takes a single argument n and outputs the first n terms of the female and male sequences.

Usage

   (f,:m)@i. 5
1 1 2 2 3
0 0 1 2 2
   (f,:m)@i. 10
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6


答:
Python 2, 107 bytes

F=lambda n:n and n-M(F(n-1))or 1
M=lambda n:n and n-F(M(n-1))
n=range(input())
print map(F,n),'\n',map(M,n)
```

Try it online

Larger input values cause a RuntimeError (too much recursion). If this is a problem, I can write a version where the error doesn't happen.

Title: Female and Male Sequences

Body:
Python 2, 107 bytes

F=lambda n:n and n-M(F(n-1))or 1
M=lambda n:n and n-F(M(n-1))
n=range(input())
print map(F,n),'\n',map(M,n)

Try it online

Larger input values cause a RuntimeError (too much recursion). If this is a problem, I can write a version where the error doesn't happen.


答:
Jelly, 10 bytes

```<code>BL©2*2_÷+®
</code>```

From Sp3000's suggestion.

Try it here.

Jelly, 11 bytes

```<code>æḟ2’Ḥ÷_BL$N
</code>```

Not very short but I need some tips.

Try it here.

Using the same formula as in Sp3000's answer. (It's not very hard to get it yourself, by differentiating geometric progression.)

Title: Mean bits: an average challenge

Body:
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

var QUESTION_ID=80586,OVERRIDE_USER=20283;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+)(?=[^\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:400px;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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Body:
Jelly, 10 bytes

BL©2*2_÷+®

From Sp3000's suggestion.

Try it here.

Jelly, 11 bytes

æḟ2’Ḥ÷_BL$N

Not very short but I need some tips.

Try it here.

Using the same formula as in Sp3000's answer. (It's not very hard to get it yourself, by differentiating geometric progression.)


Title: Female and Male Sequences

Body:
JavaScript (ES6), 75 bytes

g=n=>--n?([f,m]=g(n),m=[...m,n-f[m[n-1]]],[[...f,n-m[f[n-1]]],m]):[[1],[[0]]

I could save 2 bytes if I was allowed to return the Male sequence first:

g=n=>--n?([f,m]=g(n),[m=[...m,n-f[m[n-1]]],[...f,n-m[f[n-1]]]]):[[1],[[0]]


答:
Python 2, <s>79</s> 70 bytes

a=0,;b=1,
exec"a,b=b,a+(len(a)-b[a[-1]],);"*~-input()*2
print b,'\n',a
```

<p>Iterative rather than recursive, because why not. The first line has a trailing space - if that's not okay it can be fixed for an extra byte. -9 bytes thanks to @Dennis.</p>

<p>Here are some combined lambdas which didn't really help:</p>

<pre class="lang-py prettyprint-override"><code>f=lambda n,k:n and n-f(f(n-1,k),k^1)or k
f=lambda n,k:[k][n:]or f(n-1,k)+[n-f(f(n-1,k)[-1],k^1)[-1]]
</code>```

Both take n and a parameter k either 0 or 1, specifying male/female. The first lambda returns the nth element, and the second lambda returns the first n elements (with exponential runtime).

Title: Female and Male Sequences

Body:
Python 2, <s>79</s> 70 bytes

a=0,;b=1,
exec"a,b=b,a+(len(a)-b[a[-1]],);"*~-input()*2
print b,'\n',a

Iterative rather than recursive, because why not. The first line has a trailing space - if that's not okay it can be fixed for an extra byte. -9 bytes thanks to @Dennis.

Here are some combined lambdas which didn't really help:

f=lambda n,k:n and n-f(f(n-1,k),k^1)or k
f=lambda n,k:[k][n:]or f(n-1,k)+[n-f(f(n-1,k)[-1],k^1)[-1]]

Both take n and a parameter k either 0 or 1, specifying male/female. The first lambda returns the nth element, and the second lambda returns the first n elements (with exponential runtime).


问:
Obfuscated Hello World
Create the shortest possible obfuscated program that displays the text "Hello World".

In order to be considered an obfuscated program, it must meet at least two of the following requirements:

Does not contain the characters: h, l, w and d in any case

Does not contain the characters: e, o, r, 0, and 1 in any case

Does not contain the characters: 2 or 7

Input:

none

Output:

Hello World

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

ContentLicense: CC BY-SA 4.0

Title: Obfuscated Hello World

Body:
pb, 72 bytes

b[69+3]>b[101]>b[108]>b[108]>b[111]>>b[86+1]>b[111]>b[114]>b[108]>b[100]

Violates rule II


答:
MATL, 23 bytes

```<code>1Oiq:"@XJth"yy0)Q)_J+hw
</code>```

Try it online!

Explanation

This works iteratively. Each sequence is kept in an array. For each index n the new term of each sequence is computed and attached to the corresponding array. A for loop with N−1 terms is used, where N is the input number.

The update for sequence M needs to be done first. This is because sequence F is always greater than or equal to sequence M for the same index, so if we tried to update F first we would need a term of M not computed yet.

The two update equations are the same interchanging F and M. Thus the code for the updating is reused by applying a for loop with two iterations and swapping the sequences in the stack.

```<code>1        % Push 1: seed for F sequence
O        % Push 0: seed for M sequence
iq:      % Input N. Generate range [1 2 ... N-1]
"        % For each (i.e. iterate N-1 times)
  @      %   Push current index, n (starting at 1 and ending at N-1)
  XJ     %   Copy to clipboard J
  th     %   Duplicate and concatenate. This generates a length-2 array
  "      %   For each (i.e. iterate twice)
    yy   %   Duplicate top two elements, i.e. F and M sequences
    0)   %     In the *first* iteration: get last entry of M, i.e M(n-1)
    Q)   %     Add 1 and index into F. This is F(M(n-1))
    _J+  %     Negate and add n. This is n-F(M(n-1)), that is, M(n)
    h    %     Concatenate to update M
    w    %     Swap top two elements, to bring F to top.
         %     In the *second* iteration the procedure is repeated to update F,
         %     and then the top two elements are swapped to bring M to top again,
         %     ready for the next iteration of the outer loop
         %   End for implicitly
         % End for implicitly
         % Display implicitly from bottom to top: first line is F, second is M
</code>```

Title: Female and Male Sequences

Body:
MATL, 23 bytes

1Oiq:"@XJth"yy0)Q)_J+hw

Try it online!

Explanation

This works iteratively. Each sequence is kept in an array. For each index n the new term of each sequence is computed and attached to the corresponding array. A for loop with N−1 terms is used, where N is the input number.

The update for sequence M needs to be done first. This is because sequence F is always greater than or equal to sequence M for the same index, so if we tried to update F first we would need a term of M not computed yet.

The two update equations are the same interchanging F and M. Thus the code for the updating is reused by applying a for loop with two iterations and swapping the sequences in the stack.

1        % Push 1: seed for F sequence
O        % Push 0: seed for M sequence
iq:      % Input N. Generate range [1 2 ... N-1]
"        % For each (i.e. iterate N-1 times)
  @      %   Push current index, n (starting at 1 and ending at N-1)
  XJ     %   Copy to clipboard J
  th     %   Duplicate and concatenate. This generates a length-2 array
  "      %   For each (i.e. iterate twice)
    yy   %   Duplicate top two elements, i.e. F and M sequences
    0)   %     In the *first* iteration: get last entry of M, i.e M(n-1)
    Q)   %     Add 1 and index into F. This is F(M(n-1))
    _J+  %     Negate and add n. This is n-F(M(n-1)), that is, M(n)
    h    %     Concatenate to update M
    w    %     Swap top two elements, to bring F to top.
         %     In the *second* iteration the procedure is repeated to update F,
         %     and then the top two elements are swapped to bring M to top again,
         %     ready for the next iteration of the outer loop
         %   End for implicitly
         % End for implicitly
         % Display implicitly from bottom to top: first line is F, second is M


答:
Mathematica, 28 bytes

```<code>(Tr@⌈Log2@Range@#⌉+1)/#&
</code>```

or

```<code>Tr@⌈Log2@Range@#⌉/#+1/#&
</code>```

In either case, it's an unnamed function which takes N as an input and returns an exact (rational) result for the mean.

Title: Mean bits: an average challenge

Body:
Mathematica, 28 bytes

(Tr@⌈Log2@Range@#⌉+1)/#&

or

Tr@⌈Log2@Range@#⌉/#+1/#&

In either case, it's an unnamed function which takes N as an input and returns an exact (rational) result for the mean.