The GOLF CPU Golfing Challenge: Sides of a Cuboid

14,483 cycles

I use the fact that the output depends only on the signature (exponents in the prime factorization) of the input.  I used the formula from https://oeis.org/A034836.  The sieve of Eratosthenes is used to find primes to factorize the input by trial division.

# Input in register n
# Outputs in register r and exit code

# the signature of n (exponents in its prime factorization) are stored in
# memory starting at address 0x1000000000000000.  They are byte-sized
# since the largest exponent we can have is 64 (2**64)

# mov z, 0x1000000000000000 (implicit)
mov y, z

# pull out factors of 2
# number of factors is stored in k
# mov k, 0 (implicit)
factor_two:
  and c, n, 1
  snz c, 3
    shr n, n, 1
    inc k
    jmp factor_two

# store factors of two if nonzero
sz k, 2
  sb z, k
  inc z

# Sieve of Eratosthenes
# we only check odd primes, since we already removed factors of 2
# we store COMPOSITE(i) at address i
# we also check n for divisibility by every prime we find
# note we only have to check for prime factors up to sqrt(n)!

mov i, 1
sieve_loop:
  add i, i, 2 # go to the next odd number
  lb c, i # check if COMPOSITE(i)
  jnz sieve_loop, c # if so, continue

  mulu j, k, i, i # j = i**2
  geu c, j, n              # if i**2 > n:
  jnz end_sieve_loop, c #   break

  # otherwise, i is prime; check if n is divisible by i
  mov k, 0
  factor_i:
    divu q, r, n, i # r = n % i
    snz r, 3
      mov n, q      # n /= i
      inc k
      jmp factor_i

  # store factors of i if nonzero
  sz k, 2
    sb z, k
    inc z

  # now cross off all composites that are odd multiples of i,
  # but only up to sqrt(n)
  shl d, i, 2 # d = 2 * i
  # we already have j = i**2, we can start marking composites here:
  # since every lesser multiple of i must have a smaller  prime factor and
  # therefore must have already been marked

  sieve_inner_loop:
    sb j, 1
    add j, j, d # j += 2*i
    mulu c, k, j, j  # c = j**2
    leu c, c, n             # if j**2 < n:
    jnz sieve_inner_loop, c #   continue

  jmp sieve_loop

end_sieve_loop:

# if n != 1, n is a prime and needs to be added to the signature
cmp c, n, 1
snz c, 2 # skip if n==1
  sb z, 1

#mov z, 0x1000000000000000

# according to https://oeis.org/A034836, we have:
# a(n) = (np + 3*nsq + 2*ntp)/6
# where np = Times@@Binomial[2+s,2],
# ntp = Times@@Floor[Floor[s,3]/s],
# nsq = Times@@(Floor[s/2] + 1),
# and s is the signature

# Binomial[2+s,2] == (1+s)(2+s)/2
# Floor[Floor[s,3]/s] == 1 if s divides 3, 0 otherwise

# I tested this formula up to n=10,000,000

mov t, 0 # <= BUG? (doesn't work without this line)
mov d, 1 # np
mov e, 1 # ntp
mov f, 1 # nsq

product_loop:
  lb s, y
  jz finish, s
  inc y

  divu q, r, s, 3 # r = s % 3
  sz r, 1
    mov e, 0

  inc s
  mulu d, x, d, s # d *= s + 1

  inc s
  mulu d, x, d, s # d *= s + 2
  shr d, d, 1     # d /= 2

  shr s, s, 1     # s /= 2 (s == (s+2)/2 == floor(s/2) + 1)
  mulu f, x, f, s # f *= floor(s/2) + 1

  jmp product_loop

finish:

add r, e, f # r = e + f
shl r, r, 1 # r *= 2
add r, r, f # r += f
add r, r, d # r += d
            # r == d + 3*f + 2*e

divu r, s, r, 6 # r /= 6

halt r

Test cases:

robert@unity:~/golf-cpu$ ./assemble.py cube.golf
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1
Execution terminated after 42 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=5
Execution terminated after 77 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=8
Execution terminated after 91 cycles with exit code 3.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=24
Execution terminated after 126 cycles with exit code 6.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=100
Execution terminated after 218 cycles with exit code 8.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=1080
Execution terminated after 236 cycles with exit code 52.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468719
Execution terminated after 9710 cycles with exit code 1.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468720
Execution terminated after 422 cycles with exit code 678.
robert@unity:~/golf-cpu$ ./golf.py cube.bin n=468721
Execution terminated after 3561 cycles with exit code 2.
robert@unity:~/golf-cpu$


CJam, 82 76 66 62 58 54 bytes

qN/::~4{[8_]f/[9_]f*z{[{1$8-g)+}*]W%}%}*{_8<\2<8?}f%N*

Input format expects 0 for air cell and 8 for a chest cell. Output contains 1 for all cells that can be placed with a Chest.

UPDATE : Fixed a bug. Increased by 3 bytes :( golfed further :) . 4 bytes saved thanks to @Sp3000

Example input:

0000000800
0008008000
0000000008
0880008808
0000000000

Output:

1111110811
1110018010
1008800108
0880088008
1008800110

I think I am done golfing for now...

Explanation

qN/::~                   "This part converts the input into array of integer array";
qN/                      "Split input on new line";
   ::~                   "Parse each character in each row as integer";

4{[8_]f/[9_]f*z{[{1$8-g)+}*]W%}%}*

4{   ...z{       W%}%}*  "Run the logic 4 times, first, columns in correct order, then,";
                         "columns in reverse order, then for rows";
  [8_]f/[9_]f*           "Convert adjacent chests represented by two 8 into two 9";
                         "This happens for all the rows in the columns iterations and";
                         "for all the columns in the rows iterations";
  {               }%     "For each row/column";
   [{        }*]         "Reduce and wrap it back in the array";
     :I8-                "Store the second number in I, remove 8 from it";
         g               "Do signum. Now we have -1 for < 8 number, 0 for 8 and 1 for > 8";
          )+I            "Increment to get 0, 1 & 2. Add it to first number and put I back";

{_8<\2<8?}f%N*           "This part converts the output from previous iterations";
                         "to 3 character based final output and prints it";
{        }f%             "Map each row using the code block";
 _8<   8?                "If the value is greater than 7, make it 8, else:";
    \2<                  "If the value is greater than 1, make it 0, else 1";
            N*           "Join the arrays using new line";

Try it online here


Pyth, 38 bytes

{smm,hk+ekdfgaFTdcx1xM.ttB+0qVQ>QdZ2Sl

  m                                 SlQ   map for d in [1, …, len(input)]:
                            qVQ>Qd          pairwise equality of input[:-d] and input[d:]
                        tB+0                duplicate this list, prepending 0 to one copy
                      .t          Z         transpose, padding with 0
                    xM                      pairwise xor
                  x1                        find all occurrences of 1
                 c                 2        chop into groups of 2
           f                                filter for groups T such that:
             aFT                              the absolute difference between its elements
            g   d                             is greater than or equal to d
   m                                        map for groups k:
     hk                                       first element
    ,  +ekd                                   pair with the last element plus d
 s                                        concatenate
}                                         deduplicate

Test suite


Javascript / ECMAScript 6, 161 159 158 / 152

Javascript:

function $(t,r,i,a,n,g,l,e){b=(-g*l+a*(-n+l)+i*(g-e)+n*e)/2;c=b<0?-1:1;d=(a*l-i*e+(e-a)*t+(i-l)*r)*c;f=(i*g-a*n+(a-g)*t+(n-i)*r)*c;return d>0&&f>0&&d+f<2*b*c}

ECMAScript 6 version (thanks m.buettner, saves 6 characters)

$=(t,r,i,a,n,g,l,e)=>{b=(-g*l+a*(-n+l)+i*(g-e)+n*e)/2;c=b<0?-1:1;d=(a*l-i*e+(e-a)*t+(i-l)*r)*c;f=(i*g-a*n+(a-g)*t+(n-i)*r)*c;return d>0&&f>0&&d+f<2*b*c}

Call it as such (returns true or false):

$(pointX, pointY, v1X, v1Y, v2X, v2Y, v3X, v3Y);

Uses some fancy barycentric coordinate math based on code from this answer. An ungolfed version for your reading enjoyment follows:

function $ (pointX, pointY, v1X, v1Y, v2X, v2Y, v3X, v3Y) {
  var A =  (-v2Y * v3X + v1Y * (-v2X + v3X) + v1X * (v2Y - v3Y) + v2X * v3Y) / 2;
  var sign = A < 0 ? -1 : 1;
  var s = (v1Y * v3X - v1X * v3Y + (v3Y - v1Y) * pointX + (v1X - v3X) * pointY) * sign;
  var t = (v1X * v2Y - v1Y * v2X + (v1Y - v2Y) * pointX + (v2X - v1X) * pointY) * sign;
  return s > 0 && t > 0 && s + t < 2 * A * sign;
}


An Array of Challenges #3: Moving Averages

Dyalog APL, 4 bytes

1 byte saved thanks to @Graham

2 bytes saved thanks to @jimmy23013

Did I mention APL is not a golfing language?

⊢+/÷

with n on the right, or

+/÷⊣

with L on the right.

Try it online!

How?

÷ - divide L by n

⊢+/ - reduce + on windows of n


Can square tree rings be generated from primes?

MATLAB - 197 185 178 175 184 163 162 148 142 140 bytes

Shaved 12 bytes, thanks to Ander and Andras, and lots thanks to Luis for putting the two together. Shaved 16 thanks to Remco, 6 thanks to flawr

function F(n)
p=@primes
s=@isprime
for a=2:n^2
c=0
if~s(a)
b=nnz(p(a))
while~s(b)
b=nnz(p(b))
c=c+1
end
end
d(a)=c
end
imagesc(d(spiral(n)))

Result for N=301 (F(301)):

Explanation:

function F(n)
p=@primes % Handle
s=@isprime % Handle
for a=2:n^2 % Loop over all numbers
    c=0 % Set initial count
    if~s(a) % If not a prime
        b=nnz(p(a)) % Count primes
        while~s(b) % Stop if b is a prime. Since the code starts at 2, it never reaches 1 anyway
            b=nnz(p(b)) % count again
            c=c+1 % increase count
        end
    end
    d(a)=c % store count
end
imagesc(d(spiral(n))) % plot


JavaScript: 141

function x(i){var a=0,b,c,d;for(;a<i;a++)for(b=0;b<i;b++)for(c=0;c<i;c++)for(d=0;d<i;d++)if(a*a+b*b+c*c+d*d==i){console.log(a,b,c,d);return}}


Find how many alphanumeric characters can be made up of a single number

05AB1E, 8 7 bytes

žKÇIŒÃg

Try it online!

Explanation

žK       # push [a-zA-Z0-9]
  Ç      # convert to list of ascii codes
   IŒ    # push all substrings of input
     Ã   # keep only the subtrings which exist in the list of acsii codes
      g  # push length of resulting list


Counting shortest paths on a triangular grid

Jelly, 7 bytes

;IAṀc$Ṁ

Try it online!

How?

;IAṀc$Ṁ - Link: list of two integers   e.g. [-4, -9]
 I      - incremental differences           [-5]           (since -9 - -4 = -5)
;       - concatenate                       [-4, -9, -5]
  A     - absolute values                   [4, 9, 5]
     $  - last two links as a monad:
   Ṁ    -   maximum                         9
    c   -   choose (vectorises)             [126, 1, 126]  (9c4=9c5=126 and 9c9=1)
      Ṁ - maximum                           126


