Python 3, 80 79 59 57 bytes

-1 byte thanks to Arnauld
-20 bytes thanks to ArBo
-2 bytes thanks to negative seven

lambda x:[-i-~x*60for i in(x<2)*b'a[YUSOLI'+b'MJGDCA@>=']

Try it online!


MacOS terminal, 84 bytes

osascript -e 'tell app "System Events" to keystroke "ac" using command down'
pbpaste

Simple select-all then copy-and-paste.


Ruby with Shoes, 110

Shoes.app{button('Close'){exit}
p=para
t=Time.now
animate{u=(t-Time.now).to_i+10
exit if u<0
p.text=' '*u+?<}}

Makes a little arrow that pushes a "Close" button. (Pushing the close button manually also closes the window.)


Swap out some periodic and non-periodic parts

Python 2, 292 bytes
def x(n,d):
 L=len;s=cmp(n*d,0);n*=s;b=p=`n/d`;a={};n%=d
 while not n in a:
  a[n]=p;q=n/d;n=n%d
  if q==0:n*=10;p+=' '
  p=p[:-1]+`q`
 p=p[L(a[n]):];a=a[n][L(b):]
 if n==0:p=''
 n=int(b+p+a);d=10**L(p+a)
 if a!='':n-=int(b+p);d-=10**L(p)
 import fractions as f;g=f.gcd(n,d);return(n/g*s,d/g)

Ungolfed version, works in both python 2&3. Also prints decimal representation.
def x(n,d):
# sign handling
 s=n*d>0-n*d<0
 n*=s