Regex (ECMAScript 2018 or .NET), 140 126 118 100 98 82 bytes
^(?!(^.*)(.+)(.*$)(?<!^\2|^\1(?=(|(<?(|(?!\8).)*(\8|\3$){1}){2})*$).*(.)+\3$)!?=*)
This is much slower than the 98 byte version, because the ^\1 is left of the lookahead and is thus evaluated after it. See below for a simple switcheroo that regains the speed. But due to this, the two TIOs below are limited to completing a smaller test case set than before, and the .NET one is too slow to check its own regex.
Try it online! (ECMAScript 2018)
Try it online! (.NET)
To drop 18 bytes (118 → 100), I shamelessly stole a really nice optimization from Neil's regex that avoids the need to put a lookahead inside the negative lookbehind (yielding an 80 byte unrestricted regex). Thank you, Neil!
That became obsolete when it dropped an incredible 16 more bytes (98 → 82) thanks to jaytea's ideas which led to a 69 byte unrestricted regex! It's much slower, but that's golf!
Note that the (|( no-ops for making the regex well-linked have the result of making the it evaluate very slowly under .NET. They do not have this effect in ECMAScript because zero-width optional matches are treated as non-matches.
ECMAScript prohibits quantifiers on assertions, so this makes golfing the restricted-source requirements harder. However, at this point it's so well-golfed that I don't think lifting that particular restriction would open up any further golfing possibilities.
Without the extra characters needed to make it pass the restrictions (101 69 bytes):
^(?!(.*)(.+)(.*$)(?<!^\2|^\1(?=((((?!\8).)*(\8|\3$)){2})*$).*(.)+\3))
It's slow, but this simple edit (for just 2 extra bytes) regains all the lost speed and more:
^(?!(.*)(.+)(.*$)(?<!^\2|(?=\1((((?!\8).)*(\8|\3$)){2})*$)^\1.*(.)+\3))
^
(?!
    (.*)               # cycle through all starting points of substrings;
                       # \1 = part to exclude from the start
    (.+)               # cycle through all ending points of non-empty substrings;
                       # \2 = the substring
    (.*$)              # \3 = part to exclude from the end
    (?<!               # Assert that every character in the substring appears a total
                       # even number of times.
        ^\2            # Assert that our substring is not the whole string. We don't
                       # need a $ anchor because we were already at the end before
                       # entering this lookbehind.
    |                  # Note that the following steps are evaluated right to left,
                       # so please read them from bottom to top.
        ^\1            # Do not look further left than the start of our substring.
        (?=
            # Assert that the number of times the character \8 appears in our
            # substring is odd.
            (
                (
                    ((?!\8).)*
                    (\8|\3$) # This is the best part. Until the very last iteration
                             # of the loop outside the {2} loop, this alternation
                             # can only match \8, and once it reaches the end of the
                             # substring, it can match \3$ only once. This guarantees
                             # that it will match \8 an odd number of times, in matched
                             # pairs until finding one more at the end of the substring,
                             # which is paired with the \3$ instead of another \8.
                ){2}
            )*$
        )
        .*(.)+         # \8 = cycle through all characters in this substring
        # Assert (within this context) that at least one character appears an odd
        # number of times within our substring. (Outside this negative lookbehind,
        # that is equivalent to asserting that no character appears an odd number
        # of times in our substring.)
        \3             # Skip to our substring (do not look further right than its end)
    )
)

I wrote it using molecular lookahead (103 69 bytes) before converting it to variable-length lookbehind:
^(?!.*(?*(.+)(.*$))(?!^\1$|(?*(.)+.*\2$)((((?!\3).)*(\3|\2$)){2})*$))
^
(?!
    .*(?*(.+)(.*$))       # cycle through all non-empty substrings;
                          # \1 = the current substring;
                          # \2 = the part to exclude from the end
    (?!                   # Assert that no character in the substring appears a
                          # total even number of times.
        ^\1$              # Assert that our substring is not the whole string
                          # (i.e. it's a strict substring)
    |
        (?*(.)+.*\2$)    # \3 = Cycle through all characters that appear in this
                          # substring.
        # Assert (within this context) that this character appears an odd number
        # of times within our substring.
        (
            (
                ((?!\3).)*
                (\3|\2$)
            ){2}
        )*$
    )
)

And to aid in making my regex itself well-linked, I've been using a variation of the above regex:
(?*(.+)(.*$))(?!^\1$|(?*(.)+.*\2$)((((?!\3).)*(\3|\2$)){2})*$)\1
When used with regex -xml,rs -o, this identifies a strict substring of the input that contains an even number of every character (if one exists). Sure, I could have written a non-regex program to do this for me, but where would be the fun in that?


05AB1E, 1 byte

Code:

_

Explanation:

_     # Logical not

Try it online!


Try (Dyalog) APL, 38 43 bytes

Last input line must have a trailing newline.
{{(⊃⍵)⍪⍉⍪↑¨↓⍉↑1↓⍵}s¨',',¨(s←1↓¨⊢⊂⍨⊢=⊃)¯1⌽⍵}

Try it online! In the offline version of Dyalog APL, execute ]boxing ON -style=min for the same effect.
Explanation
{ ... } an anonymous function where ⍵ represents the argument:
 ¯1 ⌽ ⍵ rotate the trailing newline to the front
 (s ←  ... ) define the function s as follows, and apply it
  1 ↓¨ drop the first character of each
  ⊢ ⊂⍨ line, split where
  ⊃ = ⊢ the first character equals the characters in the string
 ',' ,¨ then prepend a comma to each line
 s¨ apply the function s to each line
 { ... } now apply the following anonymous function:
  1 ↓ ⍵ drop the first element (the row headers)
  ↓ ⍉ ↑ transpose the list of rows into list of columns
  ↑¨ make each element (a list of entries) into a matrix of padded entries
  ⍉ ⍪ make into one-column matrix, then transpose into one-row matrix
  (⊃⍵) ⍪ put the argument's first element (the list of headers) on top`
Note: While the line drawing characters are not explicitly used in my solution, they are part of the APL character set, and would also be counted as single bytes.


J, 6 bytes

19#.+/

Try it online!

19#. convert the following to base 19...
+/ elementwise sum of the input digit lists.


Magic: The Gathering Combat with Abilities


Python 2, 89 bytes

lambda s:map(list,map(permutations,product(*zip(s.swapcase(),s))))
from itertools import*

Try it online!

Doesn't work in Python 3. Swap case idea from HyperNeutrino.


R, 86 83 82 bytes
(or 64 bytes with additional NA values in output when length of hash result is greater than half the length of the private key N)

function(f,N,d=seq(b<-sapply(f,function(b)b%/%2^(7:0)%%2))*2)N[(d-!b)*!d>sum(N|1)]

Try it online!
Input is an array f of single-byte integers (representing the output of the hash function phi) and an array N (representing the ordered array from which to select a subset).
G=function(f,N){            # G is function with args f=array of bytes, N=array of values
  bits=                     # calculate the bits of f:
    sapply(f,function(b)    #   for each byte b in f
      b%/%2^(7:0)%%2)       #   get its bits
  d=seq(bits)               # define d as 1..number of bits
  N[                        # now output the elements of N given by indices:
    (d*2-1+bits)            #   d*2-1+bits (these are the indices from the bytes of f)
             *!d>sum(N|1)/2 #   multiplied by zero (FALSE) for bits that exceed the length of N
    ]
}


Python 2, 346 338 bytes
i,C,W=input()
r=[]
for l in [x or' 'for x in i.split('\n')]:
 while l:
  if' '==l[0]:l=l[1:]
  w=l[:W];x=W;s=w.rfind(' ')+1
  if max(W-3,0)<s:w=w[:s];x-=W-s
  elif x<len(l)and' 'not in l[x:x+1]:w=w[:-1]+'-';x-=1
  r+=[w];l=l[x:]
r=[s.ljust(W)for s in r+['']*(C-1)]
print'\n'.join('    '.join(s)for s in zip(*zip(*[iter(r)]*((len(r))/C))))

Input as 'string',C,W


Perl 6, 76 65 63 59 bytes

-4 bytes thanks to Phil H

{221222==[~] (.skip Z-$_)X%12}o*>>.&{13*.ord+>3+?/\#/-?/b/}

Try it online!

Explanation

*>>.&{ ... }  # Map notes to integers
  13*.ord     # 13 * ASCII code:  A=845 B=858 C=871 D=884 E=897 F=910 G=923
  +>3         # Right shift by 3: A=105 B=107 C=108 D=110 E=112 F=113 G=115
              # Subtracting 105 would yield A=0 B=2 C=3 D=5 E=7 F=8 G=10
              # but isn't necessary because we only need differences
  +?/\#/      # Add 1 for '#'
  -?/b/       # Subtract 1 for 'b'

{                           }o  # Compose with block
            (.skip Z-$_)        # Pairwise difference
                        X%12    # modulo 12
         [~]  # Join
 221222==     # Equals 221222


C# - Stack Exchange Hangman

Guess names of Stack Exchange websites in this Hangman game:

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

New game

This was done using ASP.NET MVC 3.0. Here's the code of the Controller that does the trick:

public class HangmanController : Controller
{
    public ActionResult Index()
    {
        var game = Session["hangman"] as HangmanGame ?? HangmanGame.New();

        game = ExecuteGameCommand(game);

        Session["hangman"] = game;

        var imageRenderer = new HangmanImageRenderer(game);
        return new ImageResult(imageRenderer.Render());
    }

    private HangmanGame ExecuteGameCommand(HangmanGame game)
    {
        var referrerQuery = Request.UrlReferrer != null ? Request.UrlReferrer.Query : string.Empty;

        if (referrerQuery.Contains("_new_hangman_"))
            return HangmanGame.New();

        if(game.IsOver())
            return game;

        var chosenLetter = HangmanGame.ValidLetters
            .FirstOrDefault(letter => referrerQuery.Contains(String.Format("_hangman_{0}_", letter)));

        if (chosenLetter != default(char))
            game.RegisterGuess(chosenLetter);

        return game;
    }
}

Other than this code, there are three more classes that I haven't included since they are pretty long and straightforward:

HangmanGame - here's where the game business rules are implemented
HangmanImageRenderer - the class that encapsulates all the GDI ugliness
ImageResult - a custom ActionResult that is used to return a dynamically generated image

The entire code listing is available at http://pastebin.com/ccwZLknX


Jelly, 24 22 20 bytes

pS€ỤỤs
LÆDżṚ$SÞḢç/ịṢ

Try it online!

Saved 2 bytes thanks to @Jonathan Allan.

Explanation

pS€ỤỤs  Helper link. Input: integer a (LHS), integer b (RHS)
p       Cartesian product between [1, 2, ..., a] and [1, 2, ..., b]
 S€     Sum each pair
   Ụ    Grade up
    Ụ   Grade up again (Obtains the rank)
     s  Split into slices of length b

LÆDżṚ$SÞḢç/ịṢ  Main link. Input: list A
L              Length
 ÆD            Divisors
     $         Monadic pair
    Ṛ            Reverse
   ż             Interleave
                 Now contains all pairs [a, b] where a*b = len(A)
      SÞ       Sort by sum
        Ḣ      Head (Select the pair with smallest sum)
         ç/    Call helper link
            Ṣ  Sort A
           ị   Index into sorted(A)


MATL, 10 6 bytes

4 bytes saved thanks to Martin!

19\qX!

Try it online!

19\            % implicitly take input (a character) and compute mod-19 of its ASCII code
   q           % subtract 1. Gives 17, 2, 3, 4 for the characters '^<v>' respectively.
               % These numbers correspond to 1, 2, 3, 4 modulo 4, and so are the numbers
               % of 90-degree rotations required by each character
    X!         % implicitly take input (string). Rotate the computed number of times
               % in steps of 90 degrees. Implicitly display

Old version, without modulo operations: 10 bytes

'^<v>'=fX!

Try it online!

'^<v>'         % push string
      =        % implicitly take input (a char) and test for equality
       f       % find index of matching character
        X!     % implicitly take input (string). Rotate that number of times
               % in steps of 90 degrees. Implicitly display


Workaround in Excel for silly Rules Regarding Mouse Inputs on Code Golf Stack Exchange: (WESRRMICGSE) 28 bytes

rank(RC[1],r1c1:r1024:c1024)

Input list as csv (10,23,34,2,) into the compiler after entering the source. no quotes, no brackets, trailing comma.

WESRRMICGSE is exactly like programming in excel, except you can omit the initial '=' sign to save a byte. The difference in functionality comes from the fact that WESRRMICGSE will either drag the formula down to copy the code automatically and provide different outputs provided with a single integer input. provided a list as input, that list goes into the B column (input column), and the formula is drug down automatically to match the number of inputs. (eg: the input 34,21,45, would 'drag' the formula down 2 cells, for a total of 3 cells with the formula).

Edit: I never expected this answer to be popular. Wow!


Mathematica, 95 86 bytes

Since the method of input has not been specified, I'm simply expecting the resolution to be saved as an integer in the variable n

r={{""}};Do[r=ArrayFlatten[r/.q_String:>{{q<>"2",q<>"1"},{q<>"3",q<>"4"}}],{Log2@n}];r

With indentation:

r = {{""}};
Do[
  r = ArrayFlatten[
    r /. q_String :> {{q <> "2", q <> "1"}, {q <> "3", q <> "4"}}
  ],
  {Log2@n}
];
r


(OP)

This is based on the example Python script in the question.

I used the simplest edit distance rather than a cleverer patience diff.

For aligning genomes there's Multi Sequence Alignment algorithms and they could well make an even better job than just considering each pair of adjacent frames?

I was pleasantly surprised how straightforward it was to implement edit distance for the diff, and made it compatible with Python's difflib.ndiff format.  There are plenty of Python implementations of edit distance to be found on the web, but I think my formulation is that little bit tidier and deals with the tricky but essential part of actually determining the path in the table too; in our context, we need to know the steps to turn one into another and not just how many steps there are.

I introduced syntax highlighting using a very simple tokenizer that ought to be able to cope with most c-like languages including, by its laxity, Python and such.  It splits the source into punctuation, whitespace, strings (with escape support) and everything else is an identifier and checked against a list of keywords.  The colouring is also easy to change.

It was easy to integrate the syntax highlighting into a dynamic language; the highlighter outputs a list of character and colour pairs, and the differ is agnostic to whether its diffing strings or any arbitrary iterables of comparables!  An interesting - and deliberate - effect of highlighting first and then diffing is that characters that remain unchanged but change colour get animated.  I didn't want to compute the highlight each frame as that would mean that as you delete a closing string you'd suddenly flash a big chunk of text up as string.

Python's support for authoring GIF is rather limited.  PIL doesn't do it, and Pillow does it rather badly.  I use Pillow, but then have to run through gifsicle to compress and add looping etc; Pillow doesn't correctly write frame timing and doesn't let you manage disposal methods etc, which is a shame as the differ has so much better understanding of the scene than a post-processing step dealing with flattened frames :(

Sourcecode


Python, 33 bytes

lambda x,y,k,X,Y,K:k>X-x>-K<Y-y<k

Python supports chains of inequalities even when they point opposite directions.
The x-coordinate intervals [x,x+k) and [X,X+K) overlap as long as neither one is fully to the right of the other, which means that each interval's left endpoint is left of the other interval's right endpoint.
x<X+K
X<x+k

The can be combined into a joint inequality -K<X-x<k. Writing the same for y-coordinates and splicing them at -K gives the expression
k>X-x>-K<Y-y<k


Join N copies of a snippet to produce N^2 characters

TECO, 4 bytes
V1\V

V prints the contents of the current line in the text buffer. 1\ inserts the string representation of the number 1 at the current position.
So on the Nth iteration of the program, the first V will output N - 1 copies of the character 1, then add another 1 to the text, then output N 1s.


x86 machine code, DOS executable, 29* 28 bytes

FAE464D0E873FAE460D0E073F4D41005212192B402CD2188F2CD21EBE3

This is a COM executable for MS-DOS, it requires a IBM PC compatible hardware.
Particularly an 8042 PS/2 controller or more likely an emulation of it through SMM.
Long story short, it should work out of the box in any mainstream PC.

The source code is

BITS 16

 ;Disable the interrupts so we don't compete with the IRQ 1 (the 8042 main
 ;device IRQ) handler (the ISR n. 9 by default) for the reading of the codes.
 cli

_wait:

 ;Is 'Output buffer full (OBF)' bit set?

 in al, 64h                ;Read the 8042 status register
 shr al, 1                 ;Move bit 0 (OBF) into the carry flag

jnc _wait                  ;Keep spinning if CF = OBF not set

 ;Read the scan code S
 in al, 60h

 ;Is S a break code?

 shl al, 1                 ;Bit 7 is set if it is
jnc _wait

 ;PART 2

 ;AL = S mod 10h := y, AH = S / 10h := x
 aam 16
 add ax, 2121h             ;Make both quantities in the printable ASCII range (skip space though)

 ;Print y
 xchg dx, ax
 mov ah, 02h
 int 21h                   ;int 21/ah=02 prints the char in DL

 ;DH is still valid here, it holds x. We print it now
 mov dl, dh
 int 21h

 ;Never terminate
jmp _wait

I've divided the program into two parts.

The first part deals with the reading of the scancodes. Scancodes are numeric values associated with every key.
Note that these are hardware code, they don't depend on the OS or the charset. They are like an encoded pair (column, row) of the key.
Every key has a scancode, even those non-standard weird function keys found on some keyboard (e.g. the "open calc" key).
Some key has multi-byte scancode, they have prefixes designed to make the stream decodificable by just looking at the sequence of bytes.
So each key gets its unique identifier, even CTRL, SHIFT, WinKeys and so on.

Only the "break codes", sent when a key is released, are processed, the "make codes" are ignored.
The formers have the higher bit (bit 7 for a byte) set, so it's easy to recognise them.

The second part deals with the printing of a byte.
Printing is always lengthy in assembly, we have no builtins.
To keep it short, and since it was required to write an identifier of the key, I abandoned decimal or hex numerals in favour of a personal encoding.

A byte xy, where x is the higher nibble and y the lower is printed as two successive chars c0 and c1 defined as:

c0 = 0x21 + y
c1 = 0x21 + x

Note that the lower nibble is printed first (this spared me a swap).
The rationale is to map the each one of the 16 possible values of a nibble into consecutive ASCII characters from '!'.
Simply put this is a hex numeral but with

The nibbles swapped
!"#$%&'()*+,-./01 as digit(als) instead of 0123456789abcdef

Running it in DOSBox and pressing some random key (some of which is a special key but note that as a Windows process DOSBox can't capture all the keys) yields

Note that this program never terminates (further, it takes complete control of the PC by disabling the interrupts) as I believe was intended by the question (simply there is no killing of processes in DOS).

* Reduced thank to CodyGray.


Python 2, 43 bytes

f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)

Test it on Ideone.
How it works
Call the function defined in the specification \$g(a, b)\$. We have that
$$
\newcommand{\sumab}[2]{\sum_{a \le #1 \le b} #2 \:}
\begin{align}
g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\
& = \sumab {i,j} {ij} - \sumab n {n^2} \\
& = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\
& = 2 \sumab {j<i} {ij} \\
& = 2 \sumab {i} {\sum_{a \le i < j} ij} \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)}
\end{align}
$$
Define the function \$f(x, y, s)\$ recursively as follows.
$$ f(x, y, s) =
\begin{cases}
2xs + f(x+1, y, s+x) & \text{ if } x \le y \\
0 & \text{ if} x > y
\end{cases}
$$
By applying the recurrence relation of \$f(a, b, 0)\$ a total of \$b - a\$ times, we can show that:
$$
\begin{align}
f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\
& \vdots \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} \\
& = g(a, b)
\end{align}
$$
This is the function f of the implementation. While b/a returns a non-zero integer, the code following and is executed, thus implementing the recursive definition of f.
Once b/a reaches 0, we have that b > a and the lambda returns False = 0, thus implementing the base case of the definition of f.


Mathematica, 43 bytes

Last@SymmetricReduction[#,Variables@#]===0&

Unnamed function taking as input a polynomial in the given format (except that juxtaposed variables must be separated by a space) and returning True or False. Variables@# detects the variables appearing in the input (and thus the input can contain all kinds of weird variable names, not just single letters). SymmetricReduction returns an ordered pair of polynomials, where the first one is symmetric and the two sum to the original polynomial; therefore we can detect whether the input is symmetric by seeing whether the second polynomial is identically 0.


Python 2, 298 bytes

def f(x,E=enumerate):
 o=[]
 while any(x):
	for k,p in E(x):
	 e=0
	 if sum(i(p,j)for j in x)<1:
		for d,r in E(o):
		 if i(p,r[-1])*((r[-1]<e)or e==0):m,e=d,r[-1]
		if e:o[m]+=[p]
		else:o+=[[p]]
		x[k]=''
 print sorted(o)
i=lambda p,b:(b!=p)*any([p==b[j:j+len(p)]for j in range(len(b)-len(p)+1)])

Try it online!

-28 bytes with tips from @dylnan, bug find by @Dennis, and bug fix by @Mr.Xcoder


Proof that every repunit has a novel prime factor
Using Zsigmondy's Theorem, the proof is simple. From Wikipedia:

In number theory, Zsigmondy's theorem, named after Karl Zsigmondy,
states that if a > b > 0 are coprime integers, then for any integer n
≥ 1, there is a prime number p (called a primitive prime divisor) that
divides an − bn and does not divide ak − bk for any positive integer k
< n, with the following exceptions: [things that don't apply here].

Consider the repunits times 9: that is, 10n-1. By Zsigmondy's Theorem with a=10, b=1, there is some prime p | 10n-1 that does not divide any 10k-1, k < n.

Since p is prime and 10n-1 = 9 · Rn, it must divide either 9 or Rn.

p cannot divide 9, since 9 = 101-1.

Therefore p divides Rn.

p cannot divide any Rk, since it doesn't divide 10k-1 = 9 · Rk.

Therefore the p from Zsigmondy's Theorem is a novel prime factor of any Rn, n ≥ 2. ∎

An example of a repeated novel prime factor
The prime 487 is a repeated prime factor of R486:
By the Fermat-Euler theorem, 10487-1 ≡ 1 (mod 487). The order of 10 mod 487, that is, the smallest power of 10 that is 1 mod 487, therefore must be a divisor of 486. In fact, the order is equal to 486. It also happens that not only is 10486 ≡ 1 (mod 487), it's also 1 (mod 4872).
See here that the order of 10 mod 487 is 486; that is, that no smaller 10k-1 is divisible by 487. Obviously, 487 doesn't divide 9, so it must divide R486.


Bash, 30 bytes

curl -F'sprunge=<-' sprunge.us

Just removed the unneeded space in -F 'sprunge=<-' and the http:// from the sprunge.us url.  OP gave me explicit permission to golf his reference solution.


Dyalog APL, 90 bytes

{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←⍴⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}

Takes list of two numbers as argument. Needs ⎕IO←0 which is default on many systems.

      f←{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←≢⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}
      f¨(17282 1342)(1596 8404)(1776 76)(123 456)
┌──────┬─────┬─────┬────┐
│   1  │1111 │  11 │    │
│ 17282│ 1596│ 1776│ 123│
│+ 1342│+8404│+  76│+456│
│ -----│ ----│ ----│ ---│
│ 18624│10000│ 1852│ 579│
└──────┴─────┴─────┴────┘

TryAPL online! Note that ⎕IO has been set and ⍎ has been emulated with e as ⍎ is banned from TryAPL for security reasons.

Ungolfed and explained

  { An anonymous function

    w ← ⍕ ⍪⍵ w gets the textified vertical arrangement of the argument
    (the numbers to be added)

    l ← ≢ ⍉w s gets the count of rows in the transposed w (i.e. the
    number of columns in w)

    s ← ⍕ +/⍵ s gets the textified sum of the argument

    ' 1'[... index into the string " 1", so zeros give spaces, and ones
    give character 1s.

      ⊂[0] w enclose down, gets list of pairs of corresponding digits in
      the numbers

      (+/ 0 10 ⊤ ⍎)¨ for each pair; make into digit(s), then sum

      (⍎¨ (-l) ↑ s)- chop left-most digit of grand total to the width of
      the longest input, then make each character into separate number and
      subtract the column sums (if the sum does not add up to the total, the
      discrepancies are due to carrys, so this gives us each column's carry)

      10| division remainder when divided by 10

    ] [end of indexing]

    w⍪⍨ stack the input numbers below

    '-'⍪⍨ stack a minus below each column

    (' + ',⍨' 1'⊃⍨l<⍴s), prepend a space to the 2nd line, a
    plus to the 3nd, a space to the 4rd, and a one
    or space to the 1st – depending on if the sum is wider than
    the widest input (meaning we need a carry high over the plus )

    ⌽ mirror right-left (so left-justification will be to the right)

    ↓ make table into list of lines (so that differing line lengths are
    allowed

    (⊂⌽s),⍨ append the sum

    ↑ combine list of lines into table (padding the right with spaces as
    needed)

    ⌽ mirror back to normal

  } [end of function]`


Pyth, 5 bytes
/^2Q4

I integer-divide by 4 instead of subtracting two from the power and flooring.


CJam, 189 187 bytes

This one's gonna be tough to explain... Time complexity is guaranteed to be O(scary).

qi:N_3>{,aN*]N({{:L;N,X)-e!{X)_@+L@@t}%{X2+<z{_fe=:(:+}%:+!},}%:+}fX{:G;N3m*{_~{G@==}:F~F\1m>~F\F=}%:*},:L,({LX=LX)>1$f{\_@a\a+Ne!\f{\:M;~{M\f=z}2*\Mff==}:|{;}|}\a+}fX]:~$e`{0=1=},,}{!!}?

If you're brave enough, try it online. On my crappy laptop I can get up to 6 with the Java interpreter or 5 in the online interpreter.

Explanation

I don't have a big math background (just finished high school, starting CS at uni next week). So bear with me if I make mistakes, state the obvious, or do things in horribly inefficent ways.

My approach is a brute force, though I tried to make it a little more clever. The main steps are:

Generate all the possible operands ∗ for a group of order n (i.e., enumerate all groups of order n);
Generate all the possible bijections φ between two groups of order n;
Using the results from steps 1 and 2, determine all isomorphisms between two groups of order n;
Using the result from step 3, count the number of groups up to isomorphism.

Before looking at the how each step is done, let's get some trivial code out of the way:

qi:N_             e# Get input as integer, store in N, make a copy
     3>{...}    ? e# If N > 3, do... (see below)
            {!!}  e# Else, push !!N (0 if N=0, 1 otherwise)

The following algorithm doesn't work correctly with n < 4, the cases from 0 to 3 are handled with a double negation.

From now on, the elements of a group will be written as {1, a, b, c, ...}, where 1 is the identity element. In the CJam implementation, the corresponding elements are {0, 1, 2, 3, ...}, where 0 is the identity element.

Let's start from step 1. Writing all possible operators for a group of order n is equivalent to generating all the valid n×n Cayley tables. The first row and column are trivial: they are both {1, a, b, c, ...} (left-to-right, up-to-down).

      e# N is on the stack (duplicated before the if)
,a    e# Generate first row [0 1 2 3 ...] and wrap it in a list
  N*  e# Repeat row N times (placeholders for next rows)
    ] e# Wrap everything in a list
      e# First column will be taken care of later

Knowing that a Cayley table is also a reduced Latin square (due to the cancellation property) allows to generate the possible tables row-by-row. Starting from the second row (index 1), we generate all the unique permutations for that row, keeping the first column fixed to the value of the index.

N({                                 }fX e# For X in [0 ... N-2]:
   {                            }%      e#   For each table in the list:
    :L;                                 e#     Assign the table to L and pop it off the stack
       N,                               e#     Push [0 ... N-1]
         X)                             e#     Push X+1
           -                            e#     Remove X+1 from [0 ... N-1]
            e!                          e#     Generate all the unique permutations of this list
              {         }%              e#     For each permutation:
               X)_                      e#       Push two copies of X+1
                  @+                    e#       Prepend X+1 to the permutation
                    L@@t                e#       Store the permutation at index X+1 in L
                          {...},        e#     Filter permutations (see below)
                                  :+    e#   Concatenate the generated tables to the table list

Not all those permutations are valid, of course: each row and column must contain all the elements exactly one time. A filter block is used for this purpose (a truthy value keeps the permutation, a falsy one removes it):

X2+                 e# Push X+2
   <                e# Slice the permutations to the first X+2 rows
    z               e# Transpose rows and columns
     {        }%    e# For each column:
      _fe=          e#   Count occurences of each element
          :(        e#   Subtract 1 from counts
            :+      e#   Sum counts together
                :+  e# Sum counts from all columns together
                  ! e# Negate count sum:
                    e#   if the sum is 0 (no duplicates) the permutation is kept
                    e#   if the sum is not zero the permutation is filtered away

Note that I am filtering inside the generation loop: this makes the code a bit longer (compared to distinct generation and filtering), but greatly improves performance. The number of permutations of a set of size n is n!, so the shorter solution would require a lot of memory and time.

A list of valid Cayley tables is a great step towards enumerating the operators, but being a 2D structure, it can't check for associativity, which is a 3D property. So next step is filtering out non-associative functions.

{                                 }, e# For each table, keep table if result is true:
 :G;                                 e#   Store table in G, pop it off the stack
    N3m*                             e#   Generate triples [0 ... N-1]^3
        {                     }%     e#   For each triple [a b c]:
         _~                          e#     Make a copy, unwrap top one
           {    }:F                  e#     Define function F(x,y):
            G@==                     e#       x∗y (using table G)
                   ~F                e#     Push a∗(b∗c)
                     \1m>            e#     Rotate triple right by 1
                         ~           e#     Unwrap rotated triple
                          F\F        e#     Push (a∗b)∗c
                             =       e#     Push 1 if a∗(b∗c) == (a∗b)∗c (associative), 0 otherwise
                                :*   e#   Multiply all the results together
                                     e#   1 (true) only if F was associative for every [a b c]

Phew! Lots of work, but now we have enumerated all groups of order n (or better, the operations on it - but the set is fixed, so it's the same thing). Next step: find isomorphisms. An isomorphism is a bijection between two of those groups such that φ(x ∗ y) = φ(x) ∗ φ(y). Generating those bijections in CJam is trivial: Ne! will do it. How can we check them? My solution starts from two copies of the Cayley table for x ∗ y. On one copy, φ is applied to all elements, without touching the order of rows or columns. This generates the table for φ(x ∗ y). On the other one the elements are left as they are, but rows and columns are mapped through φ. That is, the row/column x becomes the row/column φ(x). This generates the table for φ(x) ∗ φ(y). Now that we have the two tables, we just have to compare them: if they are the same, we have found an isomorphism.

Of course, we also need to generate the pairs of groups to test isomorphism on. We need all the 2-combinations of the groups. Looks like CJam has no operator for combinations. We can generate them by taking each group and combining it only with the elements following it in the list. Fun fact: the number of 2-combinations is n × (n - 1) / 2, which is also the sum of the first n - 1 natural numbers. Such numbers are called triangular numbers: try the algorithm on paper, one row per fixed element, and you'll see why.

:L                          e# List of groups is on stack, store in L
  ,(                        e# Push len(L)-1
    {                  }fX  e# For X in [0 ... len(L)-2]:
     LX=                    e#   Push the group L[X]
        LX)>                e#   Push a slice of L excluding the first X+1 elements
            1$              e#   Push a copy of L[X]
              f{...}        e#   Pass each [L[X] Y] combination to ... (see below)
                            e#   The block will give back a list of Y for isomorphic groups
                    \a+     e#   Append L[X] to the isomorphic groups
                          ] e# Wrap everything in a list

The code above fixes the first element of the pair, L[X], and combines it with other groups (let's call each one of those Y). It passes the pair to a isomorphism test block that I'll show in a moment. The block gives back a list of values of Y for which L[X] is isomorphic to Y. Then L[X] is appended to this list. Before understanding why the lists are set up in such a way, let's look at the isomorphism test:

\_@                                      e# Push a copy of Y
   a\a+                                  e# L[X] Y -> [L[X] Y]
       Ne!                               e# Generate all bijective mappings
          \f{                    }       e# For each bijection ([L[X] Y] extra parameter):
             \:M;                        e#   Store the mapping in M, pop it off the stack
                 ~                       e#   [L[X] Y] -> L[X] Y
                  {     }2*              e#   Repeat two times (on Y):
                   M\f=                  e#     Map rows (or transposed columns)
                       z                 e#     Transpose rows and columns
                                         e#     This generates φ(x) ∗ φ(y)
                           \Mff=         e#   Map elements of L[X], generates φ(x ∗ y)
                                =        e#   Push 1 if the tables are equal, 0 otherwise
                                  :|     e#   Push 1 if at least a mapping was isomorphic, 0 otherwise
                                    {;}| e#   If no mapping was isomorphic, pop the copy of Y off the stack

Great, now we have a list of sets like [{L[0], Y1, Y2, ...}, {L[1], Y1, ...}, ...]. The idea here is that, by transitive property, if any two sets have at least one element in common then all the groups in the two sets are isomorphic. They can be aggregated into a single set. As L[X] will never appear in the combinations generated by L[X+...], after aggregating each set of isomorphisms will have one unique element. So, to get the number of isomorphisms, it's sufficient to count how many groups appear exactly once in all sets of isomorphic groups. To do this, I unwrap the sets so they look like [L[0], Y1, Y2, ..., L[1], Y1, ...], sort the list to create clusters of the same group and finally RLE-encode it.

:~            e# Unwrap sets of isomorphic groups
  $           e# Sort list
   e`         e# RLE-encode list
     {    },  e# Filter RLE elements:
      0=      e#   Get number of occurrences
        1=    e#   Keep element if occurrences == 1
            , e# Push length of filtered list
              e# This is the number of groups up to isomorphism

That's all, folks.


Is this a Hardy-Ramanujan-Number-ish Harshad Number?

ArnoldC, 888 Bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE a
YOU SET US UP 0
GET TO THE CHOPPER a
HERE IS MY INVITATION 1
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE b
YOU SET US UP 0
GET TO THE CHOPPER b
HERE IS MY INVITATION 81
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE c
YOU SET US UP 0
GET TO THE CHOPPER c
HERE IS MY INVITATION 1458
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE d
YOU SET US UP 0
GET TO THE CHOPPER d
HERE IS MY INVITATION 1729
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE res
YOU SET US UP 0
GET TO THE CHOPPER res
HERE IS MY INVITATION a
CONSIDER THAT A DIVORCE b
CONSIDER THAT A DIVORCE c
CONSIDER THAT A DIVORCE d
ENOUGH TALK
TALK TO THE HAND res
YOU HAVE BEEN TERMINATED

I know, I just check for equality, but that shouldn't be the fun part of the program.

Enjoy reading it. :)

Added some newlines there for easier readability:

Try it online


Determine number of connected components

Ruby, 77 characters
gets;0while$_.sub!(/\b(\d+)\b(.*) (\1-\d+|\d+-\1)\b/,'\3\2');p$_.count(" ")+1

A first plain attempt in Ruby. It collects the sub-graphs using a regular expression until no more connections can be made.
Examples:
> 1-2 2-3 3-4 4-1
1

> 1-2 2-3 4-5
2

> 1-2 3-4 8-9 1-6 5-7 7-4 10-9
3


Haskell, 67 65 63 62 58 bytes

Saved 4 bytes thanks to Julian Wolf

f x=[[2*n+1,2*n+3..2*m]|n<-[0..x],m<-[n..x],m^2-n^2==x]!!0

Try it online!

I check if the number can be expressed as he difference of two squares: m^2-n^2. I can then construct the list of consecutive odd numbers: [2n+1,2n+3...2m-1]. Note that because the minimum n is chosen, the longest list will be output


Mathematica, 16 bytes
N[Tan[Pi/#]#,9]&

Try it online!
of course mathematica has built-ins for this
Area@*RegularPolygon


Python 2, 220 ... 124 119 Bytes

Huge thanks to Sp3000 for saving a lot of bytes.

f='qwertyuiopasdfghjkl zxcvbnm'.find
g=lambda i:sum(abs(f(x)%10-f(y)%10)+2*abs(f(x)/10-f(y)/10)for x,y in zip(i,i[1:]))

Usage:

g("tttt") -> 0

Check it out here.

Slightly ungolfed + explanation:

f='qwertyuiopasdfghjkl zxcvbnm'.find  # Defining keyboard rows and aliasing find
g=lambda i:                           # Defining a function g which takes variable i
    sum(                              # Sum of
        abs(f(x)%10-f(y)%10)          # horizontal distance, and
        + 2*abs(f(x)/10-f(y)/10)      # vertical distance,
        for x,y in zip(i,i[1:]))      # for each pair in the zipped list

# Example of zipping for those unaware:
# Let i = asksis, therefore i[1:] = sksis, and zip would make
# the list of pairs [(a,s),(s,k),(k,s),(s,i),(i,s)].


Jelly, 5 bytes

IA<S}

Takes two complex numbers (centers) as first argument, and two real numbers (radii) as second argument.

Try it online!

How it works

IA<S}  Main link.
       Left argument:  [x1 + iy1, x2 + iy2]
       Right argument: [r1, r2]

I      Increments; yield (x2 - x1) + i(y2 - y1).
 A     Absolute value; yield √((x2 - x1)² + (y2 - y1)²).
   S}  Take the sum of the right argument, yielding r1 + r2.
  <    Compare the results.


J (4 bytes)

Couldn't resist.

?~10

In J, if F is dyadic , F~ x is the same as x F x.


GolfScript, -153

{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

Prints

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

Score:

97 bytes of source code: +97
Shooting the Sun: -250

Try it online.

How it works

Since the code block (lambda, anonymous function)

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

does not contain any syntax errors, it will be pushed on the stack and printed verbatim if left on it. The linefeed is required to end the comment that # started.

Finally, ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 is an undefined token; it does nothing.


R, 821 - 44 = 777 bytes

Updated results: please see the edit history to make sense of all the comments below.

           language num_answers avg_count median_count
1              RUBY          49  49.97959         30.0
2              CJAM          48  32.64583         22.0
3              PYTH          48  21.02083         14.0
4          PYTHON 2          46  86.78261         77.0
5             JULIA          43  58.90698         45.0
6           HASKELL          41  74.65854         56.0
7               PHP          40  73.52500         48.0
8              PERL          36  53.30556         34.0
9          PYTHON 3          34  90.91176         90.5
10       POWERSHELL          33  60.24242         44.0
11                C          32 221.84375         79.5
12                R          32  77.40625         62.5
13             JAVA          29 170.68966        158.0
14 JAVASCRIPT (ES6)          29  90.79310         83.0
15       JAVASCRIPT          28  68.39286         61.0
16               C#          25 193.92000        130.0
17      MATHEMATICA          23  56.04348         47.0
18           MATLAB          22  67.45455         55.0
19         TI-BASIC          19  47.05263         37.0
20              APL          18  16.55556         15.0

The code, which I could shorten a bit more:

W=library;W(XML);W(plyr)
X=xpathSApply;Y=xmlValue;D=data.frame;H=htmlParse;S=sprintf
Z="http://codegolf.stackexchange.com/"
R=function(FUN,...)do.call(rbind,Map(FUN,...))
G=function(url){d=H(url)
a=as.double(sub(".*?(\\d+)a.*","\\1",X(d,"//div[starts-with(@class,'status')]",Y)))
u=paste0(Z,X(d,"//*[contains(@class,'question-hyperlink')]",xmlGetAttr,"href"))
D(u,a)}
u=S("%s/questions/tagged/code-golf?page=%i",Z,1:50)
q=R(G,u)
u=with(q,head(u[a>20],50))
A=function(url){u=S("%s?page=%i",url,1:10)
f=function(u){d=H(u)
h=X(d, "//div[@class='post-text']//h1",Y)
p="^(.*?),.*? (\\d+)( [Bb]ytes)?$"
k=grep(p,h,v=T)
l=toupper(sub(p,"\\1",k))
c=as.double(sub(p,"\\2",k))
D(l,c)}
R(f,u)}
a=R(A,u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,l%in%L)
arrange(ddply(x, "l",summarise,n=length(c),a=mean(c),m=quantile(c,0.5)),-n)

De-golfed:

library(XML)
library(plyr)
LoopBind <- function(FUN, ...) do.call(rbind, Map(FUN, ...))
GetQuestions <- function(url) {
  d = htmlParse(url)
  a=as.double(sub(".*?(\\d+)a.*","\\1",xpathSApply(d, "//div[starts-with(@class, 'status')]", xmlValue)))
  u=paste0("http://codegolf.stackexchange.com/",xpathSApply(d, "//*[contains(@class, 'question-hyperlink')]", xmlGetAttr, "href"))
  data.frame(u, a)
}
u <- sprintf("http://codegolf.stackexchange.com/questions/tagged/code-golf?page=%i", 1:50)
q <- do.call(rbind, Map(GetQuestions, u))
u <- with(q, head(u[a > 20], 50))

GetAnswers <- function(url) {
  u=sprintf("%s?page=%i",url,1:10)
  f=function(u) {
    d = htmlParse(u)
    h = xpathSApply(d, "//div[@class='post-text']//h1", xmlValue)
    p = "^(.*?),.*? (\\d+)( [Bb]ytes)?$"
    k = grep(p,h,v=T)
    l = toupper(sub(p,"\\1",k))
    c = as.double(sub(p,"\\2",k))
    data.frame(language=l,c)
  }
LoopBind(f,u)
}
a=LoopBind(GetAnswers, u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,language%in%L)
arrange(ddply(x, "language", summarise, num_answers = length(c), avg_count = mean(c), median_count = quantile(c,0.5)),
        -num_answers)


Perl 5: 98

98 including 2 command line flags.

#!perl -p0
1while/
/,($x="($`)")=~y!#!.!,s/#(.*
$)/%$1/+s/#$x?%|%$x?#/%$1$2%/s;1while s/#$x\./.$1#/s;y!%!#!

Explanation:

#!perl -p0 #read entire input to $_ and print at the end
/\n/;($x="($`)")=~y!#!.!; #calculate pattern matching space
                          #between two characters in the same column
                          #looks like "(......)"
1 while s/#(.*\n$)/%$1/+s/#$x?%|%$x?#/%$1$2%/s;
                          #flood fill solid rock with %
1 while s/#$x\./.$1#/s;   #drop loose rock
y!%!#!                    #change % back to #


Jelly, 9 7 bytes

IsJEƇḢḢ

Try it online!

How it works

IsJEƇḢḢ  Main link. Argument: A (array)

I        Increment; compute D, the array of A's forward differences.
  J      Indices; yield [1, ..., len(A)].
 s       Split D into chunks of length k, for each k in [1, ..., len(A)].
   EƇ    Comb equal; keep only partitions of identical chunks.
     Ḣ   Head; extract the first matching parititon.
      Ḣ  Head; extract the first chunk.


Python 3, 35 bytes

lambda w,n,p:-min(0,(w-p*n)//(1-p))

Try it online!
-4 bytes thanks to pajonk
Some simple math: if \$X\$ is the number of wins we need, then we have:
\$\frac{W+X}{N+X}\geq P\$
\$W+X\geq PN+PX\$
\$X-PX\geq PN-W\$
\$X(1-P)\geq PN-W\$
Since \$P<1\$, then \$1-P>0\$, so we can divide from both sides without division by zero or flipping the sign.
\$X\geq\frac{PN-W}{1-P}\$


Python 2, 167 bytes

lambda a:([q for q in range(a[-1])if a in[sorted(sum(j,[]))for j in combinations([[p for p in a if p%i<1]for i in range(2,1+a[-1])],q)]]+[0])[0]
from itertools import*

Try it online!

-9 bytes thanks to Zacharý
-4 bytes thanks to Mr. Xcoder
-2 bytes by using lists instead of sets
-5 bytes by using a in [...] rather than any([a == ...]).
-2 bytes thanks to Mr. Xcoder
-8 bytes by merging statements
-5 bytes thanks to Mr. Xcoder
-7 bytes thanks to Mr. Xcoder / Zacharý
+7 bytes to fix bug
-1 byte thanks to ovs

note

This is extremely slow for larger maximum numbers because it is in no way optimized; it did not within 2 minutes on Mr. Xcoder's device for [22, 24, 26, 30].


"Atomic" code golf - determine the number of neutrons in an isotope


Java 11, 156 151 148 118 89 bytes

n->"╔"+"╦".repeat(n-=3)+"╗\n"+("╠"+"╬".repeat(n)+"╣\n").repeat(n+1)+"╚"+"╩".repeat(n)+"╝"

Try it online.
Old 118 bytes answer in Java 8:
n->{String a="╔",b="╠",c="╚";for(int i=n;i-->3;a+="╦",b+="╬")c+="╩";a+="╗\n";for(b+="╣\n";n-->2;)a+=b;return a+c+"╝";}

-30 bytes by creating a port of @raznagul C# (.NET Core) answer, after I golfed 5 bytes.
Try it here.
Explanation:
n->                    // Method with integer parameter and String return-type
  "╔"                  //  The top-left corner
  +"╦"                 //  Appended with the top edge
      .repeat(n-=3)    //  Repeated input-3 times (-2 for the corners, -1 for width)
  +"╗\n"               //  Appended with the top-right corner and a newline
  +("╠"                //   The left edge
    +"╬"               //   Appended with the middle part
        .repeat(n)     //   Repeated input-3 times (-2 for edges, -1 for width)
    +"╣\n"             //   Appended with the right edge and a newline
          ).repeat(n+1)//  And repeat this entire line n-2 times (-2 for first/last rows)
  +"╚"                 //  Appended with the bottom-left corner
  +"╩"                 //  Appended with the bottom edge
      .repeat(n)       //  Repeated input-3 times
  +"╝"                 //  Appended with the bottom-right corners


Perl 6, 174 bytes

{~(.year,(|[X]("diaviolisgilfuldyumelralzanpalmikfavrujserravtanlinrezjildinketlenlaxnenpinmatkunmir".comb(3)xx 2)[^364],|("myuxet"X <axet teems>))[.day-of-year-1])}o*-726436

Try it online!

Generate a list of all the valid dates and then indexes the day of the year into that list.

Explanation

{                                                   }  # Anonymous code block
                                                     o*-726436  # Subtract some days from the input
  (.year,                               # Output the year
           [X]("...".comb(3))[^365]     # Then produce a list of all months/days
         (|                        ,
          |("myuxet"X <axet teems>))    # And the extra days
                                    [.day-of-year-1]   # And get the current date
 ~   # Stringify the list


MATL, 18 bytes
_G2$:iZ^t!|X>4#SY)

First input is s, second is n
This works in current version (15.0.0) of the language.
Try it online!
Explanation
_      % take input s implicitly. Negate to obtain -s
G      % push input s again
2$:    % inclusive range from -s to s
i      % take input n
Z^     % Cartesian power. Gives 2D array, with each result on a row
t!     % duplicate and transpose
|      % absolute value
X>     % maximum of each column
4#S    % sort and push the indices of the sorting
Y)     % apply as row indices into the 2D array. Display implicitly


05AB1E, 3 bytes

L/O

Try it online!
or as a Test suite

Explanation

L     # range [1 ... n]
 /    # divide n by each in above list
  O   # sum


Common Lisp, 223 95 68 66
(#1=(lambda(x p)(format t"~S~%~S"p`(,x',x,(+(/ p 2)(/ p)))))'#1#1)

Now that I read the problem statement more carefully (thanks, primo!) I noticed that the first line must be the result of calculation, not that it needs to contain the result. Thus, I think my earlier attempts did not quite follow the rules. This one should.
Example use (SBCL 1.1.15):
$ sbcl --script nq.lisp | tee nq2.lisp
1
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 3/2)
$ sbcl --script nq2.lisp | tee nq3.lisp
3/2
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 17/12)
$ sbcl --script nq3.lisp | tee nq4.lisp
17/12
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P))))) 577/408)
$ sbcl --script nq4.lisp | tee nq5.lisp
577/408
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 665857/470832)
$ sbcl --script nq5.lisp | tee nq6.lisp
665857/470832
((LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 '(LAMBDA (X P) (FORMAT T "~S~%~S" P `(,X ',X ,(+ (/ P 2) (/ P)))))
 886731088897/627013566048)
$


Perl 6 (29 28 characters)

This was somewhat annoying, but I finally managed to make a program for this task. Thanks go to the great #perl6 community, for helping me with this task. It took me two hours, hope you enjoy. The output is completely up to specification, including a newline.

say
Q[@A`DO world!]~|<HeLhg>

There are four tokens of interest.

say

This outputs the argument with new line at end. The new line after the command itself is needed as a space replacement.
Q[@A`DO world!]

This is the first string. Q[] is for raw strings (like r"" in Python). It can take any delimiter (or pair of them), in this case []. In this case, I use this for quotes, I don't need raw string behavior.
~|

This is stringwise (~) bitwise or (|) operator.
<HeLhg>

<> is list literal, which takes space separated list of elements. In this case, it has one element, and used as a scalar, it gives a string.


Retina 0.8.2, 106 103 bytes

S230 by41h012 are30,5.¶So if1230 on4n5123ore1h0.
5
 I'm1ure
4
 the3ore,¶The
3
1eash
2
he10
1
 s
0
ells

Try it online! Explanation: In Retina, a substitution only makes sense if it's long enough l for the number n of repetitions. The substitution saves n(l-1) bytes in the compressed text but costs l+3 bytes in the replacement stages. This gives the minimum length required to be useful as follows:

2 repetitions: length > 5
3 repetitions: length > 3
4 repetitions: length > 3
5 repetitions: length > 2
6+ repetitions: length > 1