# b, a, p: BEFORE decimal, AFTER decimal, PERIODIC part
 b=p=str(n//d)
 a={}
 n%=d
# long division
 while not n in a:
  a[n]=p
  q=n//d
  n=n%d
  if q==0:
   n*=10
   p+=' '
  p=p[:-1]+str(q)
# a/p still contain b/ba as prefixes, remove them
 p=p[len(a[n]):]
 a=a[n][len(b):]
 if n==0: p=''
# print decimal representation
 print("(" + b + ").(" + a + ")(" + p + ")")
# reassemble fraction (with a and p exchanged)
 n=int(b+p+a)
 d=10**len(p+a)
 if a!='':
  n-=int(b+p)
  d-=10**len(p)
# reduce output
 from fractions import gcd
 g=gcd(n,d)
 return(n//g*s,d//g)


Pyth, 57 bytes

j-f:T"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$"0{.P*Q+jkUT".-"Q\-

Try it on the online interpreter.

Way too long, and with horrific runtime (takes several seconds for N=4, running with N=5 is not recommended).

            .P           Q    all permutations of length (input) of
                 jkUT         ... the string "0123456789"
                +    ".-"     ... plus the chars "." and "-"
              *Q              ... whole thing times the input -- pyth has
                              no repeated_permutation, so this is necessary
           {                  uniquify
  f                           filter by
   :T"..."0                   does it match the really long regex?
 -                        \-  get rid of "-"
j                             join on newline

Regex explanation:

^0$|            "0", or...
^
 -?             optional negative sign
 ([1-9]\d*)?    optional part-before-decimal
 (\.\d*[1-9])?  optional part-after-decimal
$


Wolfram Language (Mathematica), 20 bytes

Root[xx^5+x+#,1]&

Try it online!

Still a built-in, but at least it isn't UltraRadical.

(the character  is displayed like |-> in Mathematica, similar to => in JS)


Impress Donald Knuth by counting polyominoes on the hyperbolic plane

GAP and its kbmag package, 711 682 658 bytes

Note that the kbmag package consists not only of GAP code, it contains C programs that have to be compiled (see the package's README file).

LoadPackage("kbmag");I:=function(p,q,n)local F,H,R,r,s,x,c;F:=FreeGroup(2);s:=F.1;r:=F.2;R:=KBMAGRewritingSystem(F/[s^2,r^p,(s*r)^q]);AutomaticStructure(R);H:=SubgroupOfKBMAGRewritingSystem(R,[r]);AutomaticStructureOnCosets(R,H);x:=w->ReducedCosetRepresentative(R,H,w);c:=function(n,U,S,P)local N,Q,Z;if n=0 then Z:=Set(U,t->Set(U,p->(p/t)));return 1/Size(SetX(Union(Z,Set(Z,Q->Set(Q,q->(MappedWord(q,[s,r],[s,r^-1]))))),[1..p],{Q,i}->Set(Q,q->x(q*r^i))));fi;if P=[]then return 0;fi;N:=P[1];Q:=P{[2..Size(P)]};Z:=Filtered(Set([1..p],i->x(s*r^i*N)),w->not w in S);return c(n,U,S,Q)+c(n-1,Union(U,[N]),Union(S,Z),Union(Q,Z));end;return c(n,[],[r/r],[r/r]);end;

This is the result of removing indentation and newlines from this version, and some inlining:

LoadPackage("kbmag");
I:=function(p,q,n)
  local F,G,H,R,r,s,x,c;
  F:=FreeGroup(2);
  s:=F.1;r:=F.2;
  G:=F/[s^2,r^p,(s*r)^q];
  R:=KBMAGRewritingSystem(G);
  AutomaticStructure(R);
  H:=SubgroupOfKBMAGRewritingSystem(R,[r]);
  AutomaticStructureOnCosets(R,H);
  x:=w->ReducedCosetRepresentative(R,H,w);
  c:=function(n,U,S,P)
    local N,Q,Z;
    if n=0 then
      Z:=Set(U,t->Set(U,p->(p/t)));
      Z:=Union(Z,Set(Z,Q->Set(Q,q->(MappedWord(q,[s,r],[s,r^-1])))));
      Z:=SetX(Z,[1..p],{Q,i}->Set(Q,q->x(q*r^i)));
      return 1/Size(Z);
    fi;
    if P=[]then return 0;fi;
    N:=P[1];Q:=P{[2..Size(P)]};
    Z:=Filtered(Set([1..p],i->x(s*r^i*N)),w->not w in S);
    return c(n,U,S,Q)+c(n-1,Union(U,[N]),Union(S,Z),Union(Q,Z));
  end;
  return c(n,[],[r/r],[r/r]);
end;

If the line containing {Q,i}-> doesn't work, your GAP is too old. You can then replace that line with:

Z:=SetX(Z,[1..p],function(Q,i)return Set(Q,q->x(q*r^i));end);

Several of the Set operations could be slightly faster List operations (the improved version at least uses that it is a set for even more golfing and a little speed compensation), but that would cost one byte each time.

And yes, Knuth's and your result is confirmed:

gap> Read("i.gap");
─────────────────────────────────────────────────────────────────────────────
Loading  kbmag 1.5.9 (Knuth-Bendix on Monoids and Automatic Groups)
by Derek Holt (https://homepages.warwick.ac.uk/staff/D.F.Holt/).
Homepage: https://gap-packages.github.io/kbmag
─────────────────────────────────────────────────────────────────────────────
gap> I(4,5,5);
16
gap> I(4,5,6);
55
gap> I(4,5,7);
224
gap> I(4,5,8);
978
gap> I(4,5,9);
4507
gap> I(4,5,10);
21430

The \$n=7\$ computation already takes several minutes. My computations also agree with the other results in the table.


Batch, 256 bytes

@set i=echo
@%i%off
set u=
for /l %%j in (2,2,%1)do call set i=%%i%%
set/af=%1^&1
if %f%==1 %i% __&%i%/,,\o&set u=__
for /l %%j in (2,2,%1)do call:l
exit/b
:l
set i=%i:~0,-2%
%i%  _%u%_
%i%o/,%u%,\
%i% __%u%__
%i%/,_%u%_,\o
set u=__%u%__

Note that line 1 has a trailing space and line 4 has two trailing spaces. i therefore contains an echo command with the appropriate amount of indentation for each turtle. Meanwhile u contains the number of underscores in alternate turtles. A leading odd turtle is special-cased and then the rest of the turtles are output in pairs.


Implement my method of adding numbers mentally


JavaScript (ES7), 113 109 bytes

s=>(p=s.split` `)[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},0]/(10**(m[p[3][0]]-m[p[1][0]]))

Edit: Apparently we can use µ(U+00B5 MICRO SIGN) for the micro sign now, so replacing with that saves a byte.

For ES6 compatibility (10**(m[p[3][0]]-m[p[1][0]])) can be replaced with Math.pow(10,m[p[3][0]]-m[p[1][0]]) for 114 bytes.

Explanation

s=>                                  // s = input string
  (p=s.split` `)                     // p = input parts

    // m = dictionary of SI prefix digit powers of 10
    //     the exact values don't matter as long as they are relative to each other
    [m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},

    0]                               // get the number
      /(10**(m[p[3][0]]-m[p[1][0]])) // get the factor to divide by from the difference
                                     //     between the SI prefix powers of 10

Test

This test uses Math.pow instead of ** so that common browsers can test it.

<input type="text" id="input" value="2000 MB to GB" /><button onclick="result.innerHTML=(

  s=>(p=s.split` `)[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},0]/Math.pow(10,m[p[3][0]]-m[p[1][0]])

)(input.value)">Go</button>


Python 2, 102 97 bytes

thanks to @JonathanFrech for -5 bytes

w=input();l=range(len(w)+1)
print{w[a:b]for a in l for b in l if b-a>1<set(w[a:b])<=set('aeiou')}

Try it online!

lowercase I/O


Compute the number of ways how you can express a number as a sum

Haskell, 170 148

An efficient Haskell version using a generating function with Memoization. Solve instantaneously the problem for n = 1000. No precision issues even with large numbers:

time ./partitions 10000
36167251325636293988820471890953695495016030339315650422081868605887952568754066420592310556052906916435144
./partitions 10000  17.02s user 0.00s system 100% cpu 17.021 total

The code

generalizedPentagonal = map pentagonal $ [1..] >>= \i->[i,-i]
    where pentagonal n = (3*n^2-n)`quot`2

partitions = (map partitions' [0..] !!)
    where partitions' 0 = 1
          partitions' n = sum . alternate . map partitions . takeWhile (>=0) . map (n-) $ generalizedPentagonal
          alternate = zipWith (*) (concat . repeat $ [1,1,-1,-1])

Code-golf version

p=(map a[0..]!!)where a 0=1;a n=sum.zipWith(*)(concat.repeat$[1,1,-1,-1]).map p.takeWhile(>=0).map(n-).map(\n->(3*n^2-n)`quot`2)$[1..]>>= \i->[i,-i]

Efficiency improvements

Replace the memoization with an Array instead of a list:

import Data.Array
[...]
bnd = (0,10000)
partitions = (array bnd [(i, partitions' i) | i <- range bnd] !)
[...]

Time for partitions 10000 drop from 17s to 960ms

Results

Interpreted:

partitions 1000
24061467864032622473692149727991
(0.11 secs, 21833064 bytes)

Compiled:

time ./partitions 1000
24061467864032622473692149727991
./partitions 1000  0.08s user 0.00s system 99% cpu 0.084 total

Useful links

The generating function
Generalized pentagonal numbers


Is there a way of shortening fat-arrow functions?

Use Recursion

I've found that recursion is (almost) always shorter than eval+for. The general way to convert from for to eval is:

for(a=n;b;c);d
(f=a=>b?f(c):d)(n)

So let's see your example:

b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}

We can first simplify it to:

for(m=b,a=1;~-m;--m,a*=m*m)a%b;

What did we do here? Well we simply moved everything inside the for statement, this helps us reduce the amount of semicolons which is not directly better but almost always leads to some golf.

Let's put this in eval and compare it to the recursion version:

b=>{m=b;for(a=1;~-m;)--m,a*=m*m;return a%b}
b=>eval('for(m=b,a=1;~-m;--m,a*=m*m)a%b')
b=>(f=a=>~-m?(--m,f(a*=m*m)):a%b)(1,m=b)

The first part of the for loop (a=n), we can start that off by passing those variables in as arguments. The condition is simply: b?(c,f(a)):d where d is the return value. Usually c just modifies a so it can be merged into it. So we can golf it even more using what I've mentioned:

b=>(f=a=>~-m?(--m,f(a*=m*m)):a%b)(1,m=b)
b=>(f=a=>~-m?f(a*=--m*m):a%b)(1,m=b) // --m moved into a*=
b=>(f=a=>--m?f(a*=m*m):a%b)(1,m=b) // --m moved to condition

That said, as noted by @Niel is simplifying your algorithm. An algorithm golfy in one language may not be golfy in another so make sure to try different algoriths and compare them.


Sage – 102 104/115

Why use number theory, when there is brute force?

v=lambda n:[j for j in range(n+1)if all(sum(e^(i*2*I*pi/n)for i in c)for c in Combinations(range(n),j))]

For a given number of vials, this goes over all ways to position the vials and calculates their center of mass by using complex arithmetics. If the center of mass is zero for none of these ways, the number is returned.

Unfortunately, this does not work in certain cases (10,14), because Sage fails to simplify some expressions to zero (which may be related to this bug). One could regard this as a flaw of the interpreter and not the program and still say that the algorithm and program are fine.

The following 113-character alternative relies on floats instead of symbols and does not suffer from these problems:

v=lambda n:[j for j in range(n+1)if all(abs(sum(exp(i*2j*pi/n)for i in c))>1e-9for c in Combinations(range(n),j))]

Test output of the 113-character version (for n in range(14): print n,v(n)):

0 []
1 [1]
2 [1]
3 [1, 2]
4 [1, 3]
5 [1, 2, 3, 4]
6 [1, 5]
7 [1, 2, 3, 4, 5, 6]
8 [1, 3, 5, 7]
9 [1, 2, 4, 5, 7, 8]
10 [1, 3, 7, 9]
11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12 [1, 11]
13 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
14 [1, 3, 5, 9, 11, 13]

I did not want to wait the runtime for higher n.

This originates from the following Python solution. Exact arithmetics and not having to import some modules is quite something.

Python – 173 154 156

from itertools import*
from cmath import*
v=lambda n:[j for j in range(n+1)if all(abs(sum(exp(i*2j*pi/n)for i in c))>1e-9for c in combinations(range(n),j))]

Test output of this variant (for n in range(24): print n,v(n)):

0 []
1 [1]
2 [1]
3 [1, 2]
4 [1, 3]
5 [1, 2, 3, 4]
6 [1, 5]
7 [1, 2, 3, 4, 5, 6]
8 [1, 3, 5, 7]
9 [1, 2, 4, 5, 7, 8]
10 [1, 3, 7, 9]
11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12 [1, 11]
13 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
14 [1, 3, 5, 9, 11, 13]
15 [1, 2, 4, 7, 8, 11, 13, 14]
16 [1, 3, 5, 7, 9, 11, 13, 15]
17 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
18 [1, 17]
19 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
20 [1, 3, 17, 19]
21 [1, 2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20]
22 [1, 3, 5, 7, 9, 13, 15, 17, 19, 21]
23 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
24 [1, 23]

I did not want to wait the runtime for higher n.


Python 2, 42 bytes

lambda m:sum(r[-1]-r[0]for r in m+zip(*m))

An unnamed function taking a list of lists, m, and returning the resulting number.

Try it online!

How?

The sum of the deltas of a list is the last element minus the first, everything else just cancels:
(r[n]-r[n-1])+(r[n-1]-r[n-2])+...+(r[2]-r[1]) = r[n]-r[1]

The zip(*m) uses unpacking (*) of m to pass the rows of m as separate arguments to zip (interleave) and hence transposes the matrix. In python 2 this yields a list (of tuples, but that's fine), so we can add  (concatenate) it to (with) m, step through all our rows and columns, r, perform the above trick for each and just add up the results (sum(...)).


Python 3, 265 bytes

def f(x,n):
 for e in g(x,x-(x>7)):
  try:
   if eval(e)==n:return e
  except:1
g=lambda x,d:{str(x)*-~i for i in range(d)}|{s%(a,b)for a in g(x,d-1)for b in g(x,d-a.count(str(x)))for s in'%s**%s (%s/%s) (%s+%s) (%s-%s) %s*%s %s/%s'.split()['**'in a+b:]}if d else{}

Try it online!

Works for all numbers in the reference linked by Engineer Toast.

Runs up to x=8 on tio, x=9 takes a couple of minutes on my machine.

The function g returns a set of all combinations with at most x number of x's. f then loops through them and returns the first which evaluates to the number n.

The number of possible values i found for each x are:

x  possible numbers
------
2  5
3  17
4  35
5  56
6  83
7  101
8  101
9  101

All the numbers above can be generated from (a+b), (a-b), (a+b), a*b, a/b, (a/b), and a^b.
a+b and a-b do not give more numbers.

a^b is also only used once, as otherwise huge numbers are created (this is also verified in the reference document above)

An alternate version which short-circuits as soon as it finds a solution (not as golfed):

This is much faster as for x=7..9 all numbers can be created.

Python 3, 338 289 bytes

def f(x,n,d=-1):
 d=[d,x][d<0];X=str(x);r=set()
 for E in{X*-~i for i in range(d)}|{s%(a,b)for a in[0]*d and f(x,n,d-1)for b in f(x,n,d-a.count(X))for s in'%s**%s (%s/%s) (%s+%s) (%s-%s) %s*%s %s/%s'.split()['**'in a+b:]}:
  try:e=eval(E)
  except:e=-1
  if e==n:exit(E)
  r|={E}
 return r

Try it online!


Don't repeat yourself in Rock-Paper-Scissors

Ruby, 39 bytes

->n{(?P*n..?S*n).grep_v /[^RPS]|(.+)\1/}

This hilariously inefficient function generates all strings of length N that lie alphabetically between N Ps and N Ss, then filters out the vast majority that contain non-RPS characters. The actual squarefree check just uses a Regexp backreference: (.+)\1.

More idiomatic 65 bytes that finish in a reasonable amount of time for N=10:

->n{%w[R P S].repeated_permutation(n).map(&:join).grep_v /(.+)\1/}

Edit: Saved a byte thanks to G B.


Ruby, 92; Ostrich 0.7.0, 38

f=->m,n{((1..m-1).map{|x|[x,1]}+(1..n-1).map{|x|[1.0*x*m/n,0]}).sort_by(&:first).map &:last}

:n;:m1-,{)o2W}%n1-,{)m n/*0pW}%+_H$_T%

Output for both of them uses 1's and 0's (ex. 101101).

Here's an explanation of the Ostrich one:

:n;:m    store n and m as variables, keep m on the stack
1-,      from ex. 5, generate [0 1 2 3]
{...}%   map...
  )        increment, now 5 -> [1 2 3 4]
  o        push 1 (the digit 1 is special-cased as `o')
  2W       wrap the top two stack elements into an array
           we now have [[1 1] [2 1] [3 1] [4 1]]
n1-,     doing the same thing with n
{...}%   map...
  )        increment, now 3 -> [1 2]
  m n/*    multiply by slope to get the x-value for a certain y-value
  0        push 0
  pW       wrap the top two stack elements (2 is special-cased as `p')
+        concatenate the two arrays
_H$      sort-by first element (head)
_T%      map to last element (tail)

And an explanation of how the whole thing works, using the Ruby code as a guide:

f = ->m,n {
    # general outline:
    # 1. collect a list of the x-coordinates of all the crossings
    # 2. sort this list by x-coordinate
    # 3. transform each coordinate into a 1 or 0 (V or H)
    # observation: there are (m-1) vertical crossings, and (n-1) horizontal
    #   crossings. the vertical ones lie on integer x-values, and the
    #   horizontal on integer y-values
    # collect array (1)
    (
        # horizontal
        (1..m-1).map{|x| [x, 1] } +
        # vertical
        (1..n-1).map{|x| [1.0 * x * m/n, 0] }  # multiply by slope to turn
                                               # y-value into x-value
    )
    .sort_by(&:first)  # sort by x-coordinate (2)
    .map &:last        # transform into 1's and 0's (3)
}


Is it a valid consonant cluster in Lojban?

Pyth, 53 48 47 bytes
!}z+"mz"s.pMs[+VGGc"xcxkcsjz"2*"ptkfcsx""bdgvjz

This generates a list of all invalid pairs based on the rules above, then checks if the input is one of them.
! }                        A not in B
    z                      input
    +
      "mz"                  "mz"
      s                    flattened
        .pM                permutations of each:
            s [               flatten the three-element array:
                +V              Alphabet vectorized concat with itself.
                   G            That is, duplicate letters
                   G
                c"xcxkcsjz"2     That string chopped every 2
                *               outer product of
                  "ptkfcsx"      voiced letters
                  "bdgvjz        and unvoiced letters

Try it here.


Sum of Fibonacci numbers -- speed contest

Python, 7 chars

It turns out that the period of G(i)=F(i) mod 10^9 is 1.5e9 exactly.  So when adding them up, we can group them into groups of size 1.5e9, each of which will have the same sum (mod 10^9).  Turns out, that sum is 0.  So if we take N to be any multiple of 1.5e9, the sum of the first N fibonacci numbers is 0.  So:

print 0

will, given an argument i, print the sum of the first i * 1.5e9 Fibonacci numbers.  Super fast and works for an arbitrarily large i.


Jelly, 34 bytes

Ṿ€“1“ ”ys³G
>®i©1ḍoṛ®¦
²R;1©ÇÐĿÑ€Y

Try it online!

How it works

²R;1©ÇÐĿÑ€Y  Main link. Argument: n (integer)

²            Yield n².
 R           Range; yield [1, ..., n²].
   1©        Yield 1 and copy it to the register.
  ;          Append 1 to the range.
             This is the initial state. Let's call it S.
     ÇÐĿ     Call the second helper link until the results are no longer unique.
             This returns all unique results as an array.
        Ṅ€   Call the first helper link on each result.
          Y  Join, separating by linefeeds.

>®i©1ḍoṛ®¦   Second helper link. Argument: S (state)

>®           Compare all integers in S with the value in the register.
  i 1        Find the first index of 1 (i.e., the first number that is greater
             than the register.
   ©         Copy the index to the register. Let's call the index p.
     ḍ       Test all numbers in S for divisibility by p. This yield 1 for
             multiples of p, 0 otherwise.
      o      Logical OR; replace 0's with the corresponding values of S.
       ṛ®¦   Replace the 0 at index p with the corresponding element of S (p).
             For the purposes of the explanation, S is now the updated state.

Ṿ€“1“ ”ys³G  First helper link. Argument: A (array)

Ṿ€           Uneval each; convert all integers in A into strings.
  “1“ ”y     Replace each string "1" with the string " ".
        s³   Split into chunks of length n (command-line argument).
          G  Grid; separate row items by spaces (left-padding since the row items
             are strings), the rows themselves by linefeeds.


05AB1E, 37 35 33 32 31 29 28 bytes
εk3÷üÊ}DO2@¹ü«εüQO}²{¹˜êQ)˜P

-2 bytes by taking inspiration of the ê approach @Emigna used in his 05AB1E answer.
-3 bytes thanks to @Grimy.
Takes a list of list of characters for the words as first input, and the flattened list of twelve letters as second input.
Try it online or verify all test cases.
Explanation:

ε         # Map over the character-lists `y` of the (implicit) input-list of words:
 k        #  Get the index of each character in the (implicit) input-list of letters
  3÷      #  Integer-divide each index by 3
    üÊ    #  Check for each overlapping pair of integers that they are NOT equal
}D        # After the map: duplicate the resulting list
  O       #  Get the sum of each inner list of truthy/falsey values
   2@     #  And check that each is larger than 2 (so all words had at least 3 letters)
¹ü        # Get all overlapping pairs of character-lists from the input-list of words:
  «       #  And merge them together to a flattened list of characters
   ε   }  # Map over those merged character lists:
    üQ    #  Check for each overlapping pair of characters in the list that they are equal
      O   #  And take the sum of this (where we'd expect 1/truthy if the last character of
          #  the first word and the first character of the second word are equal)
          #  (NOTE: This could fail for inputs with identical adjacent characters,
          #   but the earlier check of `εk3÷üÊ}` already covers for this)
²{        # Push the input-list of letters, and sort them
  ¹˜      # Push the input-list of list of word-letters, flattened,
    ê     # and then uniquified and sorted as well
     Q    # And check if both lists of characters are the same
)˜        # Then wrap everything on the stack into a list, and deep flatten it
  P       # And check if everything is truthy by taking the product
          # (which is output implicitly as result)


Create the slowest growing function you can in under 100 bytes

Brachylog, 100 bytes

llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

Try it online!

This is probably nowhere near the slowness of some other fancy answers, but I couldn't believe noone had tried this simple and beautiful approach.

Simply, we compute the length of the input number, then the length of this result, then the length of this other result... 100 times in total.

This grows as fast as log(log(log...log(x), with 100 base-10 logs.

If you input your number as a string, this will run extremely fast on any input you could try, but don't expect to ever see a result higher than 1 :D


Ruby, 221 bytes
->w,h{s=' '
a=(s*9+?_*5)*(w/2)+$/
(2-h*2).upto(h*2+3){|y|c=y<4-h*2
a+=[b=c ?s:?\\,s+b,s,''][y%4]
(0-w/2).upto(w/2){|x|a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",s*7,?_*5,"/     \\"][(y+x*2+w)%4]%[x,y/4]}
a+='//  '[c ?3:y%4]+$/}
a}

Ungolfed in test program
f=->w,h{
  s=' '                                #set s to space for golfing reasons
  a=(s*9+?_*5)*(w/2)+$/                #start building the output with a row of just _ and space

  (2-h*2).upto(h*2+3){|y|              #iterate 4 times for each row of hexagons, plus an extra 2 at the end to finish last row
    c=y<4-h*2                          #condition for first two rows
    a+=[b=c ?s:?\\,s+b,s,''][y%4]      #string to be output before main set of hexagons (spaces for top row, \ for certain other rows

    (0-w/2).upto(w/2){|x|              #iterate through hexagons on each row, 4 lines for each with the following printf type string
      a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",#line 1:contains ends / \ and numbers
         s*7,                          #line 2 padding spaces
         ?_*5,                         #line 3 padding ___
         "/     \\"][(y+x*2+w)%4]%     #line 0 top of hexagon / \; formula to select string to be printed
           [x,y/4]                     #numbers to be printed (if format for current line does not require them they are ignored)
    }

    a+='//  '[c ?3:y%4]+$/             #ending alternates between / and space; / are suppressed for first two rows
  }
  a
}

puts g[7,3]
puts g[5,5]

Output
As I was finishing debugging, I noticed an ambiguity in the spec. Where w+1 is divisible by 4, the first and last x coordinates are odd, and there is no ambiguity. But where w-1 is divisible by 4 the first and last x coordinates are even. I assumed that the first and last columns should be offset below the next ones. But then I read the previous question and noted in that case it was the odd columns that should be offset below the even ones (note for w-1 divisible by 4 it is not possible to do both.)
That distinction was not made in this question, however. I will leave this up to OP's judgement and rework if necessary, though I'd prefer not to have to.
         _____         _____         _____
        /     \       /     \       /     \
  _____/ -2,-1 \_____/  0,-1 \_____/  2,-1 \_____
 /     \       /     \       /     \       /     \
/ -3,-1 \_____/ -1,-1 \_____/  1,-1 \_____/  3,-1 \
\       /     \       /     \       /     \       /
 \_____/ -2,0  \_____/  0,0  \_____/  2,0  \_____/
 /     \       /     \       /     \       /     \
/ -3,0  \_____/ -1,0  \_____/  1,0  \_____/  3,0  \
\       /     \       /     \       /     \       /
 \_____/ -2,1  \_____/  0,1  \_____/  2,1  \_____/
 /     \       /     \       /     \       /     \
/ -3,1  \_____/ -1,1  \_____/  1,1  \_____/  3,1  \
\       /     \       /     \       /     \       /
 \_____/       \_____/       \_____/       \_____/
         _____         _____
        /     \       /     \
  _____/ -1,-2 \_____/  1,-2 \_____
 /     \       /     \       /     \
/ -2,-2 \_____/  0,-2 \_____/  2,-2 \
\       /     \       /     \       /
 \_____/ -1,-1 \_____/  1,-1 \_____/
 /     \       /     \       /     \
/ -2,-1 \_____/  0,-1 \_____/  2,-1 \
\       /     \       /     \       /
 \_____/ -1,0  \_____/  1,0  \_____/
 /     \       /     \       /     \
/ -2,0  \_____/  0,0  \_____/  2,0  \
\       /     \       /     \       /
 \_____/ -1,1  \_____/  1,1  \_____/
 /     \       /     \       /     \
/ -2,1  \_____/  0,1  \_____/  2,1  \
\       /     \       /     \       /
 \_____/ -1,2  \_____/  1,2  \_____/
 /     \       /     \       /     \
/ -2,2  \_____/  0,2  \_____/  2,2  \
\       /     \       /     \       /
 \_____/       \_____/       \_____/


Perl 6, 28 characters

{grep({.Num+|0-$_},^∞)[^$_]}

Try it online!

This is actually 30 bytes, but the challenge is scored in characters.

This should work theoretically. This creates a lazy list of numbers that compares the default number type (with arbitrary precision) against the same number converted to a Num datatype, which is a 64-bit floating point number, and returns the first \$n\$ elements of the list

Here's a version starting at \$2^{53}-5\$


Python 3, 26 bytes

lambda s:ord(s[-1])*2%19%4

Try it online!

$$ f(x) = (2x \bmod 19) \bmod 4 $$


Befunge-93, width = 13 15, titles = 31 24 chars

A power outage last night prevented me from updating this when I figured it out, but I managed to reduce the triangle width and increase the song lengths!

Pointing-up program: "Dig a Pony", 10 characters:

      v
     v>
    v#  >
   "<
  v <>"y"v>
 <v"Dig a P"
"^>:#,_@.>"no

Explanation

I REALLY took advantage of Befunge's wrap-around trick and I picked "Dig a Pony" specifically because it had a space at the 6th position. This allows program flow to move through the song name. Try it in the online interpreter to see how it works.

Pointing-down program: "If I Fell", 9 characters:

< v"f I Fell"
 v>"I">:#,_@
  "raC yM "
   v"Drive

       .

(Period is extraneous and only included to make the other lines show up.)

Explanation

The only relevant lines here are the first two. I used the wrap-around trick (the instruction pointer is sent left immediately) to squeeze in one more character. The second line prints out the song name.

Combined: "Drive My Car", 12 characters:

      v< v"f I Fell"v
     v> v>"I">:#,_@v>
    v#  >"raC yM "v#  >
   "<     v"Drive"<
  v <>"y"v>     v <>"y"v>
 <v"Dig a P"   <v"Dig a P"
"^>:#,_@.>"no "^>:#,_@.>"no
< v"f I Fell"v< v"f I Fell"
 v>"I">:#,_@v> v>"I">:#,_@
  "raC yM "v#  >"raC yM "
   v"Drive"<     v"Drive
         v <>"y"v>
        <v"Dig a P"
       "^>:#,_@.>"no

Here's the same thing, but with lines added to show the hexagon and triangles.

       -----------------
      /v\< v"f I Fell"/v\
     /v> \v>"I">:#,_@/v> \
    /v#  >\"raC yM "/v#  >\
   /"<     \v"Drive/"<     \
  /v <>"y"v>\     /v <>"y"v>\
 /<v"Dig a P"\   /<v"Dig a P"\
/"^>:#,_@.>"no\ /"^>:#,_@.>"no\
-------------------------------
\< v"f I Fell"/v\< v"f I Fell"/
 \v>"I">:#,_@/v> \v>"I">:#,_@/
  \"raC yM "/v#  >\"raC yM "/
   \v"Drive/"<     \v"Drive/
    \     /v <>"y"v>\     /
     \   /<v"Dig a P"\   /
      \ /"^>:#,_@.>"no\ /
       -----------------

Explanation

This is where the third and fourth lines of the pointing-down triangle come into play. There are several redirects at the edge of both triangles that serve to move the instruction pointer through those two lines and push "Drive My Car" onto the stack. Then it is printed out using the >:#,_@ bit in the pointing-up triangle. Incidentally, both the left and the right pointing-up triangles are used.

There might be a way to use more of the empty space, but I think my time is better spent on other questions. :P


List where pinballs would exit a grid of bumpers from different entrance points

JavaScript (ES6),  218 215 213  212 bytes
Takes input as (w,h,o) where \$o\$ is an object whose keys are the coordinates of the bumpers in 'x,y' format and whose values are either '/' or '\'.

(w,h,o)=>(A=[...Array(w+h<<1)].map((_,n)=>(p=n-w)<0?[n,-1,3]:p<h?[w,p]:(p-=w)<h?[h+~p,h,1]:[-1,2*h+~p,2])).map(g=([x,y,d])=>A.every(([X,Y])=>X-x|Y-y&&++i,(c=o[[x+=~-d%2,y+=~-~-d%2]])?d^=c<{}||3:i=0)?g([x,y,d]):i)

Try it online!
Commented
We first create an array \$A[\:]\$ of tuples \$[x, y, d]\$ where \$(x, y)\$ is the starting position along the borders of the playfield and \$d\$ is the initial direction.
( A = [...Array(w + h << 1)]  // create an array A[] of (w + h) * 2 items
  .map((_, n) =>              // for each item at position n in A[]:
    (p = n - w) < 0 ?         //   set p = n - w; if this is the bottom side:
      [n, -1, 3]              //     start at (n, -1) in direction 3
    :                         //   else:
      p < h ?                 //     if this is the right side:
        [w, p]                //       start at (w, p) in direction 0 (implicit)
      :                       //     else:
        (p -= w) < h ?        //       subtract w from p; if this is the top side:
          [h + ~p, h, 1]      //         start at (h + ~p, h) in direction 1
        :                     //       else (left side):
          [-1, 2 * h + ~p, 2] //         start at (-1, 2 * h + ~p) in direction 2
  )                           // end of map()
)                             //

We then simulate the trajectory of the ball, starting at each position defined above, until it reaches another starting position.
.map(g = ([x, y, d]) =>       // for each tuple [x, y, d] in A[]:
  A.every(([X, Y]) =>         //   for each tuple [X, Y] in A[]:
    X - x | Y - y             //     break if (x, y) = (X, Y)
    && ++i,                   //     otherwise, increment i
    ( c =                     //     define c as
        o[[                   //       the bumper character at
          x += ~-d % 2,       //         (x, y), once updated according to d
          y += ~-~-d % 2      //         (0 = West, 1 = South, 2 = East, 3 = North)
        ]]                    //
    ) ?                       //     if c is set:
      d ^= c < {} || 3        //       XOR d with 1 (for '/') or 3 (for '\')
    :                         //     else:
      i = 0                   //       initialize i to 0
  ) ?                         //   end of every(); if truthy:
    g([x, y, d])              //     do a recursive call to move the ball further
  :                           //   else:
    i                         //     we've reached a starting position: yield i
)                             // end of map()


Conways's Game of Life: Most newborn generating starting pattern

Pyth, 65 63 bytes

M}3-BGHeSm+F.n<VVM.:.ugVVuCmsM.:++0k03G2NNd)2muCm.[Hk0GQd^^U2EE

Test suite

Input is taken as:

n,m
x
y

On the input 3,3,12,12, I got 594, not 596, with the same grid as the OP, so I'm not sure what's up.

How it works:

^^U2EE: Generate all possible patterns

muCm.[Hk0GQd: Pad them to the appropriate size. Written as pad, rotate, repeat.

uCmsM.:++0k03G2N: Generate the number of live neighbors for each cells. Written as pad, take subsequences of size 3, sum them, rotate, repeat.

M}3-BGH ... gVV ... N: Pair that with the original grid, use both to calculate the new cells. We do this by checking whether live neighbors including the center, optionally minus whether it was alive, contains a 3. I really like this VV trick, so I wrote a helper function (M}3-BGH) so I could do it twice. (see below)

.u ... d): Do that until it stops changing, return all intermediate steps.

.: ... 2: Take all consecutive pairs.

<VVM: Map each pair to the number of new cells born. I'm particularly proud of <VVM, I thought that was very clever.

m+F.n: Map each grid to its total number of cells born.

eS: Max


MATLAB, 25 bytes
Function accepting a string.
- is converted to =... so the dash is not just preserved, there is twice as much of it?
@(n)106-n-5*(n==48|n==53)


It will require some extra tosses, but you can get a fair result this way:

Always use two throws to determine the answer, a HH or TT throw is discarded.

HT == True
TH == False

You know that the probability of HT is the same as the probability of TH.


Pyth, 36 * .95 * .90 = 30.78

jd+JrFAQ<*vz,H.xeJhH?&%K-vzlJ2>K0K.q

Test suite

Outputs space separated integers and can handle arbitrary integer inputs, so it qualifies for both bonuses.

Input format:

length
starting finger, ending finger

The output is constructed by starting with a range from the starting finger to the ending finger, then repeating the end of that range and the ending finger the necessary number of times. Exiting is done via explicit checks for the length of the second step being odd and positive, or else .q, Pyth's exit function is called.


Python (w/ pypy2 v7.3.1) ~0.9s
Using a Multiple Polynomial Quadratic Sieve. I took this to be a code challenge, so I opted not to use any external libraries (other than the standard log function, I suppose). When timing, the PyPy JIT should be used, as it results in timings 4-5 times faster than that of cPython.
Update (2013-07-29):
Since originally posting, I've made several minor, but significant changes which increase the overall speed by a factor of about 2.5x.
Update (2014-08-27):
As this post is still receiving attention, I've updated my_math.py correcting two errors, for anyone who may be using it:

isqrt was faulty, sometimes producing incorrect output for values very close to a perfect square. This has been corrected, and the performance increased by using a much better seed.
is_prime has been updated. My previous attempt to remove perfect square 2-sprps was half-hearted, at best. I've added a 3-sprp check - a technique used by Mathmatica - to ensure that the tested value is square-free.

Update (2014-11-24):
If at the end of the calculation no non-trivial congruencies are found, the progam now sieves additional polynomials. This was previously marked in the code as TODO.
Update (2020-08-29):
A few improvements resulting in minor performance gains, including:

Calculating the average contributation of the skipped primes, rather than roughly approximating.
Actually sieving powers of the prime factor base. The modular square root of each power can be computed efficiently through use of Hensel Lifting.
Reusing the sieve array in subsequent iterations, rather than creating a new one.

mpqs.py
import math
import my_math
import time

# Multiple Polynomial Quadratic Sieve
# assumes n is composite
def mpqs(n, verbose=False):
  if verbose:
    time1 = time.time()

  root_n = my_math.isqrt(n)
  root_2n = my_math.isqrt(n+n)

  # formula chosen by experimentation
  # seems to be close to optimal for n < 10^50
  bound = int(7.5 * math.log(n, 10)**2)

  prime = []
  mod_root = []
  log_p = []
  num_prime = 0

  # size of the sieve
  x_max = bound * 5
  x_max_2 = x_max+x_max

  # maximum value on the sieved range
  m_val = (x_max * root_2n) >> 1

  # find a number of small primes for which n is a quadratic residue
  pg = my_math.primes()
  p = pg.next()
  while p < bound or num_prime < 3:

    # legendre (n|p) is only defined for odd p
    if p > 2:
      leg = my_math.legendre(n, p)
    else:
      leg = n & 1

    if leg == 1:
      prime += [p]
      log_p += [math.log(p, 10)]
      r = int(my_math.mod_sqrt(n, p))
      roots = [r]
      q = p
      while q < x_max:
        # find all square roots mod p^n via Hensel Lifting
        r = int((r + (n - r*r)*my_math.mod_inv(r+r, q))%q)
        #assert r*r%q == n%q
        roots += [r]
        q *= p
      mod_root += [roots]
      num_prime += 1
    elif leg == 0:
      if verbose:
        print 'trial division found factors:'
        print p, 'x', n/p
      return p

    p = pg.next()

  # fudging the threshold down a bit makes it easier to find powers of partial-partial
  # relationships, but it also makes the smoothness check slower. reducing by twice the log
  # of the largest prime in the factor base results in cofactors less than that value squared
  thresh = math.log(m_val, 10) - log_p[-1]*2

  # skip small primes. they contribute very little to the log sum
  # and add a lot of unnecessary entries to the table
  # instead, fudge the threshold down a bit, according to expected number of factors
  min_prime = int(thresh*2)
  sp_idx = my_math.binary_search(prime, min_prime)
  sieve_primes = prime[sp_idx:]

  fudge = sum([log_p[i]/(prime[i]-1) for i in xrange(sp_idx)])

  sums = [fudge]*x_max_2

  if verbose:
    print 'smoothness bound:', bound
    print 'sieve size:', x_max
    print 'log threshold:', thresh
    print 'skipping primes less than:', min_prime

  smooth = []
  used_prime = set()
  partial = {}
  num_smooth = 0
  prev_num_smooth = 0
  num_used_prime = 0
  num_partial = 0
  num_poly = 0
  root_A = my_math.isqrt(root_2n / x_max)

  if verbose:
    print 'sieving for smooths...'
  while True:
    # find an integer value A such that:
    # A is =~ sqrt(2*n) / x_max
    # A is a perfect square
    # sqrt(A) is prime, and n is a quadratic residue mod sqrt(A)
    while True:
      root_A = my_math.next_prime(root_A)
      leg = my_math.legendre(n, root_A)
      if leg == 1:
        break
      elif leg == 0:
        if verbose:
          print 'dumb luck found factors:'
          print root_A, 'x', n/root_A
        return root_A

    A = root_A * root_A

    # solve for an adequate B
    # B*B is a quadratic residue mod n, such that B*B-A*C = n
    # this is unsolvable if n is not a quadratic residue mod sqrt(A)
    b = my_math.mod_sqrt(n, root_A)
    B = (b + (n - b*b) * my_math.mod_inv(b + b, root_A))%A

    # B*B-A*C = n <=> C = (B*B-n)/A
    C = (B*B - n) / A

    num_poly += 1

    # sieve for prime factors
    i = sp_idx
    for p in sieve_primes:
      logp = log_p[i]

      e = 0
      q = p
      while q < x_max:
        inv_A = my_math.mod_inv(A, q)
        # modular root of the quadratic
        a = int(((mod_root[i][e] - B) * inv_A)%q)
        b = int(((q - mod_root[i][e] - B) * inv_A)%q)

        amx = a+x_max
        bmx = b+x_max

        apx = amx-q
        bpx = bmx-q

        k = q
        while k < x_max:
          sums[apx+k] += logp
          sums[bpx+k] += logp
          sums[amx-k] += logp
          sums[bmx-k] += logp
          k += q

        q *= p
        e += 1

      i += 1

    # check for smooths
    x = -x_max
    i = 0
    while i < x_max_2:
      v = sums[i]
      if v > thresh:
        vec = set()
        sqr = []
        # because B*B-n = A*C
        # (A*x+B)^2 - n = A*A*x*x+2*A*B*x + B*B - n
        #               = A*(A*x*x+2*B*x+C)
        # gives the congruency
        # (A*x+B)^2 = A*(A*x*x+2*B*x+C) (mod n)
        # because A is chosen to be square, it doesn't need to be sieved
        sieve_val = (A*x + B+B)*x + C

        if sieve_val < 0:
          vec = {-1}
          sieve_val = -sieve_val

        for p in prime:
          while sieve_val%p == 0:
            if p in vec:
              # keep track of perfect square factors
              # to avoid taking the sqrt of a gigantic number at the end
              sqr += [p]
            vec ^= {p}
            sieve_val = int(sieve_val / p)

        if sieve_val == 1:
          # smooth
          smooth += [(vec, (sqr, (A*x+B), root_A))]
          used_prime |= vec
        elif sieve_val in partial:
          # combine two partials to make a (xor) smooth
          # that is, every prime factor with an odd power is in our factor base
          pair_vec, pair_vals = partial[sieve_val]
          sqr += list(vec & pair_vec) + [sieve_val]
          vec ^= pair_vec
          smooth += [(vec, (sqr + pair_vals[0], (A*x+B)*pair_vals[1], root_A*pair_vals[2]))]
          used_prime |= vec
          num_partial += 1
        else:
          # save partial for later pairing
          partial[sieve_val] = (vec, (sqr, A*x+B, root_A))
      x += 1

      # reset the value for the next go
      sums[i] = fudge
      i += 1

    prev_num_smooth = num_smooth
    num_smooth = len(smooth)
    num_used_prime = len(used_prime)

    if verbose:
      print 100 * num_smooth / num_prime, 'percent complete\r',

    if num_smooth > num_used_prime and num_smooth > prev_num_smooth:
      if verbose:
        print '%d polynomials sieved (%d values)'%(num_poly, num_poly*x_max_2)
        print 'found %d smooths (%d from partials) in %.3f seconds'%(num_smooth, num_partial, time.time()-time1)
        print 'solving for non-trivial congruencies...'

      # set up bit fields for gaussian elimination
      masks = []
      mask = 1
      bit_fields = [0]*num_used_prime
      for vec, vals in smooth:
        masks += [mask]
        i = 0
        for p in used_prime:
          if p in vec: bit_fields[i] |= mask
          i += 1
        mask += mask

      # row echelon form
      col_offset = 0
      null_cols = []
      for col in xrange(num_smooth):
        pivot = col-col_offset == num_used_prime or bit_fields[col-col_offset] & masks[col] == 0
        for row in xrange(col+1-col_offset, num_used_prime):
          if bit_fields[row] & masks[col]:
            if pivot:
              bit_fields[col-col_offset], bit_fields[row] = bit_fields[row], bit_fields[col-col_offset]
              pivot = False
            else:
              bit_fields[row] ^= bit_fields[col-col_offset]
        if pivot:
          null_cols += [col]
          col_offset += 1

      # reduced row echelon form
      for row in xrange(num_used_prime):
        # lowest set bit
        mask = bit_fields[row] & -bit_fields[row]
        for up_row in xrange(row):
          if bit_fields[up_row] & mask:
            bit_fields[up_row] ^= bit_fields[row]

      # check for non-trivial congruencies
      for col in null_cols:
        all_vec, (lh, rh, rA) = smooth[col]
        lhs = lh   # sieved values (left hand side)
        rhs = [rh] # sieved values - n (right hand side)
        rAs = [rA] # root_As (cofactor of lhs)
        i = 0
        for field in bit_fields:
          if field & masks[col]:
            vec, (lh, rh, rA) = smooth[i]
            lhs += list(all_vec & vec) + lh
            all_vec ^= vec
            rhs += [rh]
            rAs += [rA]
          i += 1

        factor = my_math.gcd(my_math.list_prod(rAs)*my_math.list_prod(lhs) - my_math.list_prod(rhs), n)
        if 1 < factor < n:
          break
      else:
        if verbose:
          print 'none found.'
        continue
      break

  if verbose:
    print 'factors found:'
    print factor, 'x', n/factor
    print 'time elapsed: %.3f seconds'%(time.time()-time1)
  return factor

if __name__ == "__main__":
  import argparse
  parser = argparse.ArgumentParser(description='Uses a MPQS to factor a composite number')
  parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
  parser.add_argument('--verbose', dest='verbose', action='store_true', help="enable verbose output")
  args = parser.parse_args()

  if args.verbose:
    mpqs(args.composite, args.verbose)
  else:
    time1 = time.time()
    print mpqs(args.composite)
    print 'time elapsed: %.3f seconds'%(time.time()-time1)

my_math.py
import math
import mpqs

# primes less than 212
small_primes = [
    2,  3,  5,  7, 11, 13, 17, 19, 23, 29, 31, 37,
   41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
   97,101,103,107,109,113,127,131,137,139,149,151,
  157,163,167,173,179,181,191,193,197,199,211]

# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
    1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
   53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,
  107,109,113,121,127,131,137,139,143,149,151,157,
  163,167,169,173,179,181,187,191,193,197,199,209]

# distances between sieve values
offsets = [
  10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
   6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
   2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
   4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]

# tabulated, mod 105
dindices =[
  0,10, 2, 0, 4, 0, 0, 0, 8, 0, 0, 2, 0, 4, 0,
  0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 6, 0, 0, 2,
  0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 2,
  0, 6, 6, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 4, 2,
  0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 6, 2,
  0, 6, 0, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 8,
  0, 0, 2, 0,10, 0, 0, 4, 0, 0, 0, 2, 0, 4, 2]

max_int = 2147483647

# returns the index of x in a sorted list a
# or the index of the next larger item if x is not present
# i.e. the proper insertion point for x in a
def binary_search(a, x):
  s = 0
  e = len(a)
  m = e >> 1
  while m != e:
    if a[m] < x:
      s = m
      m = (s + e + 1) >> 1
    else:
      e = m
      m = (s + e) >> 1
  return m

# divide and conquer list product
def list_prod(a):
  while len(a) > 1:
    a = [m*n for m,n in zip(a[::2], a[1::2] + [1])]
  return a[0]

# greatest common divisor of a and b
def gcd(a, b):
  while b:
    a, b = b, a%b
  return a

# extended gcd
def ext_gcd(a, m):
  a = int(a%m)
  x, u = 0, 1
  while a:
    x, u = u, x - (m/a)*u
    m, a = a, m%a
  return (m, x, u)

# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
  return pow(a, (m-1) >> 1, m)

# modular inverse of a mod m
def mod_inv(a, m):
  return ext_gcd(a, m)[1]

# modular sqrt(n) mod p
# p must be prime
def mod_sqrt(n, p):
  a = n%p
  if p%4 == 3:
    return pow(a, (p+1) >> 2, p)
  elif p%8 == 5:
    v = pow(a << 1, (p-5) >> 3, p)
    i = ((a*v*v << 1) % p) - 1
    return (a*v*i)%p
  elif p%8 == 1:
    # Shanks' method
    q = p-1
    e = 0
    while q&1 == 0:
      e += 1
      q >>= 1

    n = 2
    while legendre(n, p) != p-1:
      n += 1

    w = pow(a, q, p)
    x = pow(a, (q+1) >> 1, p)
    y = pow(n, q, p)
    r = e
    while True:
      if w == 1:
        return x

      v = w
      k = 0
      while v != 1 and k+1 < r:
        v = (v*v)%p
        k += 1

      if k == 0:
        return x

      d = pow(y, 1 << (r-k-1), p)
      x = (x*d)%p
      y = (d*d)%p
      w = (w*y)%p
      r = k
  else: # p == 2
    return a

#integer sqrt of n
def isqrt(n):
  c = (n << 2)/3
  d = c.bit_length()

  a = d>>1
  if d&1:
    x = 1 << a
    y = (x + (n >> a)) >> 1
  else:
    x = (3 << a) >> 2
    y = (x + (c >> a)) >> 1

  if x != y:
    x = y
    y = (x + n/x) >> 1
    while y < x:
      x = y
      y = (x + n/x) >> 1
  return x

# integer cbrt of n
def icbrt(n):
  d = n.bit_length()

  if d%3 == 2:
    x = 3 << d/3-1
  else:
    x = 1 << d/3

  y = (2*x + n/(x*x))/3
  if x != y:
    x = y
    y = (2*x + n/(x*x))/3
    while y < x:
      x = y
      y = (2*x + n/(x*x))/3
  return x

# strong probable prime
def is_sprp(n, b=2):
  if n < 2: return False
  d = n-1
  s = 0
  while d&1 == 0:
    s += 1
    d >>= 1

  x = pow(b, d, n)
  if x == 1 or x == n-1:
    return True

  for r in xrange(1, s):
    x = (x * x)%n
    if x == 1:
      return False
    elif x == n-1:
      return True

  return False

# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
  P = 1
  Q = (1-D) >> 2

  # n+1 = 2**r*s where s is odd
  s = n+1
  r = 0
  while s&1 == 0:
    r += 1
    s >>= 1

  # calculate the bit reversal of (odd) s
  # e.g. 19 (10011) <=> 25 (11001)
  t = 0
  while s:
    if s&1:
      t += 1
      s -= 1
    else:
      t <<= 1
      s >>= 1

  # use the same bit reversal process to calculate the sth Lucas number
  # keep track of q = Q**n as we go
  U = 0
  V = 2
  q = 1
  # mod_inv(2, n)
  inv_2 = (n+1) >> 1
  while t:
    if t&1:
      # U, V of n+1
      U, V = ((U + V) * inv_2)%n, ((D*U + V) * inv_2)%n
      q = (q * Q)%n
      t -= 1
    else:
      # U, V of n*2
      U, V = (U * V)%n, (V * V - 2 * q)%n
      q = (q * q)%n
      t >>= 1

  # double s until we have the 2**r*sth Lucas number
  while r:
    U, V = (U * V)%n, (V * V - 2 * q)%n
    q = (q * q)%n
    r -= 1

  # primality check
  # if n is prime, n divides the n+1st Lucas number, given the assumptions
  return U == 0

## Baillie-PSW ##
# this is technically a probabalistic test, but there are no known pseudoprimes
def is_bpsw(n):
  if not is_sprp(n, 2): return False

  # idea shamelessly stolen from Mathmatica's PrimeQ
  # if n is a 2-sprp and a 3-sprp, n is necessarily square-free
  if not is_sprp(n, 3): return False

  a = 5
  s = 2
  # if n is a perfect square, this will never terminate
  while legendre(a, n) != n-1:
    s = -s
    a = s-a
  return is_lucas_prp(n, a)

# an 'almost certain' primality check
def is_prime(n):
  if n < 212:
    m = binary_search(small_primes, n)
    return n == small_primes[m]

  for p in small_primes:
    if n%p == 0:
      return False

  # if n is a 32-bit integer, perform full trial division
  if n <= max_int:
    p = 211
    while p*p < n:
      for o in offsets:
        p += o
        if n%p == 0:
          return False
    return True

  return is_bpsw(n)

# next prime strictly larger than n
def next_prime(n):
  if n < 2:
    return 2

  n += 1
  if n < 212:
    m = binary_search(small_primes, n)
    return small_primes[m]

  # find our position in the sieve rotation via binary search
  x = int(n%210)
  m = binary_search(indices, x)
  i = int(n + (indices[m] - x))

  # adjust offsets
  offs = offsets[m:] + offsets[:m]
  while True:
    for o in offs:
      if is_prime(i):
        return i
      i += o

# an infinite prime number generator
def primes(start = 0):
  for n in small_primes[start:]: yield n
  pg = primes(6)
  p = pg.next()
  q = p*p
  sieve = {221: 13, 253: 11}
  n = 211
  while True:
    for o in offsets:
      n += o
      stp = sieve.pop(n, 0)
      if stp:
        nxt = n/stp
        nxt += dindices[nxt%105]
        while nxt*stp in sieve:
          nxt += dindices[nxt%105]
        sieve[nxt*stp] = stp
      elif n < q:
        yield n
      else:
        sieve[q + dindices[p%105]*p] = p
        p = pg.next()
        q = p*p

# true if n is a prime power > 0
def is_prime_power(n):
  if n > 1:
    for p in small_primes:
      if n%p == 0:
        n /= p
        while n%p == 0: n /= p
        return n == 1

    r = isqrt(n)
    if r*r == n:
      return is_prime_power(r)

    s = icbrt(n)
    if s*s*s == n:
      return is_prime_power(s)

    p = 211
    while p*p < r:
      for o in offsets:
        p += o
        if n%p == 0:
          n /= p
          while n%p == 0: n /= p
          return n == 1

    if n <= max_int:
      while p*p < n:
        for o in offsets:
          p += o
          if n%p == 0:
            return False
      return True

    return is_bpsw(n)
  return False

max_trial = 1e10
max_pollard = 1e22

def factor(n):
  if n < max_trial:
    return factor_trial(n)
  for p in small_primes:
    if n%p == 0:
      return [p] + factor(n/p)
  if is_prime(n):
    return [n]
  if n < max_pollard:
    p = pollard_rho(n)
  else:
    p = lenstra_ecf(n) or mpqs.mpqs(n)
  return factor(p) + factor(n/p)

def factor_trial(n):
  a = []
  for p in small_primes:
    while n%p == 0:
      a += [p]
      n /= p
  i = 211
  while i*i < n:
    for o in offsets:
      i += o
      while n%i == 0:
        a += [i]
        n /= i
  if n > 1:
    a += [n]
  return a

def pollard_rho(n):
  # Brent's variant
  y, r, q = 0, 1, 1
  c, m = 9, 40
  g = 1
  while g == 1:
    x = y
    for i in range(r):
      y = (y*y + c) % n
    k = 0
    while k < r and g == 1:
      ys = y
      for j in range(min(m, r-k)):
        y = (y*y + c) % n
        q = q*abs(x-y) % n
      g = gcd(q, n)
      k += m
    r *= 2
  if g == n:
    ys = (ys*ys + c) % n
    g = gcd(n, abs(x-ys))
    while g == 1:
      ys = (ys*ys + c) % n
      g = gcd(n, abs(x-ys))
  return g

def ec_add((x1, z1), (x2, z2), (x0, z0), n):
  t1, t2 = (x1-z1)*(x2+z2), (x1+z1)*(x2-z2)
  x, z = t1+t2, t1-t2
  return (z0*x*x % n, x0*z*z % n)

def ec_double((x, z), (a, b), n):
  t1 = x+z; t1 *= t1
  t2 = x-z; t2 *= t2
  t3 = t1 - t2
  t4 = 4*b*t2
  return (t1*t4 % n, t3*(t4 + a*t3) % n)

def ec_multiply(k, p, C, n):
  # Montgomery ladder algorithm
  p0 = p
  q, p = p, ec_double(p, C, n)
  b = k >> 1
  while b > (b & -b):
    b ^= b & -b
  while b:
    if k&b:
      q, p = ec_add(p, q, p0, n), ec_double(p, C, n)
    else:
      q, p = ec_double(q, C, n), ec_add(p, q, p0, n),
    b >>= 1
  return q

def lenstra_ecf(n, m = 5):
  # Montgomery curves w/ Suyama parameterization.
  # Based on pseudocode found in:
  # "Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware"
  # Gaj, Kris et. al
  # http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
  # Phase 2 is not implemented.
  B1, B2 = 8, 13
  for i in range(m):
    pg = primes()
    p = pg.next()
    k = 1
    while p < B1:
      k *= p**int(math.log(B1, p))
      p = pg.next()
    for s in range(B1, B2):
      u, v = s*s-5, 4*s
      x = u*u*u
      z = v*v*v
      t = pow(v-u, 3, n)
      P = (x, z)
      C = (t*(3*u+v) % n, 4*x*v % n)
      Q = ec_multiply(k, P, C, n)
      g = gcd(Q[1], n)
      if 1 < g < n: return g
    B1, B2 = B2, B1 + B2

if __name__ == "__main__":
  import argparse
  import time
  parser = argparse.ArgumentParser(description='Uses a various methods to factor a composite number')
  parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
  args = parser.parse_args()

  time1 = time.time()
  print factor(args.composite)
  print 'time elapsed: %.3f seconds'%(time.time()-time1)

Sample I/O:
$ pypy mpqs.py --verbose 523022617466601111760007224100074291200000001
smoothness bound: 14998
sieve size: 74990
log threshold: 18.7325510316
skipping primes less than: 37
sieving for smooths...
230 polynomials sieved (34495400 values)
found 849 smooths (242 from partials) in 0.786 seconds
solving for non-trivial congruencies...
factors found:
37280713718589679646221 x 14029308060317546154181
time elapsed: 1.011 seconds

Note: not using the --verbose option will give slightly better timings:
$ pypy mpqs.py 523022617466601111760007224100074291200000001
37280713718589679646221
time elapsed: 0.902 seconds

Basic Concepts
In general, a quadratic sieve is based on the following observation: any odd composite \$n\$ may be represented as:
\$n=(x+d)(x-d)=x^2-d^2\Rightarrow d^2=x^2-n\$
This is not very difficult to confirm. Since \$n\$ is odd, the distance between any two cofactors of \$n\$ must be even \$2d\$, where \$x\$ is the mid point between them. Moreover, the same relation holds for any multiple of \$n\$
\$abn=(ax+ad)(bx-bd)=abx^2-abd^2\Rightarrow abd^2=abx^2-abn\$
Note that if any such \$x\$ and \$d\$ can be found, it will immediately result in a (not necessarily prime) factor of \$n\$, since \$x+d\$ and \$x-d\$ both divide \$n\$ by definition. This relation can be further weakened - at the consequence of allowing potential trivial congruencies - to the following form:
\$d^2\equiv x^2\mod n\$
So in general, if we can find two perfect squares which are equivalent mod \$n\$, then it's fairly likely that we can directly produce a factor of \$n\$ a la \$\gcd(x±d,n)\$. Seems pretty simple, right?
Except it's not. If we intended to conduct an exhaustive search over all possible \$x\$, we would need to search the entire range from \$\sqrt{n}\$ to \$\sqrt{2n}\$, which is marginally smaller than full trial division, but also requires an expensive is_square operation each iteration to confirm the value of \$d\$. Unless it is known beforehand that \$n\$ has factors very near \$\sqrt{n}\$, trial division is likely to be faster.
Perhaps we can weaken this relation even more. Suppose we chose an \$x\$, such that for
\$y\equiv x^2\mod n\$
a full prime factorization of \$y\$ is readily known. If we had enough such relations, we should be able to construct an adequate \$d\$, if we choose a number of \$y\$ such that their product is a perfect square; that is, all prime factors are used an even number of times. In fact, if we have more such \$y\$ than the total number of unique prime factors they contain, a solution is guaranteed to exist; It becomes a system of linear equations. The question now becomes, how do we chose such \$x\$? That's where sieving comes into play.
The Sieve
Consider the polynomial:
\$y(x)=x^2-n\$
Then for any prime \$p\$ and integer \$k\$, the following is true:
\$y(x+kp)=(x+kp)^2-n\\y(x+kp)=x^2+2xkp+(kp)^2-n\\y(x+kp)=y(x)+2xkp+(kp)^2\equiv y(x)\mod p\$
This means that after solving for the roots of the polynomial mod \$p\$ - that is, you've found an \$x\$ such that \$y(x)\equiv 0\mod p\$, ergo \$y\$ is divisible by \$p\$ - then you have found an infinite number of such \$x\$. In this way, you can sieve over a range of \$x\$, identifying small prime factors of \$y\$, hopefully finding some for which all prime factors are small. Such numbers known as \$k-smooth\$, where \$k\$ is the largest prime factor used.
There's a few problems with this approach, though. Not all values of \$x\$ are adequate, in fact, there's only very few of them, centered around \$\sqrt{n}\$. Smaller values will become largely negative (due to the \$-n\$ term), and larger values will become too large, such that it is unlikely that their prime factorization consists only of small primes. There will be a number of such \$x\$, but unless the composite you're factoring is very small, it's highly unlikely that you'll find enough smooths to result in a factorization. And so, for larger \$n\$, it becomes necessary to sieve over multiple polynomials of a given form.
Multiple Polynomials
So we need more polynomials to sieve? How about this:
\$y(x)=(Ax+B)^2-n\$
That'll work. Note that \$A\$ and \$B\$ could literally be any integer value, and the math still holds. All we need to do is choose a few random values, solve for the root of the polynomial, and sieve the values close to zero. At this point we could just call it good enough: if you throw enough stones in random directions, you're bound to break a window sooner or later.
Except, there's a problem with that too. If the slope of the polynomial is large at the x-intercept, there'll only be a few suitable values to sieve per polynomial. It'll work, but you'll end up sieving a whole lot of polynomials before you get what you need. Can we do better?
We can do better. An observation, as a result of Montgomery is as follows: if \$A\$ and \$B\$ are chosen such that there exists some \$C\$ satisfying
\$B^2-n=AC\$
then the entire polynomial can be rewritten as
\$y(x)=(Ax+B)^2-n=(Ax)^2+2ABx+B^2-n=A(Ax^2+2Bx+C)\$
Furthermore, if \$A\$ is chosen to be a perfect square, the leading \$A\$ term can be neglected while sieving, resulting in much smaller values, and a much flatter curve. For such a solution to exist, \$n\$ must be a quadratic residue mod \$\sqrt{A}\$, which can be known immediately by computing the Legendre symbol:
\$(n|\sqrt{A})=1\$. Note that in order to solve for \$B\$, a complete prime factorization of \$\sqrt{A}\$ needs to be known (in order to take the modular square root \$\sqrt{n}\mod\sqrt{A}\$), which is why \$\sqrt{A}\$ is typically chosen to be prime.
It can then be shown that if \$A\approx\frac{\sqrt{2n}}{M}\$, then for all values of \$x\in[-M,M]\$:
\$|y(x)|\le\frac{M\sqrt{2n}}{2}\$
And now, finally, we have all the components necessary to implement our sieve. Or do we?
Powers of Primes as Factors
Our sieve, as described above, has one major flaw. It can identify which values of \$x\$ will result in a \$y\$ divisible by \$p\$, but it cannot identify whether or not this \$y\$ is divisible by a power of \$p\$. In order to determine that, we would need to perform trial division on the value to be sieved, until it is no longer divisible by \$p\$.

Edit: This is incorrect. The roots of \$n\$ mod \$p^k\$ can be computed directly from the roots mod \$p\$ through the use of Hensel Lifting. This current implementation does precisely this.

We seemed to have reached an impasse: the whole point of the sieve was so that we didn't have to do that. Time to check the playbook.
\$\ln(a\cdot b\cdot c\cdot d\cdot\ldots)=\ln(a)+\ln(b)+\ln(c)+\ln(d)+\ln(\ldots)\$
That looks pretty useful. If the sum of the \$\ln\$ of all of the small prime factors of \$y\$ is close to the expected value of \$\ln(y)\$, then it's almost a given that \$y\$ has no other factors. In addition, if we adjust the expected value down a little bit, we can also identify values as smooth which have several powers of primes as factors. In this way, we can use the sieve as a 'pre-screening' process, and only factor those values which are likely to be smooth.
This has a few other advantages as well. Note that small primes contribute very little to the \$\ln\$ sum, but yet they require the most sieve time. Sieving the value 3 requires more time than 11, 13, 17, 19, and 23 combined. Instead, we can just skip the first few primes, and adjust the threshold down accordingly, assuming a certain percentage of them would have passed.
Another result, is that a number of values will be allowed to 'slip through', which are mostly smooth, but contain a single large cofactor. We could just discard these values, but suppose we found another mostly smooth value, with exactly the same cofactor. We can then use these two values to construct a usable \$y\$; since their product will contain this large cofactor squared, it no longer needs to be considered.
Putting it all together
The last thing we need to do is to use these values of \$y\$ construct an adequate \$x\$ and \$d\$. Suppose we only consider the non-square factors of \$y\$, that is, the prime factors of an odd power. Then, each \$y\$ can be expressed in the following manner:
\$y_0=p_0^0\cdot p_1^1\cdot p_2^1\cdots p_n^0\\y_1=p_0^1\cdot p_1^0\cdot p_2^1\cdots p_n^1\\y_2=p_0^0\cdot p_1^0\cdot p_2^0\cdots p_n^1\\y_3=p_0^1\cdot p_1^1\cdot p_2^0\cdots p_n^0\\\vdots\$
which can be expressed in the matrix form:
\$M=\begin{bmatrix}0&1&1&\cdots&0\\1&0&1&\cdots&1\\0&0&0&\cdots&1\\1&1&0&\cdots&0\\\vdots\end{bmatrix}\$
The problem then becomes to find a vector \$v\$ such that \$vM=\vec{0}\mod 2\$, where \$\vec{0}\$ is the null vector. That is, to solve for the left null space of \$M\$. This can be done in a number of ways, the simplest of which is to perform Gaussian Elimination on \$M^T\$, replacing the row addition operation with a row xor. This will result in a number of null space basis vectors, any combination of which will produce a valid solution.
The construction of \$x\$ is fairly straight-forward. It is simply the product of \$Ax+B\$ for each of the \$y\$ used. The construction of \$d\$ is slightly more complicated. If we were to take the product of all \$y\$, we will end up with a value with 10s of thousands, if not 100s of thousands of digits, for which we need to find the square root. This calcuation is impractically expensive. Instead, we can keep track of the even powers of primes during the sieving process, and then use and and xor operations on the vectors of non-square factors to reconstruct the square root.
I seem to have reached the 30000 character limit. Ahh well, I suppose that's good enough. Saved a bunch of bytes by switching to \$MathJax\$.


Jelly, 7 6 bytes

;_/!:/

Look ma, no Unicode! This program takes a single list as input, with n at its first index.

Try it online! or verify all test cases at once.

How it works

;_/!:/ Input: A (list)

 _/    Reduce A by subtraction. This subtracts all other elements from the first.
;      Concatenate A with the result to the right.
   !   Apply factorial to all numbers in the resulting list.
    :/ Reduce the result by division. This divides the first element by the others.


LARGEST program to reverse a single line from stdin with no redundant code

C# – Something about 90 KB, but actually, ~90×n for any n

See https://gist.github.com/mormegil-cz/8581459 for the full source code. A short preview version to taste:

var c1 = Console.Read();
if (c1 > 0 && c1 != 13)
{
    var c2 = Console.Read();
    if (c2 > 0 && c2 != 13)
    {
        var c3 = Console.Read();
        if (c3 > 0 && c3 != 13)
        {
            // ...
            Console.Write((char)c3);
        }
        Console.Write((char)c2);
    }
    Console.Write((char)c1);
}
Console.WriteLine();

And because writing the source code seems a bit repetitive, let’s use a simple tool:

void Main()
{
    const int MAX_DEPTH = 1000;
    Console.WriteLine("using System;");
    Console.WriteLine("using System.Text;");
    Console.WriteLine();
    Console.WriteLine("class C");
    Console.WriteLine("{");
    Console.WriteLine("\tstatic void Main()");
    Console.WriteLine("\t{");
    for (int i = 0; i < MAX_DEPTH; ++i)
    {
        var indent = new string('\t', i + 2);
        Console.WriteLine("{0}var c{1} = Console.Read();", indent, i);
        Console.WriteLine("{0}if (c{1} > 0 && c{1} != 13)", indent, i);
        Console.WriteLine("{0}{{", indent);
    }
    var restIndent = new string('\t', MAX_DEPTH + 2);
    Console.WriteLine("{0}var rest = new StringBuilder();", restIndent);
    Console.WriteLine("{0}for (var c = Console.Read(); c > 0 && c != 13; c = Console.Read())", restIndent);
    Console.WriteLine("{0}{{", restIndent);
    Console.WriteLine("{0}\trest.Append((char)c);", restIndent);
    Console.WriteLine("{0}}}", restIndent);
    Console.WriteLine("{0}var restArray = rest.ToString().ToCharArray();", restIndent);
    Console.WriteLine("{0}Array.Reverse(restArray);", restIndent);
    Console.WriteLine("{0}Console.Write(new string(restArray));", restIndent);
    for (int i = MAX_DEPTH - 1; i >= 0; --i)
    {
        var indent = new string('\t', i + 2);
        Console.WriteLine("{0}\tConsole.Write((char)c{1});", indent, i);
        Console.WriteLine("{0}}}", indent);
    }
    Console.WriteLine("\t\tConsole.WriteLine();");
    Console.WriteLine("\t}");
    Console.WriteLine("}");
}

Change MAX_DEPTH to get a larger score (or possibly an internal C# compiler error?).


MATL, 2 bytes

Za

Try it online!
All test cases.

For the Za lord!


Table cloths
Flat
I started out putting a plaid/gingham pattern into perspective like a boundless table cloth:
unsigned char RD(int i,int j){
    float s=3./(j+99);
    return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;
}
unsigned char GR(int i,int j){
    float s=3./(j+99);
    return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;
}
unsigned char BL(int i,int j){
    float s=3./(j+99);
    return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;
}

Ripple
Then I introduced a ripple (not strictly correct perspective, but still in 140 characters):
unsigned char RD(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
unsigned char GR(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
unsigned char BL(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}

Colour
Then I made some of the colours more fine grained to give detail on a wider range of scales, and to make the picture more colourful...
unsigned char RD(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;
}
unsigned char GR(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;
}
unsigned char BL(int i,int j){
    float s=3./(j+99);
    float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;
    return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;
}

In motion
Reducing the code just slightly more allows for defining a wave phase P with 2 decimal places, which is just enough for frames close enough for smooth animation. I've reduced the amplitude at this stage to avoid inducing sea sickness, and shifted the whole image up a further 151 pixels (at the cost of 1 extra character) to push the aliasing off the top of the image. Animated aliasing is mesmerising.
unsigned char RD(int i,int j){
#define P 6.03
float s=3./(j+250),y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;}

unsigned char GR(int i,int j){
float s=3./(j+250);
float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;
return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;}

unsigned char BL(int i,int j){
float s=3./(j+250);
float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;
return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;}


Calculate the Gamma function for half-integer arguments

M, 7 bytes

,0_.!÷/

Try it online! or verify all test cases.

Trivia

Meet M!

M is a fork of Jelly, aimed at mathematical challenges. The core difference between Jelly and M is that M uses infinite precision for all internal calculations, representing results symbolically. Once M is more mature, Jelly will gradually become more multi-purpose and less math-oriented.

M is very much work in progress (full of bugs, and not really that different from Jelly right now), but it works like a charm for this challenge and I just couldn't resist.

How it works

,0_.!÷/  Main link. Argument: n

,0       Pair with 0. Yields [n, 0].
  _.     Subtract 1/2. Yields [n - 1/2, -1/2].
    !    Apply the Π function. Yields [Π(n - 1/2), Π(-1/2)] = [Γ(n + 1/2), Γ(1/2)].
     ÷/  Reduce by division. Yields Γ(n + 1/2) ÷ Γ(1/2) = Γ(n + 1/2) ÷ √π.


Semi-decide Post's Correspondence Problem

Python 3, 223 216 199 192 191 189 183 bytes
Thanks to @KarlKastor for pointing out that I could use count
from itertools import*
j=''.join
def f(x):
 for l in count(1):
  for i in product(x,repeat=l):
   *b,=zip(*i);c=j(b[0])
   if c==j(b[1]):print(c,j(str(x.index(k)+1)for k in i));return

A function that takes input of a tuple of pairs of strings x in the form ((seq1,seq2),(seq1,seq2)...) and prints the output to STDOUT in the same format as the test cases.
To continuously output solutions rather than just one solution, remove the return statement.
How it works
The function generates all l-length arrangements of the string pairs using product, with l being initialised at 1. This list is then unpacked and transposed using zip; this leaves a two-element list, where the first element contains all the first strings in the pairs, and the second all the second strings in the pairs. Each element is concatenated to a string using join; if these are the same, we have a hit and the string is printed to STDOUT. The sequence of pair indices is then generated by looking up each pair in the original arrangement using index; these indices are concatenated to a string, and also printed to STDOUT. If no solution exists for that l, l is incremented and the process repeated.
Try it on Ideone


C, 149 89

Well, this was a noobish shot at it, but probably a decent starting point:

#include <cstdio>
float i;
int o(float a,int n=2){return a<0?n-2:o(a-1./n,n+1);}
main(){if (scanf("%f",&i),i==0) return 0;printf("%d card(s)\n",o(i));main();}

It reported as 145 characters.

With a push in the right direction, I got the solution down to 122 by changing the function to a for loop.

#include <cstdio>
float i;
main(){
if (scanf("%f",&i),i==0) return 0;
int n=2;for(;i>0;)i-=1./n++;
printf("%d card(s)\n",n-2);
main();}

On a roll!

#include <cstdio>
main()
{
    float i,n=2;
    for(scanf("%f",&i);i>0;i-=1/n++);
    if (n-=2) printf("%.0f card(s)\n",n), main();
}

Scooted scanf, for loop division doesn't need 1. any more, adjusting n now done in conditional.

Switched over to C, got some good savings.  Down to 89 characters.

main(n)
{
    float i;
    for(scanf("%f",&i);i>0;i-=1./++n);
    if (--n) printf("%d card(s)\n",n), main(1);
}


Find a function with cycles of every length

MATL, 47 bytes
E|G0<-QXJ:tQ*2/0hStJ<f0))Q2MQ)&:J6M-)2/ttk>Eq*k

Try it online!
General explanation
Function 2 below is the same as used in @Sp3000's answer to the related challenge. Thanks to @Agawa001 for noticing.
The function is the composition of three:

Bijection from Z (the integers) to N (the naturals).
Bijection from N to N with the desired characteristic (one cycle of each length).
Inverse of function 1.

Functions 1 and 3 are used because it's easier (I think) to achieve the desired behaviour in N than in Z.
Function 2 is as follows: upper line is domain, lower line is codomain. Commas are used for clarity:
1,  2  3,  4  5  6,  7  8  9  10  ...
1,  3  2,  6  4  5, 10  7  8   9  ...

The first block (from upper 1 to lower 1) is a cycle of length 1. The second (from 2 3 to 3 2) is a cycle of length 2, etc. In each block, the lower part (image of the function) is the upper part circularly shifted one step to the right.
Function 1 is as follows:
 -5  -4  -3  -2  -1   0  +1  +2  +3  +4  ...
+10  +8  +6  +4  +2  +1  +3  +5  +7  +9  ...

Function 3 is the same as 1 with the two lines swapped.
Examples
The image of 3 is -5. First 3 is mapped to 7 by function 1; then 7 is mapped to 10 by function 2; then 10 is mapped to -5` by function 3.
The length-1 cycle is 0. The length-2 cycle is -1 1. The length-3 cycle is -3 2 -2, etc.
Code explained
Functions 1 and 3 are straightforward.
Function 2 works by finding the lower endpoint of the corresponding input block. For example, if the input to this function is 9 it finds 7 (see blocks above). It then picks the upper endpoint, which is 10 in the example. The circular shift of the block is achieved thanks to MATL's 1-based, modular indexing.
         % FUNCTION 1
         % Implicit input
E|       % Multiply by two. Absolute value
G0<      % 1 if input is negative, 0 otherwise
-        % Subtract
Q        % Add 1
XJ       % Copy to clipboard J. Used as input to the next function

         % FUNCTION 2
:        % Range [1 2 ... J], where J denotes the input to this function
tQ*      % Duplicate, increment by 1, multiply
2/       % Divide by 2
0hS      % Prepend a 0. This is needed in case J is 0
tJ<f     % Duplicate. Find indices that are less than the input J
0)       % Pick the last index.
)        % Apply as index to obtain input value that ends previous block
Q        % Add 1: start of current block
2M       % Push the two arguments to second-to-last function call
Q)       % Add 1 and use as index: end of current block
&:       % Inclusive binary range: generate input block
J        % Push J (input to function 2)
6M-      % Subtract start of block
)        % Apply as index (1-based, modular). This realizes the shifting

         % FUNCTION 3
2/       % Divide by 2
ttk>     % Duplicate. 1 if decimal part is not 0; 0 otherwise
Eq       % Multiply by 2, add 1
*        % Multiply
k        % Round down
         % Implicit display


Pyth, 38 32 bytes

VQJK1FZacN1k XKH]Z=KZ;WJ=JO@HJpJ

Thanks to FryAmTheEggman for 5 bytes!
To be honest I started writing Python answer when I noticed somebody posted a very similiar one so I decided to challenge myself with something new so I rewrote my answer (which was basically Pietu's answer) in Pyth.

Input is an array of strings ["Mary" , "had" , "a" , "little"]


Perl, 101 98 bytes

Includes +4 for -0p

Run with the input on STDIN

tictactoe.pl
OXO
---
--X
^D

Output is the same diagram, but with each move updated with its status, 1 represents a win, 2 represents a draw and 3 represents a loss. For this case that would be

OXO
223
21X

so 3 moves draw, 1 wins and 1 loses
(I'll update the solution if this output format is unacceptable, but the basic code will remain the same)

tictactoe.pl:

#!/usr/bin/perl -0p
m%@{[map"O.{$_}"x"@-"."O|",1-/.(
)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2

This is already painfully slow and uses lots of memory for the empty 3*3 board (why actually, the recursion doesn't go that deep. Must be some memory leak). Adding memoizing costs 6 bytes but is a lot saner:

#!/usr/bin/perl -0p
$$_||=m%@{[map"O.{$_}"x"@-"."O|",1-/.(\n)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2


MATL, 53 bytes
j61tthYX'+-*/'X{Y@!"t'ABCD'!XKX{@YXU?K@Y}hwxKGm1L3$).

Uses current version (10.1.0)
EDIT (June 12, 2016): to adapt to changes in the language, replace Y} by g and 1L3$) by Y). The link below incorporates those modifications
Try it online!
Explanation
This tests all possible permutations of the four operators in a loop until one permutation makes all equations true.
To test if equations are true, a regex is applied to replace the four letters by the operators (in the order dictated by the current permutation), and the string is converted to numbers (evaluated). This gives an array with as many numbers as equations, in which equations that are true become 1 and equations that are false become 0. If this vector only contains 1 values, we're done.
The solution found assigns operators to the four letters, but not all of them necessarily appear in the input. So a final test is done to discard not used letters (and their matching operators).
j            % input data string
61           % '=' (ASCII)
tth          % duplicate twice and concat: '==' (ASCII)
YX           % regexprep to change '=' into '==' in input string
'+-*/'       % push string
X{           % transform into cell array {'+','-','*','/'}
Y@!          % all permutations, each in a column
"            % "for" loop. Iterate columns (that is, permutations)
  t          %   duplicate data string containing '=='
  'ABCD'!XK  %   create column array ['A';'B';'C';'D'] and copy to clipboard K
  X{         %   transform into column cell array {'A';'B';'C';'D'}
  @          %   push column cell array with current permutation of operator symbols
  YX         %   regexprep. Replaces 'A',...,'D' with current permutation of operators
  U          %   convert to numbers, i.e. evaluate string
  ?          %   if all numbers are 1 (truthy result): found it! But before breaking...
    K        %     push column array ['A';'B';'C';'D']
    @Y}      %     push column array with current permutation of operator symbols
    h        %     concatenate horizontally into 4x2 char array
    wx       %     delete original input so it won't be displayed
    K        %     push ['A';'B';'C';'D']
    G        %     push input string
    m        %     logical index that tells which of 'A',...,'D' were in input string
    1L3$)    %     apply that index to select rows of the 4x2 char array
    .        %     we can now break "for" loop
             %   implicitly end "if"
             % implicitly end "for"
             % implicitly display stack contents


Haskell, 74 bytes

a%b|let a?i|a<1=0^(i-b)^2|d<-a-1=div(i*d?(i-1)-(d-i)*d?i)a=map(a?)[1..a+b]

Try it online!

Uses a recursive formulation I found. Let \$g_b(a,i)\$ be the coefficient of \$p_i\$ in \$p_a p_b\$, which is implemented in the code by a?i (with b fixed). We can express \$g_b\$ recursively as

$$g_b(a,i)=\frac{i\cdot g_b(a-1,i-1)-(a-1-i)\cdot g_b(a-1,i-1)}{a}$$

with base case
$$g_b(0,i)=
\begin{cases}
1,\text{ if }b=i\\
0,\text{ otherwise}\\
\end{cases}
$$

The base case corresponds to the expansion for \$p_b\$, which has a single nonzero coefficient of \$p_i\$ at \$i=b\$. The code implements this indicator function as 0^(i-b)^2.

The code has guards belonging to the definition of ? in the let binding. It's perhaps easier to read as the following (non-working) code where the definition of a?i expects b as a global variable. Perhaps confusingly, the a in the definition of ? is not always the same as the input to %, since it recurses down.

a?i|a<1=0^(i-b)^2|d<-a-1=div(i*d?(i-1)-(d-i)*d?i)a
a%b=map(a?)[1..a+b]

The main function % lists the coefficients for each i from 1 to a+b. It's possible to code the recursion in % directly by zipping shifted lists, but I did not find a short way to do it especially with the dependence on the position i.


Jelly, 8 bytes

ị“+×*_”v

Try it online!

How it works

Firstly, notice that x&3 is equivalent to x%4, where % is modulo. Then, since Jelly uses modular indexing (a[n] == a[n+len(a)]), so we don't even need to deal with that.

Then:

If x%4==0, return x_x (subtraction) (for consistency);
If x%4==1, return x+x;
If x%4==2, return x×x(multiplication);
If x%4==3, return x*x(exponentiation)

Note that Jelly uses 1-indexing, so the subtraction "_" is moved to the end.

ị“+×*_”v  example input: 10
ị“+×*_”   index 10 of the string “+×*_”, which gives "×"
       v  evaluate the above as a Jelly expression,
          with 10 as the argument, meaning "10×" is the
          expression evaluated. The dyad "×" takes the
          second argument from the only argument, effectively
          performing the function to itself.


Use ' (quote) as synonym for "" for single words.

Quote stops evaluation of symbol, allowing you to e.g. print it. Note that the casing is dependant on *print-case* variable (most of the time it's in the upcase).

(print"yes")
(print'yes) ; saved a byte!


V, 20 bytes

123i\  \__ò70|lé
4x

Try it online!

As usual, here is a hexdump:

0000000: 3132 3369 5c20 205c 5f5f 1bf2 3730 7c6c  123i\  \__..70|l
0000010: e90a 3478                                ..4x

Explanation:

123                     " 123 times:
   i                    " Insert the following:
    \  \__              " '\  \__'
          <esc>         " Return to normal mode
               ò        " Recursively:
                70|     "   Move to the 70th column
                   l    "   Move one char over
                    é   "   Insert a single newline
4x                      "   Delete 4 characters


Husk, 16 13 11 bytes
ṁḋ↔Θ↑←¡ȯ←Lḋ

Try it online!
Outputs a flat boolean array.
-2 using the idea from Jonathan Allan's answer.
Explanation
ṁḋ↔Θ↑←¡ȯ←Lḋ
      ¡ȯ    create an infinite list using:
         Lḋ length of binary digits
        ←   decremented
    ↑       take the longest prefix with:
     ←       elements that aren't falsy when decremented(1)
   Θ        prepend 0 to that
  ↔         reverse
ṁḋ          convert each to binary and flatten


JavaScript (ES6),  92 88 61  59 bytes
Saved 2 bytes thanks to a suggestion from @tsh
Expects UdLRAB for the dance moves and . for waiting. Outputs either undefined if there's no match, or the sequence of the matching dance (e.g. dR for Monkey or dURLAB for Water Town).

s=>(/d([A-R]|U(U|A|LR|RLAB|RRBA|LLBA|BLBR))/.exec(s)||0)[0]

Try it online!
or Try it with enhanced output


Python 2 - 181 bytes

It turns the abbreviated string into a regex and attempts to match groups from the search list.

The ternary operation if and elses are 14 bytes. I've tried to cut it down into a list and then accessing one of the items based on the state of r, but don't have anything shorter that this yet.

import re
def s(a,l):
 r=[m.group(1)for e in l for m in[re.compile('^('+a.replace(' ','\w+ ')+'\w+)$').search(e)]if m]
 print','.join(r)+'?'if len(r)>1 else r[0]if r else'Not found'

Call with s(str, list):

s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger'])
>>> chicken nuggets
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger', 'chicken nuggets with sauce', 'foobar'])
>>> chicken nuggets
s('c n', ['chicken burger', 'chicken nuggets', 'cheeseburger', 'chicken nuggets with sauce', 'foobar', 'cfoo nbar'])
>>> chicken nuggets,cfoo nbar?


Jelly, 71 65 bytes

J4Ṭ;-+ʋ€ịṭ@Wẋ¥€3ṭœcJ;2/Ṣṭ,`Ɗ€€ƲḊ,UṢƑ€o\ƲI,I$E€ƊIỊẠƊ3ƭ€€€»/€¬µ5ƤFS

Try it online!

A monadic link taking a list if integers and returning an integer. I’m sure this can be shortened further.

Explanation

...µ5Ƥ   | Run the main chain (below) for each 5-integer-long infix of the list
      F  | Flatten list
       S | Sum

Main chain

This generates the lists for the each set of tests. To deal with the variation in test 3, there are 3 copies made of each innermost list. For the first and second sets of tests, the last copy of each innermost list is sorted, while for the third set of tests it is not.

Main chain part 1 (generates swapped lists for third set of tests)

J                | Sequence along list [1,2,3,4,5]
 4    ʋ€         | Do the following as a dyad for each of 1,2,3,4 with 1,2,3,4,5 as the right argument:
  Ṭ              | - Convert to logical list with 1 at the relevant index [[1],[0,1],[0,0,1],[0,0,0,1]]
   ;-            | - Concatenate -1 to this
     +           | - Add (to [1,2,3,4,5])
        ị        | Index into original list
         ṭ@      | Tack onto end the original list
           Wẋ¥€3 | Repeat each inner list 3 times

Main chain part 2 (generates lists for first and second sets of tests)

ṭ             Ʋ  | Tack output of part 1 onto the following:
 œcJ             | - Combinations of lengths 1,2,3,4,5
    ;2/          | - Pairwise reduce using concatenation
           Ɗ€€   | - Following as a monad for each innermost list:
       Ṣ         |   - Sort
        ṭ,`      |   - Tacked onto the list paired with itself
               Ḋ | - Remove first (i.e. the combinations of lengths 1 and 2)

Main chain part 3 (runs the tests)

                   3ƭ€€€     | For each innermost list, do one of the following three in turn:
       Ʋ                     | - Tests 1 and 2
,U                           |   - Pair with reversed list
  ṢƑ€                        |   - Check whether each invariant if sorted
     o\                      |   - Cumulative or
              Ɗ              | - Tests 4 and 5
        I                    |   - Increments (test 4)
         ,I$                 |   - Paired with increments of increments (test 5)
            E€               |   - Check if all equal for each of these
                  Ɗ          | - Test 3
               I             |   - Increments
                Ị            |   - Absolute value <= 1
                 Ạ           |   - All
                        »/€  | Reduce each using max - picks the best results for each test for each set of tests
                           ¬ | Not (vectorises)