Edit: As @Arnauld pointed out, you can count repetitions from the substitution entries as well. This means that although there were only 5 repetitions of space+s in my previous encoded text, there are also 3 repetitions in the substitutions, thus allowing me to save 3 bytes overall. (@Arnauld himself had only spotted 2 of the 3 repetitions.)


Julia, 64 50 48 42 32 30 bytes

g(x)=[x;x<3||g(x^(x%2+.5)÷1)]

This is a recursive function that accepts an integer and returns a float array.

We build an array by concatenating the input with the next term of the sequence, computed as x to the power of its parity plus 1/2. This gives us either x1/2 or x1+1/2 = x3/2. Integer division by 1 gets the floor. When the condition x < 3 is true, the final element will be a Boolean rather than a numeric value, but since the array is not of type Any, this is cast to have the same type as the rest of the array.

Saved 14 bytes thanks to Dennis!


BBC BASIC, 155 ASCII characters, tokenised filesize 140
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
  a=1s=.000003INPUTx,v
  IFv<1v=9999
  FORw=1TOv-1a=w/a
  NEXTb=SGN(x)*s*a/SQR(v)IFv MOD2b=b/PI ELSEb=b/2
  f=.5FORz=0TOABS(x)STEPs
  f+=b/(1+z*z/v)^(v/2+.5)NEXTPRINTf

The code is in two parts. The first calculates the coefficient that is independent of x. and stores it in b. The algorithm is a bit like a continued fraction, but a mathematician would probably call it a simple quotient of two products. It's based on a formula from the Wikipedia page in the question, which is similar to a factorial but has the product (v-1)(v-3)... divided by the product (v-2)(v-4)... This is possible because we are only interested in half-integral values of the gamma function (arbitrary values of the gamma function would be a lot harder.) Using this formula we never have to calculate either gamma function, so we avoid large numbers. The largest intermediate value is approximately the square root of v.
The second is a straightforward integration from 0 to x by summation. It is known that f(0) is 0.5 so we start from there and work outwards. the sign and magnitude of b are modified before the loop, in order to be able to give the final answer directly.
Pretty version, ungolfed
This contains a few extra lines to add colour and to plot the data. The range x=0 to endpoint, and f(x)=0.5 to 1 is shown. Also v is modified to 2^v to be able to show the full range of v values without exceeding the limits on colour. In order to speed the drawing up, there are two less digits in s than in the golfed version. Even so, there is only one discrepancy when compared with http://www.wolframalpha.com/input/?i=student+t-distribution+probability: 0.8130575 rounds up to 0.8131. The golfed version give the correct answer (0.8130) for this and all the other cases below.
  a=1                              :REM accumulator for gamma series
  s=.0001                          :REM step size for x integration
  INPUTx,v
  IFv<1 v=9999                     :REM if v<1, set v to a value that gives results indistinguishable from infinity
  GCOLv                            :REM pick a colour
  v=2^v                            :REM for the pretty version, modify v to 2^v
  FORw=1TOv-1
    a=w/a                          :REM calculate series as per Wikipedia
  NEXT
  b=a/SQR(v)                       :REM divide a by the necessary values...
  IFv MOD2 b=b/PI ELSE b=b/2       :REM to give the coefficient, per Wikipedia

  b*=SGN(x)*s                      :REM modify according to sign and step size
  f=.5                             :REM initialise f(x)=.5 at x=0
  FORz=0TO ABS(x) STEPs
    f+=b/(1+z*z/v)^(v/2+.5)        :REM perform integration as simple "barchart" sum
    PLOT69,z*100+200,(f-.5)*1600   :REM plot a point
  NEXT
  PRINT f


Bash, 105 bytes

trap -- 'trap|xxd -b -c1|cut -d\  -f2|tr -d \\n|cut -c`x=\`cat f||echo 1\`;echo $((x+1))>f;echo $x`' EXIT

NOTE: Make sure that you don't have an important file called f in the directory you're testing this.

If you want to test this, you can use the following command:

for i in $(seq 848); do bash path/to/script.sh 2> /dev/null; done | tr -d \\n

Which should give the same output xxd -c1 -b path/to/script.sh|cut -d\  -f2|tr -d \\n.

Explanation

This is using the trap trick - calling trap inside the trap action simply prints that line. Next that output gets piped to xxd which converts it to binary (unfortunately xxd -bp doesn't work - thus the workaround with cut & tr):

xxd -c1 -b $0|cut -d\  -f2|tr -d \\n

From that we're only interested in one bit (say N) which we can select with cut -cN.

To find out what N we're using (remember that's the part that needs to be incremented after each call), simply try to set x to the content of the file f and if it doesn't exist set it to 1:

x=`cat f||echo 1`

Last thing to do, is to update the file f - writing x+1 to it:

echo $((x+1))>f


C++, Score: 1.42042 1.46766

This is essentially a slightly more sophisticated version of the two existing solutions:
Of the four possible moves, it selects the one that maximizes brightness.
However, instead of only looking at the brightness of the target pixel, it looks at the weighted sum of pixel-brightness in the neighborhood of the target pixel, where pixels closer to the target have a greater weight.

EDIT: Using nonlinear brightness in neighborhood calculation improves the score slightly.

Compile with g++ joe.cpp -ojoe -std=c++11 -O3 -lcairo. Requires cairo.

Run with joe <image-file> [<radius>].
<image-file> is the input PNG image.
<radius> (optional argument) is the radius of the summed-over neighborhood, in pixels (smaller is faster, larger is (roughly) better.)
Outputs the score and an image named out.<image-file>.

#include <cairo/cairo.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    auto* img = cairo_image_surface_create_from_png(argv[1]);
    int width = cairo_image_surface_get_width(img),
        height = cairo_image_surface_get_height(img),
        stride = cairo_image_surface_get_stride(img);
    unsigned char* data = cairo_image_surface_get_data(img);

    double* brightness = new double[width * height];
    double total_brightness = 0;
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            const unsigned char* p = data + stride * y + 4 * x;
            total_brightness += brightness[y * width + x] = p[0] + p[1] + p[2];
        }
    }

    const int r = argc > 2 ? stoi(argv[2]) : 64, R = 2 * r + 1;
    double* weight = new double[R * R];
    for (int y = -r; y <= r; ++y) {
        for (int x = -r; x <= r; ++x)
            weight[R * (y + r) + (x + r)] = 1.0 / (x*x + y*y + 1);
    }

    auto neighborhood = [&] (int x, int y) {
        double b = 0;
        int x1 = max(x - r, 0), x2 = min(x + r, width - 1);
        int y1 = max(y - r, 0), y2 = min(y + r, height - 1);
        for (int v = y1; v <= y2; ++v) {
            const double *B = brightness + width * v + x1;
            const double *W = weight + R * (v - (y - r)) + (x1 - (x - r));
            for (int u = x1; u <= x2; ++u, ++B, ++W)
                b += (*W) * (*B) * (*B);
        }
        return b;
    };

    int n = (2 * width * height + 3) / 6;
    int x = 0, y = 0;
    double path_brightness = 0;
    int O[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    for (int i = 0; i < n; ++i) {
        if (i % 1000 == 0) cerr << (200 * i + n) / (2 * n) << "%\r";

        path_brightness += brightness[width * y + x]; brightness[width * y + x] = 0;
        unsigned char* p = data + stride * y + 4 * x;
        p[0] = p[1] = 16 * i % 255; p[2] = 0;

        auto O_end = partition(begin(O), end(O), [&] (const int* o) {
            return x + o[0] >= 0 && x + o[0] < width &&
                   y + o[1] >= 0 && y + o[1] < height;
        });
        const int* o_max; double o_max_neighborhood = -1;
        for (auto o = O; o != O_end; ++o) {
            double o_neighborhood = neighborhood(x + (*o)[0], y + (*o)[1]);
            if (o_neighborhood > o_max_neighborhood)
                o_max = *o, o_max_neighborhood = o_neighborhood;
        }
        x += o_max[0]; y += o_max[1];
    }

    cout << (path_brightness * width * height) / (n * total_brightness) << endl;

    cairo_surface_write_to_png(img, (string("out.") + argv[1]).c_str());

    delete []brightness;
    delete []weight;
    cairo_surface_destroy(img);
}

Results

Bridge    1.39945
Balls     1.77714
Scream    1.38349
Fractal   1.31727
Vortex    1.66493
Tornado   1.26366
-----------------
Average   1.46766

More eye-candy


Divisor sum from prime-power factorisation

CJam, 15 bytes * 0.8 = 12

q~.{_@)#(\(/}:*

Try it online. The input order is exponent list first, then list of primes (-3 bytes thanks to @Dennis).

For each prime-exponent pair (p, e) find

(p^(e+1) - 1)/(p - 1)

then find the product of all of these. E.g. for 240 this would be

(1 + 2 + 4 + 8 + 16)(1 + 3)(1 + 5) = 31 * 4 * 6 = 744

Depending on how exponentiation is implemented, this can be better than O(sum of exponents).


Find the submatrix with the smallest mean, 2.0

Mathematica, 77 50 bytes

±x_:=x~Subsets~{3}
Min[Mean/@Mean/@±#&/@±#]&

 is Mathematica's transposition operator (and is rendered as a superscript T in Mathematica).

This answer first defines a helper operator ± which returns all 3-element subsets of a list, and then evaluates to an unnamed function which uses this operator to solve the problem.

This is done by first computing all 3-element subsets of the matrix's rows. Then for each such subset, we transpose it and compute its 3-element subset of rows. This gives us all possible 3x3 submatrices (although they are transposed). We then compute the mean on all of them and find the overall minimum.


Create a programs that counts the 0's in numbers from 0 to a billion

Python (brute force, 80 chars)

def r(n):
    l=[str(i).count('0') for i in xrange(n+1)]
    return l[-1],sum(l)

Just to asure, i got the task right, it evaluates to:

r(10)
>>> (1, 2)
r(1000000000)
>>> (9, 788888899)


J, 17 bytes
<;.1~1,1~:&|2-/\]

Try it online!
Thanks to rak for pointing out that repeated elements should start a new group

2-/\] Take successive deltas
1~:&| Is the absolute value not equal to 1?
1, Append one (since first element always starts a new group)
<;.1~ Group by that mask (ie, start new group every time there's a one)


Jelly, 9 bytes

bṖ’ḅi-µ#Ṫ

A full program which reads a (1-indexed) integer from STDIN and prints the result.

Try it online!

How?

A Gryphon number is a number which is expressible in a base less than itself such that all the digits are ones except the least significant, which is a zero. For example:

\$30=1\times 2^4+1\times 2^3+1\times2^2+1\times2^1+0\times2^0 \rightarrow 30_2 = 11110\$

\$84=1\times 4^3+1\times 4^2+1\times 4^1+0\times 4^0 \rightarrow 84_4 = 1110\$

This program takes n, then starts at v=0 and tests for this property and increments v until it finds n such numbers, then outputs the final one.

To test a base b number it subtracts one from every digit, converts from base v, and then checks if the result is \$-1\$. (Note that b is less than v)

\$30_2 \rightarrow 0\times 30^4+0\times 30^3+0\times30^2+0\times30^1+(-1)\times30^0 = -1\$

\$84_4 \rightarrow 0\times 84^3+0\times 84^2+0\times 84^1+(-1)\times 84^0 = -1\$

bṖ’ḅi-µ#Ṫ - Main Link: no arguments
       #  - set v=0 then count up collecting n=STDIN matches of:
      µ   -  the monadic link -- i.e. f(v):  e.g. v=6
 Ṗ        -    pop (implicit range of v)            [1,2,3,4,5]
b         -    to base (vectorises)                 [[1,1,1,1,1,1],[1,1,0],[2,0],[1,2],[1,1]]
  ’       -    decrement (vectorises)               [[0,0,0,0,0,0],[0,0,-1],[1,-1],[0,1],[0,0]]
   ḅ      -    from base (v) (vectorises)           [0,-1,5,1,0]
     -    -    literal -1                           -1
    i     -    first index of (zero if not found)   2
          - }  e.g. n=11 -> [6,12,14,20,30,39,42,56,62,72,84]
        Ṫ - tail         -> 84
          - implicit print


Python 2, 98 bytes

w,h,a,b=input()
a*='+'
b*='#'
for c in b+a+h*'X'+a+b:print' '.join(min(c,d)for d in b+a+w*'X'+a+b)

Try it online!

Prints a space-separated grid, strictly following the spec. I'm amused that *= is used to convert a and b from numbers to strings.

Python 3 can save some bytes by avoiding ' '.join, maybe more by using f-strings and assignment expressions. Thanks to Jo King for -2 bytes.

Python 3, 93 bytes

def f(w,h,a,b):a*='+';b*='#';[print(*[min(c,d)for d in b+a+w*'X'+a+b])for c in b+a+h*'X'+a+b]

Try it online!


Ruby, 274 252 249 245 214 211 207 204 202 characters (-5 = 197)

How did PHP beat Ruby in char count?! >:O Must find some way to golf more...

Edit: I beat the PHP answer, but the user who wrote it helped me do it! Go upvote him; he deserves it :-P

Another edit: Gah! He passed me again! You are a very worthy opponent, @MathieuRodic; congratulations, I have to let you win ;-)

P=(M=Math)::PI
puts"Data: #{([x=y=a=0]*5).map{a+=o=rand -179..e=180;x+=M.sin(b=a*P/e)*d=rand 500;y+=d*M.cos b;"#{o}:#{d}"}*?,}
Heading: #{M.atan(y/x)/P*-e+90}
Distance: #{M.hypot x,y}
Orientation: #{a}"

Ungolfed code (and slightly much older version):

data = Array.new(5) { [rand(-179..180), rand(0..500)] }
puts "Data: #{data.map{|x|"#{x[0]}:#{x[1]}"}.join ?,}"
x, y, a = [0] * 3
data.each do |o, d|
    a += o
    x += Math.sin(a * Math::PI / 180) * d
    y += Math.cos(a * Math::PI / 180) * d
end
puts "Heading: #{Math.atan(y / x) / Math::PI * -180 + 90}
Distance: #{Math.sqrt(x * x + y * y)}
Orientation: #{a}"

Sample output:

c:\a\ruby>robotgolf
Data: 94:26,175:332,14:390,159:448,-45:20
Heading: 124.52305879195005
Distance: 279.5742334385328
Orientation: 397


Python 3, 223 221 216 214 212 chars
ጸ=0
for  in"ጸꛯ裶":ጸ=ጸ<<20|ord()
while ጸ:print(end=chr(ጸ%128));ጸ>>=7

Converts from base 2²⁰ (1048576) to base 128. Just for fun, I used some of the letters from the encoded string as variable names.

Edit 1: (221) I saved two characters by using base 128 rather than base 127, allowing me to use the bit-shift operation >>=7 rather than the integer division //=127.
Edit 2: (216) Thanks to ovs in the comments for suggesting a way to save a whopping five characters.
Edit 3: (214) Using base 2²⁰ allows us to save another two characters, because we can write the constant as 2**20 in the code, which only takes five characters to write rather than seven.
Edit 4: (212) We can write ጸ<<20|ord() instead of ጸ*2**20+ord().


Define variables using the syntax variable R value rather than I HAS A variable ITZ value.

If you want to set a variable n equal to 1,

n R 1

is only 5 bytes, whereas

I HAS A n ITZ 1

is 15 bytes.


Pyth, 21 bytes

huXf>+H@GhT@GT0G1Qm0Q

Try it online: Single Demonstration or Test Suite

Explanation:

                  m0Q   generate a list of zeros of length len(input)
                        This will simulate the current depths
 u               Qm0Q   reduce G, starting with G=[0,...,0], for H in input():
   f          0             find the first number T >= 0, which satisfies:
    >+H@GhT@GT                  H + G[T+1] > G[T]
  X            G1           increase the depth at this position by one
                            update G with this result
h                       print the first element in this list


Jelly, 7 bytes

6Æṣ=$#Ṫ

Try it online!

How it works

6Æṣ=$#Ṫ  Main link. Argument: n

6        Set the return value to 6.
     #   Execute the link to the left with argument k = 6, 7, 8, ... until n
         values of k result in a truthy value. Yield the array of matches.
    $        Combine the two links to the left into a monadic chain.
 Æṣ              Compute the sum of k's proper divisors.
   =             Compare the result with k.
      Ṫ  Tail; extract the last match.


Vim, 60, 46, 38, 37 bytes/keystrokes

qq/\d
ggDJ@"/[v^]
sv^<esc>l?\V<C-r>"
x@qq4u@q

<esc> and <C-r> are both 1 byte/keystroke. Byte Counter

Test Case 1 (Verbose mode)

Test Case 2 (Verbose mode)

Thanks to Grimy for the ideas that led to a reduction of 22 bytes :)


05AB1E, 4 bytes

Takes input as S, [V,C]

Çè€Ω

Try it online!


Mathematica, 212 152 139 135 bytes
{#~(s=##~SoundNote~41&)~1&/@LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu",{14,18,21}~s~16}~Sound~18.5

Outputs a Sound object that plays Pachelbel's Canon in D when the Play button is pressed. The instrument is MIDI instrument #41 "Violin".
The Audio
Click me!
Explanation
LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu"

Find the letter numbers of each character in the string ("a" -> 1, "b" -> 2, and so on), wrapped with a List. (This string represents Pachelbel's Canon in D)
#~(s=##~SoundNote~41&)~1&/@...

Set s to SoundNote function whose instrument is #41. Set the duration to 1 and map that function to each element in the List (thus making SoundNote primitive objects).
{14,18,21}~s~16

Make the last triad. (The duration 16 is there to make the last note 16 times longer--a whole note is sixteen times a sixteenth note.)
... ~Sound~18.5

Make a Sound object, 18.5 seconds long (because the tempo is 65 bpm [5 measures of 4/4 with tempo 65 bpm = approximately 18.5 seconds]).
126 byte version, non-competing
Sound[{(s=SoundNote)/@LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu",{14,18,21}~s~16},240/13]

Non-competing because the output contains two sixteenth notes instead of an eighth note, and the separation is quite noticeable.


Wolfram - 236

Pretty clunky right now, but at least it works.

f[x_,w_,c_]:=Module[{l=Length,d=Sqrt@CentralMoment[#,2]&,n,a,b,t,r},n=Length@x;a=Normalize/@LowerTriangularize@Array[Boole[Abs[#1-#2]<w]&,{n,n}]^2;{b,t,r}=If[d@x>c,{a,d@#>c&,l@#-1&},{Inverse@a,d@#<c&,-l@#+2&}];r@NestWhileList[b.#&,x,t]]


Fifth Grade Math Problem for the Week: Automated Decryption of Caesar Ciphers

Python 2, 384 319

a=raw_input()
e=lambda v,b:(ord(v)+b-65-32*(v>"``"))%26+65+32*(v>"``")
c=lambda b:''.join(chr(e(f,b))if f.isalpha() else f for f in a)
p=map(c,range(26))
w=map(str.strip,open('w'))
l=[0]*26
for k,i in enumerate(p):
    for j in i.split():
        if j.lower() in w:l[k]+=1
m=[i for i,j in enumerate(l)if j==max(l)][0]
print p[m]

I named my wordlist w, which is a newline-separated list of lowercase words.


Wherre are the adjacent characters in the title? [3, 4]!

Retina, 33 29 23 bytes

Saved 6 bytes thanks to Martin Ender

T`L`:`(.)\1+
:
$.`¶
T`L

Outputs a linefeed-separated list of indices.

Try it online!

Explanation

T`L`:`(.)\1+

Transliterate runs of the same character into colons, to mark positions where there are duplicate characters.

:
$.`¶

Then replace each colon with the length of the text before it, followed by a linefeed.

T`L

Finally, delete any remaining letters.


Javascript, 11 8 bytes, Score: 8 / 5
x=>x^x/2

Simple implementation of gray code. Decoding usally needs a whole loop. Let's see who comes up with the smallest or even without a loop !


Python, 110

l=1
exec"print;n=1;r=0;exec\"c=0;exec'print n,;n*=r-c;c+=1;n/=c;'*r;print n;r+=1;n=n*l/r-n;\"*l;l+=1;"*input()

Original, ungolfed solution:

for layer in range(1, input() + 1):
    print
    n = 1
    for row in range(1, layer + 1):
        for col in range(1, row):
            print n,
            n *= row - col
            n /= col
        print n
        n *= layer - row
        n /= row


8-bit style bouncing ball around a canvas

Bash + Unix utilities, 125 117 bytes

for((x=y=u=v=1;;x+=u,y+=v,u=(x<1||x>=`tput cols`-1)?-u:u,v=(y<1||y>=`tput lines`-1)?-v:v)){
tput cup $y $x
sleep .1
}

Animation of sample run:


Generate a sequence with unique subsequences

What I'm starting with here is a De Bruijn sequence.  Stealing some reference code on the topic, here is my submission:

#!/usr/bin/env python

def de_bruijn(k, n):
    """ De Bruijn sequence for alphabet size k and subsequences of length n. """
    a = [0] * k * n
    sequence = []
    def db(t, p):
        if t > n:
            if n % p == 0:
                for j in range(1, p + 1):
                    sequence.append(a[j])
        else:
            a[t] = a[t - p]
            db(t + 1, p)
            for j in range(a[t - p] + 1, k):
                a[t] = j
                db(t + 1, t)
    db(1, 1)
    return sequence

seq = de_bruijn(9, 9) # cyclic
seq = seq + seq[:8]   # extended to max
print(''.join(map(lambda n: chr(49+n), seq)))

After running for ten minutes, the output is a 387,420,497 digit sequence.  This is 9^9 + 8 digits, as expected.  (Thank you @PeterTaylor for the +8 tip on the cyclic output.)


Bash + GNU utilities, 27
dc -e2o?p|tr -s 0|dc -e2i?p

Input read from STDIN.


Write a program that says how many times it was ran

Somewhat less trivial example than y'old bash, in C:

#include <stdio.h>

int main(int argc,char **argv){
    const char *data="Da best marker in da world 0\0\0\0\0\0\0";
    FILE *f;
    int i;
    char c;
    long int pos;
    printf("%s\n",data+27);
    f=fopen(argv[0],"r+b");
    i=0;
    c=fgetc(f);
    while(!feof(f)){
        if(data[i]==c){
            i++;
            if(i==27)break;
        } else i=0;
        c=fgetc(f);
    }
    if(i!=27)return 1;
    i=0;
    pos=ftell(f);
    c=fgetc(f);
    while(c!='\0'){
        i=10*i+c-'0';
        c=fgetc(f);
    }
    i++; //The increment!
    fseek(f,pos,SEEK_SET);
    fprintf(f,"%d",i);
    fflush(f);
    fclose(f);
    return 0;
}


Python 3, 48 bytes

_='\n_=%r;print(_%%_,end="")';print(_%_,end="")

Try it online!

I mean, it works :p


Powers of 10 literals with scientific notation:

4e6 = 4000000

Powers of 2 literals:

4KB = 4096
4MB = 4194304
4GB = 4294967296

# TB and PB suffixes also exist, but less useful for golf.

Could come in handy.


Husk, 12 11 bytes

↑§foẊ<Ẋ-tİp

Try it online!

-1 byte thanks to H.PWiz.

Explanation

↑§foẊ<Ẋ-tİp  Input is n.
         İp  The infinite list of primes.
      Ẋ-     Take pairwise differences,
   oẊ<       then pairwise comparisons.
        t    Frop the first element from İp
 §f          and filter the rest using the result of oẊ<Ẋ-.
↑            Take first n elements of this list.


Pyth, 29 28 26 24 bytes
Thanks to @Jakube for saving me 3 bytes with .p and L.
Very simple, checks if any elements in list 2 are greater than mean of list 1 and less than mean of list 2, then repeats with list 1 and list 2 switched.
Lcsblbff&>YyhT<YyeTeT.pQ

Prints an a non-empty list for truthy, and [] for falsey.
L                    Define y(b). Pyth has no builtin for mean
 c                   Float div
  sb                 Sum of b
  lb                 Length of b
f        .pQ         Filter all permutations of input
 f     eT            Filter the last element of the filter var
  &                  Logical and
   >Y                Inner filter var greater than
    y                Call the mean function we defined earlier
     hT              First element of outer filter var
   <Y                Inner filter var less than
    y                Mean of
     eT              Last element of outer filternvar

Try it online here.
Test Suite.


Python, 58
f=lambda G,V:V<{0}or sum(f(G,V-{v})*(V-G[v]==V)for v in V)

The input consists of an adjacency dictionary G and a vertex set V.
G = {0:{1,2,3,5}, 1:{2,4}, 2:set(), 3:{2}, 4:set(), 5:{3}, 6:set()}
V = {0,1,2,3,4,5,6}

The code is recursive. The set V stores all nodes that still need visiting. For each potential next node, we check its suitability by seeing if no remaining vertices point to it, with V-G[v]==V checking that V and G[v] are disjoint. For all suitable such vertices, we add the number of topological sorts with it removed. As a base case, the empty set gives 1.


Pyth - 31 bytes
The new key thing cost me too much.
ss.emr!FZk@@QsedthdfndeTrb8cz\#

Test Suite.


Charcoal, 17 bytes

ＧＨ<↗↘>↖↙ＬθθＧＨ<Ｌθθ

Try it online! Link is to verbose version of code. Explanation:

ＧＨ

Draw along a path.

<↗↘>↖↙

Draw in the directions ↘↗↗↘↙↖↖↙ (the < and > are shorthands for those two pairs, but the other pairs don't have shorthands.)

Ｌθ

Each path segment has the same length, including the ends, of the length of the input.

θ

Use the input as the text to be written along the path.

ＧＨ<Ｌθθ

Print the first two parts of the path again so that the middle character is correct.


Python, 244 238 233 232

e='abhioptuwycdjmnsqxzfgvklebr'
for w in raw_input().split():
 for i in 0,3,6,9:print' '.join(''.join((' '+'\|/-O-/|\ '[j])[`j`in'4'+'6736031025071568328578162735'[e.find(c):][:2]]for j in range(i,9)[:3])for c in w if c.lower()in e)

This uses a favorite trick of mine: single-track encoding.  I've labeled the semaphore bits (sbits)

\|/     012
- -  -> 3 5
/|\     678

to obtain the following chart of which sbits occur for which letter:

0: ciotuy
1: djkptv
2: elquwx
3: bhopqrs
5: fjmrwyz
6: ahiklmn
7: abcdefg
8: gnsvxz

each letter occurs exactly twice in the chart, since the signalman has two arms.  Then, I view this as a graph on the letters a-z, with edges between letters sharing sbits, with the edges labeled according to the shared sbit.  Ideally, I'd find a Hamilton path through this graph, such that subsequent edges don't have the same label.  No such paths exist... so you'll note that the variable e contains the letter b twice.

With my nearly-Hamilton path e, I construct an array d of sbit labels used in the traversal of e.  Then, to figure out where to put her arms, the signalman need only find the desired letter in the following handy chart

abhioptuwycdjmnsqxzfgvklebr
6736031025071568328578162735

whence her arms go in the position directly below, and below&right of the letter.


Add without addition (or any of the 4 basic arithmetic operators)

Javascript (25)

while(y)x^=y,y=(y&x^y)<<1

This adds two variables x and y, using only bitwise operations, and stores the result in x.

This works with negative numbers, too.


05AB1E, 4 bytes
ÙœåP

Only takes input \$J\$ (I don't need \$n\$ with this approach).
Try it online or verify all test cases.
Explanation:

Ù     # Uniquify the digits of (implicit) input-integer
 œ    # Get all permutations of this uniquified integer
  å   # Check for each if it's a substring of the (implicit) input-integer
   P  # And check if this is truthy for all of them
      # (after which the result is output implicitly)


Let's play some Reaper - Closed for Submissions

Sniper

A bot fueled by spite. Keeps track of opponent's cooldowns and scores. Attempts to keep others from winning. Pretty much never actually wins, but makes the game frustrating to play for others.

EDIT:

If reaping would cause it to win, reap.
If no one is >= 70% of the winning score:

If everyone else is on their cooldown, wait until the last possible moment to reap.
If anyone else would win by reaping the current value, and they are active now or would be active next turn, reap.
If at least half of the other users are on their cooldown, attempt to reap. This makes it difficult to target specific opponents, and so was removed.
Otherwise, reap 25% of the time (essentially to guarantee that this bot does reap SOMETIMES, just in case something weird happens, like everyone is waiting several turns).

If someone IS >= 70% of the winning score:

If Sniper can win a tiebreaker, and next round would be above the average Reap value for the highest scoring opponent, reap
If highest scoring opponent will leave their cooldown next turn, reap.

def Sniper(self, Reap, prevReap):
    # initialize opponents array
    if not hasattr(self.obj, "opponents"):
        self.obj.opponents = {}

    # initialize previous Reap value
    if not hasattr(self.obj, "lastReap"):
        self.obj.lastReap = 0

    # increment all stored wait times to see who will be "active" this turn
    for opponent in self.obj.opponents:
        self.obj.opponents[opponent]["time"] += 1

    # update opponents array
    for opponent in prevReap:
        # don't track yourself, since you're not an opponent
        if opponent != "Sniper":
            # initialize opponent
            if opponent not in self.obj.opponents:
                self.obj.opponents[opponent] = {"time": 0, "points": 0, "num_reaps": 0, "avg": 0}
            self.obj.opponents[opponent]["time"] = 0
            self.obj.opponents[opponent]["points"] += self.obj.lastReap
            self.obj.opponents[opponent]["num_reaps"] += 1
            self.obj.opponents[opponent]["avg"] = self.obj.opponents[opponent]["points"] / self.obj.opponents[opponent]["num_reaps"]

    # done "assigning" points for last round, update lastReap
    self.obj.lastReap = Reap

    # get current 1st place(s) (excluding yourself)
    winner = "" if len(self.obj.opponents) == 0 else max(self.obj.opponents, key=lambda opponent:self.obj.opponents[opponent]["points"])

    # you are ready now
    if self.time >= self.waittime:
        # current Reap is sufficient for you to win
        if self.points + Reap >= self.win:
            return 1

        if (
                # a 1st place exists
                winner != ''
                # if current 1st place is close to winning
                and self.obj.opponents[winner]["points"] / self.win >= .7
        ):
            if (
                    # next round's Reap value will be above opponent's average Reap
                    (Reap * self.mult >= self.obj.opponents[winner]["avg"])
                    # we have been waiting at least as long as our opponent (tiebreaker)
                    and self.time >= self.obj.opponents[winner]["time"]
            ):
                return 1

                # current 1st place opponent will be active next round
            if self.obj.opponents[winner]["time"] + 1 >= self.waittime:
                return 1

        else:
            if (
                    # everyone is waiting for their cooldown
                    all(values["time"] < self.waittime for key, values in self.obj.opponents.items())
                    # and we're tracking ALL opponents
                    and len(self.obj.opponents) == self.lenBots - 1
                    # at least one person will be ready next turn
                    and any(values["time"] + 1 >= self.waittime for key, values in self.obj.opponents.items())
            ):
                return 1

            if (
                    # opponent will be active next round
                    any( (values["time"] + 1 >= self.waittime)
                         # current Reap value would allow opponent to win
                         and (values["points"] + Reap >= self.win) for key, values in self.obj.opponents.items())
            ):
                return 1

            if (
                    # a 1st place exists
                    winner != ''
                    # current 1st place opponent will be active next round
                    and (self.obj.opponents[winner]["time"] + 1 >= self.waittime)
                    # next round's Reap value will be above their average Reap
                    and (Reap * self.mult >= self.obj.opponents[winner]["avg"])

            ):
                return 1

            # # at least half of opponents are waiting for their cooldown
            # if sum(values["time"] < self.waittime for key, values in self.obj.opponents.items()) >= (self.lenBots - 1) / 2:
            #     return 1

            # 25% of the time
            if self.getRandom() <= .25:
                return 1

    # default return: do not snipe
    return 0

Bored

Just for fun, this bot was brought along by a friend and doesn't actually want to be here. They roll a d16 until they get a number in 1-9, then they attempt to reap anytime a number contains the chosen digit. (Going to look for a d10 would disrupt the game, which is rude, and 0 is just too easy!)

def Bored(self, Reap, prevReap):
    # if this is the first round, determine your fav number
    if not hasattr(self.obj, "fav_int"):
        r = 0

        while r == 0:
            # 4 bits are required to code 1-9 (0b1001)
            for i in range(0, 4):
                # flip a coin. Puts a 1 in this bit place 50% of the time
                if self.getRandom() >= .50:
                    r += 2**i
            # if your random bit assigning has produced a number outside the range 1-9, try again
            if not (0 < r < 10):
                r = 0

        self.obj.fav_int = r

    # you are ready now
    if self.time >= self.waittime:
        # current Reap is sufficient for you to win
        if self.points + Reap >= self.win:
            return 1
        # do you like this value?
        if str(self.obj.fav_int) in str(Reap):
            return 1
        # do you like your wait time?
        if self.time % int(self.obj.fav_int) == 0:
            return 1

    # default return: do not reap
    return 0


Python 3,  32  31 bytes

exit('GBoaodd'['G'<input()::2])

Try it online!

How?

Tests if input is 'Good' by comparing 'G'<input().

Uses the fact that in Python False==0 and True==1 to use the result as the start index of a slice of 'GBoaodd' using an undefined stop and a step of 2 with 'GBoaodd'[start:stop:step].

Prints to STDERR (saving a byte with exit in place of print).


Python, FOUR HUNDRED bits
i=0
while 1:print" "*(i%8>3 and-i%4 or i%4),0;i+=1
At first I wanted to make a sine scroller, but there was no place for the import. Now you get a bugged triangle wave. ~~~party~~~


JavaScript (ES6), 50 35 bytes

f=(n,s="1",t=0)=>s[n-1]||f(n,s+t,s)
<input type=number min=1 oninput=o.textContent=this.value&amp;&amp;f(this.value)><pre id=o>

Outputs 1 for lower and 0 for upper. Explanation: Partial lists of boolean values can be constructed using a Fibonacci-like identity: given two lists, starting with 1 and 10, each subsequent list is the concatenation of the previous two, resulting in 101, 10110, 10110101 etc. In this case it's slightly golfier to have a fake 0th entry of 0 and use that to construct the second element of the list.