text:
Golf a Brain-Flak Integer
Integers are tedious to represent in Brain-Flak. There are 8 operators:
()      Evaluates to 1, but does not push anything on any stack
[]      Evaluates to an indeterminate value for the purposes of this question
{}      Removes the top of the stack and evaluates to it
<>      Switches to or back from the alternate stack and evaluates to zero
(foo)   Pushes the value of the expression foo to the stack and evaluates to it
[foo]   Evaluates to the negation of foo
{foo}   Evaluates the expression foo until the top of the stack is zero
<foo>   Evaluates to zero but executes foo anyway

foo may consist of multiple operators, in which case they are evaluated and summed. For example (()()) pushes 2 to the stack (and evaluates to 2 too).
Obviously, the (()...()) mechanism is not useful in Code Golf as large numbers would take n*2+2 bytes to represent. Your challenge is therefore to write a program or function that will output in as few bytes as possible a Brain-Flak program that will push a given positive integer n to the active stack. This program must not make any assumptions about the existing contents of the stacks, so it must not leave the stacks exchanged or add or remove extra values from the stacks.
Although your program or function must be capable of returning a working Brain-Flak program for all inputs from 1 to 1,000,000 the winner will be the program or function that generates the smallest set of appropriate Brain-Flak programs for all 1061 prime numbers between 1,000 and 10,000. You should note the total size of your outputs for those 1061 inputs as part of your submission. Your program or function may accept the integer and return the (string) Brain-Flak program in any of the usual acceptable I/O formats. Ties will be broken using the size of your program or function.

Just as a note: the number of valid programs of length 2n is 4^n catalan(n).

Hmm, I like the challenge, but I think it should be scored on unknown integers. Otherwise, the integers programs are scored upon could be brute forced and other integers just left as (()()()...()). Plus, if you just use prime numbers, that might miss out on some optimizations possible for composites.

Also, why is [] undefined for this challenge? I find it strange to implement 7 of the 8 operators. Either way, cool challenge, I'm honored someone would write a challenge inspired by my own language!

@DJMcMayhem I want people to be able to compute their own score. All relevant prime numbers are one more than a composite number, so there should be plenty of potential optimisations. Also, I don't want people to rely on a particular value of [] in their answer.

@EamonOlive I went for pushing n to the stack because that way it works as a standalone program that prints n.

Is source code compression (specifically Phar) allowed?

@YetiCGN How would it be a working Brain-Flak program if you compressed it?

You can add a PHP script to a Phar (php archive) with gzip or bzip2 compression that will run and output the Brain-Flak program. It's the PHP script that's compressed, but you can run it with php brainflak.phar <input>. Or did I misread the question and it's ONLY the Brain-Flak programs' codesize for each of the prime numbers that counts and not the original language's codesize?

@YetiCGN The script's size only counts as a tie-breaker.

Python 2, 59394 59244 58534 58416 58394 58250
Ok here is my solution.
import re
import math

cache = {0:"<()>"}

def find(x,i,j):
    return i*((x**2+x)/2)+(j+1)*((x**2-x)/2)

def solve(x, i, j):
    a = (i + j + 1)/2.
    b = (i - j - 1)/2.
    c = -x
    return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)

def size(i,j=0):
    return 4*(i+j)+14

def polynomials(n):
    upperBound = int(4*math.log(n,2))
    i = 0
    answers = []
    while size(i) < upperBound:
        for j in range(i):
            sol = int(solve(n, i-j, j)+.5)
            if find(sol, i-j, j) == n:
                answers.append((sol, i-j, j))
        i += 1
    return answers

def complement(character):
        dict = {"(":")","{":"}","<":">","[":"]",")":"(","}":"{",">":"<","]":"["}
        return dict[character]

def findMatch(snippet, index):
        increment = 1 if snippet[index] in "({<[" else -1
        stack = []
        if snippet[index] in "(){}<>[]":
                stack.append(snippet[index])
        while len(stack) > 0 and index + increment < len(snippet):
                index += increment
                if snippet[index] in "(){}<>[]":
                        if complement(snippet[index]) == stack[-1]:
                                stack = stack[:-1]
                        else:
                                stack.append(snippet[index])
        return index

def isPrime(n):
    return not [0 for x in range(2,int(n**.5)+1) if n%x==0] and n>1

def getPrimeFactors(n):
    return [x for x in range(2,n/2) if n%x==0 and isPrime(x)]

def divHardcode(n,m):
    assert n%m == 0
    assert m != 1
    assert n != 1
    binary = bin(m)[3:]
    return (binary.count("1")+len(binary))*"("+getBF(n/m)+")"*binary.count("1")+binary.replace("1","){}{}").replace("0","){}")

def isTriangular(n):
    #Triangles must be between sqrt(2n) and cbrt(2n)
    if n < 0: return isTriangular(-n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return True
    return False

def getTriangle(n):
    if n < 0: return -getTriangle(-n)
    #Triangles must be between sqrt(2n) and cbrt(2n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return x
    #If we don't find one we made a mistake
    assert False

def getSimpleBF(n):
    if n in cache:return cache[n]
    if n < 0:
        # There is room for better solutions here
        return "["+getSimpleBF(-n)+"]"
    elif n == 0:
        return ""
    elif n < 6:
        return "()"*n
    #Non-edge cases
    solutions = []
    factors = getPrimeFactors(n)
    if n >= 78 and isTriangular(n):
        solutions.append(
           min([push(getTriangle(n))+"{({}[()])}{}","<"+push(getTriangle(n)+1)+">{({}[()])}{}"],key=len)
        )
    polynomialSolutions = polynomials(n)
    for polynomial in polynomialSolutions:
        solutions.append("<%s>{%s({}[()])%s}{}"%(push(polynomial[0]),"({})"*polynomial[1],"({})"*polynomial[2]))
        #Mod 3 tricks
    if n % 3 == 2:
       solutions.append(("((%s)()){}{}")%getBF(n/3))
    elif n % 3 == 1:
       solutions.append(("((%s)()()){}{}")%getBF(n/3-1))
    #Basic solutions
    if isPrime(n):
        solutions.append(getSimpleBF(n-1) + "()")
    else:
        #TODO multithread
        solutions += map(lambda m:divHardcode(n,m),factors)
    return min(solutions,key=lambda x:len(unpack(x)))

def getBF(n):
    if n in cache: return cache[n]
    result = getSimpleBF(n)
    index = n - 1
    while index > n-(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index -= 1
    index = n + 1
    while index < n+(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index += 1
    cache[n] = result
    return result

def unpack(string):
    reMatch = re.match("\(*<",string)
    if reMatch:
        location =reMatch.span()
        return string[location[1]:findMatch(string,location[1]-1)] +string[:location[1]-1] + string[findMatch(string,location[1]-1)+1:]
    return string

def push(n):
    return unpack("("+getBF(n)+")")

def kolmo(string):
    code = push(ord(string[-1]))
    stringVector = map(ord,string)
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

def kolmo(stringVector):
    code = push(stringVector[-1])
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

if __name__ == "__main__":
    import primes
    sum = 0
    for prime in primes.nums:
        print push(prime)
        sum += len(push(prime))
    print sum

The relevant function is push(n). To call it simply call push on the integer you wish to represent.
Explanation
The main optimization done by the program is multiplication hard-coding.  The idea of multiplication hardcoding is pretty simple.  You push the a number and then pop and push it to create a new value.  For example to multiply by two you can use the following code ((n){}) where n code producing a specific number.  This works because both (n) and {} have a value of n.
This simple idea can be made more complex for larger numbers.  Take for instance 5 it was discovered a while ago that the best way to multiply by five was (((n)){}){}{}.  This code makes two copies of the n multiplies one by 4 and adds the two.  Using the same strategy I make every multiplication based on a number's binary representation.  I won't get into the details of how this works right now but I do this by chopping off the first one of the binary representation and replacing 0 with ){} and 1 with ){}{}.  It then makes sure that n is pushed the appropriate number of times and balances all the parentheses.  (If you want to know how this is done you can look at my code).  If you want to know why this works just ask me in a comment.  I don't think anyone actually reads all the updates to my post so I left the explanation out.
When the algorithm attempts to find a multiplication hardcode it attempts all of a numbers prime factors.  It ignores composite factors because at one point composite factors could always be expressed more concisely as its own prime factors it is not known if this is still true.
The other byte saving mechanism is a polynomial solution finder.  There are certain forms of polynomials that are easy to represent with decrementing loops.  These polynomials include, but are not limited to, polygonal numbers. This optimization finds polynomials that fit the form and creates the code that makes them.
Output
paste-bin

"whether n is larger or smaller than n+1"??

@Sparr whether the interpretation of n is larger or smaller than n+1

You should unindent the lines from if n % 3 == 2:  to the end of that function by one level.

Brain-Flak, 64664
Try it Online!
Here is my annotated code
({}<
 ((((()()()()()){}){}){}()) #41
>)
{
 (({})[()()()()()()])
 ([({}<(())>)](<>)){({}())<>}{}<>{}{}<>(({})){(<{}({}<>)>)}{}({}<>)
 {((< #IF
  {}
  {({}[()]< #FOR
   ((((()()()()()){}){}){}()) #41
   (({})[()])                 #40
  >)}{}
 >))}{}
 (({}))
 #MOD2
 {(<
  ({}<(())>)({<({}[()]<>)><>(()[{}])<><({}<>)>}{}<({}<>)><>)<>({}<>)
  {((<{}({}< #IF
   {}
   (((()()()()())({})({})({}){})({})({})({}){})  #125
   (({})[()()])                                  #123
   ((((()()()()()){}){}){}())                    #41
   <>
   ((((()()()()()){}){}){})                      #40
   <>
   >)

  >))}{}{}
 >)}{}
 #MOD2 (number 2)
 (({}))
 ({}(())){({}[()]<>)<>(()[{}])<>({}<>)}{}
 (({})<([{}]{})>)
 {
  ({}[()]<<>
    ((((()()()()()){}){}){}) #40
    (({})())                 #41
   <>>)
 }{}
}{}
<>{({}<>)<>}<>((((()()()()()){}){}){})

Explanation
This only implements two rules as of now:

If n is divisible by two return (n/2){}
If n is not divisible by two return n-1()

It also hardcodes all the numbers smaller than 6.

Seems like a check for divisibility by three should reduce score by quite a bit

@ASCII-only I actually implemented it and it increased the byte count.  I am working on a way of implement a smarter version of divisibility by three.

Ok, using Brain-Flak to make a program that generates Brain-Frak numbers. Nice.

Perl, 59222 59156 58460 characters

n() (11322660 characters)
(n){}() (64664 characters)
((n)){}{} (63610 characters)
((n)()){}{} (63484 characters) - this is a novel calculation
(n){({}[()])}{} (60748 characters)
n[m] (62800 characters)
(n){m({}[l])}{} (58460 characters) - this is a novel calculation

The formula for that last calculation is n(n/l+1)/2+mn/l. I've tried some other calculations but they are no longer helpful for the given output. The program actually generates all the values up to 9999 but then lists the given prime numbers and their total length.
@primes = (<list of the 4-digit prime numbers here>);
@numbers = ();
for ($i = 1; $i < 10000; $i++) {
  $numbers[$i] = "()" x $i; # default calculation
}
for ($i = 2; $i < 10000; $i++) {
  for ($j = 1; $j < 8; $j++) {
    &try($i, "$numbers[$i+$j]\[$numbers[$j]]");
  }
  &try($i + 1, "$numbers[$i]()");
  &try($i * 2, "($numbers[$i]){}");
  &try($i * 3, "(($numbers[$i])){}{}");
  &try($i * 3 + 2, "(($numbers[$i])()){}{}");
  for ($l = 1; $l * $l < $i; $l++) {
    unless ($i % $l) {
      for ($j = 0; ($k = (($i + $j + $j) * $i / $l + $i) / 2) < 10000; $j++) {
        &try($k, "($numbers[$i]){$numbers[$j]({}[$numbers[$l]])}{}");
      }
    }
  }
}
$len = 0;
foreach (@primes) {
  print "($numbers[$_])\n";
  $len += 2 + length $numbers[$_];
}
print "$len\n";
sub try {
  ($n, $s) = @_;
  $numbers[$n] = $s if (length($numbers[$n]) > length $s);
}

Could you provide a link to the output?

@DJMcMayhem Oops, I'd accidentally corrupted my list of primes, invalidating my character count.

@Linus ((X)()){}{} pushes X, then adds 1, pushes the result, then pops the X+1 and X. Total 3X+2. I think I tried the other formula on Try It Online but I can double-check if you like.

@Neil My mistake... These look good but what exactly corrupts your primes then?

@Linus Oh that? Copy/paste error...

So, I've been planning on writing a web-app for brain-flak integer metagolf to make it more convenient/portable. Since this answer has the best score, I'd love to copy its algorithm for the web-app. Would you mind? I'd give you credit for it.

@DJMcMayhem Sure, that's fine.

@Neil I get 58158 when I add &try($i * $i, "$numbers[$i]{({})({}[()])}{}");, which goes down to 58032 when I also add &try((3 * $i * $i - $i) / 2, "$numbers[$i]{({})({}[()])({})}{}"); (square/pentagonal numbers) - it's from here

My bad, it should be $numbers[$i])({({})({}[()])}{} and $numbers[$i])({({})({}[()])({})}{}

@ASCII-only )(? How does that work?

@Neil When you add the outer () it becomes a chained ()(), enter a square number like 1048576 here to see an example

@ASCII-only But then I would have to take care not to use it inside (n){m({}[l])}{}.

@Neil If I'm correct, that can be solved by having an array of safe values (filled with a falsy value by default). You would then call tryunsafe, which would replace $safe[$n] with $numbers[$n] if $safe[$n] is still falsy, and use e.g. $safe[$j] || $numbers[$j] for the loop with $l (sorry, don't know perl logical operators/logical operator behavior so this may not be correct)

&tryunsafe("$numbers[$i])({({})({})({}[()])}{}") should reduce the bytecount to 57870 if the other two are implemented as well

@ASCII-only What's the formula for that last one?

@Neil (3 * $i * $i + $i) / 2, see Wheat Wizard's solution for more details (this is pentagonal numbers for negative values)

Let us continue this discussion in chat.

Lua 5.3, 57522
I actually started working on this back when the question was posted, but forgot about it until the Brain-Flak anniversary.
-- 64 gives all results through 10000 (should run in about 1 second)
-- 78 gives all results through 100000 (should run in about 20 seconds)
-- 90 gives all results through 1000000 (should run in about 200 seconds)
-- Note: Timings may not be accurate, as the are not updated every time new cases are added.

local k_max_len = 64
local k_limit = 10000

local pre = os.clock()

local function compute_multiplier_helper(prefix, suffix, m)
  if m == 2 then
    prefix[#prefix + 1] = "("
    suffix[#suffix + 1] = "){}"
  elseif m % 2 == 0 then
    prefix[#prefix + 1] = "("
    compute_multiplier_helper(prefix, suffix, m // 2)
    suffix[#suffix + 1] = "){}"
  else
    suffix[#suffix + 1] = ")"
    compute_multiplier_helper(prefix, suffix, m - 1)
    prefix[#prefix + 1] = "("
    suffix[#suffix + 1] = "{}"
  end
end

local function compute_multiplier(m)
  local prefix = {}
  local suffix = {}
  compute_multiplier_helper(prefix, suffix, m)
  return table.concat(prefix), table.concat(suffix)
end

local multipliers = {}
for m = 2, k_limit do
  -- Including all factors, not just primes.
  -- This did improve a few numbers, although none in the ppcg test set.
  local prefix, suffix = compute_multiplier(m)
  local mult = {prefix = prefix, suffix = suffix, m = m, cost = #prefix + #suffix}
  table.insert(multipliers, mult)
end
table.sort(multipliers, function(a, b) return a.cost < b.cost end)

local poly_multipliers = {}
poly_multipliers[1] = {m = 1, s = "({})", l = 4}
for m = 2, k_limit do
  local prefix, suffix = compute_multiplier(m)
  local s = prefix .. "({})" .. suffix
  assert(#s <= 4 * m)
  poly_multipliers[m] = {m = m, s = s, l = #s}
end
poly_multipliers[k_limit + 1] = {m = 0, s = "", l = 0}

table.sort(poly_multipliers, function(a, b) return a.l < b.l end)

local pcache = {}
local plen_cache = {}

local function register_push(prefix, suffix, value, pvalue)
  if value > 1500000 or value < -1500000 then return end
  local old_res = pcache[value]
  if old_res == nil then
    local res = {prefix = prefix, suffix = suffix, value = value, pvalue = pvalue}
    pcache[value] = res
    local length = #prefix + #suffix
    local lcache = plen_cache[length]
    if lcache == nil then
      lcache = {}
      plen_cache[length] = lcache
    end
    lcache[#lcache + 1] = res
  end
end

local function get_pushes(length)
  return ipairs(plen_cache[length] or {})
end

register_push("", "()", 1, 0)
register_push("", "<()>", 0, 0)

local function triangle(n)
  return (n * (n + 1)) // 2
end

local function process(length)
  -- basic
  for _, res in get_pushes(length - 2) do
    register_push(res.prefix, res.suffix .. "()", res.value + 1, res.pvalue)
    register_push(res.prefix, "[" .. res.suffix .. "]", -res.value, res.pvalue)
  end

  -- multiplication by constant (precomputed)
  for _, mult in ipairs(multipliers) do
    local cost = mult.cost
    if length - cost >= 4 then
      local m, prefix, suffix = mult.m, mult.prefix, mult.suffix
      for _, pus in get_pushes(length - cost) do
        local name = prefix .. pus.suffix .. suffix
        register_push(pus.prefix, name, pus.value * m, pus.pvalue)
      end
    else
      break
    end
  end

  -- residue 2 mod3 trick (Neil)
  -- ((n)()){}{}
  --  (n)        -- push n
  -- (   ())     -- push n + 1
  --        {}{} -- (n + 1) + (n + 1) + n
  if length - 10 >= 2 then
    for _, res in get_pushes(length - 10) do
      local name = "((" .. res.suffix .. ")()){}{}"
      register_push(res.prefix, name, 3 * res.value + 2, res.pvalue)
    end
  end

  -- residue 1 mod3 trick (Wheat Wizard)
  -- ((n)()()){}{}
  --  (n)          -- push n
  -- (   ()())     -- push n + 2
  --          {}{} -- (n + 2) + (n + 2) + n
  -- not useful, but fast...
  if length - 12 >= 2 then
    for _, res in get_pushes(length - 12) do
      local name = "((" .. res.suffix .. ")()()){}{}"
      register_push(res.prefix, name, 3 * res.value + 4, res.pvalue)
    end
  end

  -- residue 2 mod5 trick (tehtmi)
  -- (((n)){}()){}{}
  --   (n)           -- push n
  --  (   )          -- push n
  -- (     {}())     -- push 2n + 1
  --            {}{} -- (2n + 1) + (2n + 1) + n
  -- [[
  if length - 14 >= 2 then
    for _, res in get_pushes(length - 14) do
      local name = "(((" .. res.suffix .. ")){}()){}{}"
      register_push(res.prefix, name, 5 * res.value + 2, res.pvalue)
    end
  end
  -- ]]

  -- residue 4 mod5 trick (tehtmi)
  -- (((n)()){}){}{}
  --   (n)           -- push n
  --  (   ())        -- push n + 1
  -- (       {})     -- push 2n + 2
  --            {}{} -- (2n + 2) + (2n + 2) + n
  -- [[
  if length - 14 >= 2 then
    for _, res in get_pushes(length - 14) do
      local name = "(((" .. res.suffix .. ")()){}){}{}"
      register_push(res.prefix, name, 5 * res.value + 4, res.pvalue)
    end
  end
  -- ]]

  -- residue 6 mod7 trick (tehtmi)
  -- ((((n)())){}{}){}{}
  --    (n)              -- push n
  --   (   ())           -- push n + 1
  --  (       )          -- push n + 1
  -- (         {}{})     -- push 3n + 3
  --                {}{} -- (3n + 3) + (3n + 3) + n
  -- [[
  if length - 18 >= 2 then
    for _, res in get_pushes(length - 18) do
      local name = "((((" .. res.suffix .. ")())){}{}){}{}"
      register_push(res.prefix, name, 7 * res.value + 6, res.pvalue)
    end
  end
  --]]

  -- residue 4 mod7 trick (tehtmi)
  -- ((((n))()){}{}){}{}
  --    (n)              -- push n
  --   (   )             -- push n
  --  (     ())          -- push n + 1
  -- (         {}{})     -- push 3n + 2
  --                {}{} -- (3n + 2) + (3n + 2) + n
  -- [[
  if length - 18 >= 2 then
    for _, res in get_pushes(length - 18) do
      local name = "((((" .. res.suffix .. "))()){}{}){}{}"
      register_push(res.prefix, name, 7 * res.value + 4, res.pvalue)
    end
  end
  --]]

  -- residue 2 mod7 trick (tehtmi)
  -- ((((n))){}{}()){}{}
  --    (n)              -- push n
  --   (   )             -- push n
  --  (     )            -- push n
  -- (       {}{}())     -- push 3n + 1
  --                {}{} -- (3n + 1) + (3n + 1) + n
  -- [[
  if length - 18 >= 2 then
    for _, res in get_pushes(length - 18) do
      local name = "((((" .. res.suffix .. "))){}{}()){}{}"
      register_push(res.prefix, name, 7 * res.value + 2, res.pvalue)
    end
  end
  --]]

  -- triangle numbers (?)
  --(n){({}[()])}{}
  --(n)              -- push n
  --   {        }    -- sum and repeat
  --    (      )     -- push
  --     {}[()]      -- top - 1
  --             {}  -- pop 0
  if length - 14 >= 2 then
    for _, res in get_pushes(length - 14) do
      if res.value > 0 then
        local code = "{({}[()])}{}"
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, triangle(res.value - 1), res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, triangle(res.value), res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, triangle(res.value) + res.pvalue, 0)
      end
    end
  end

  -- negative triangle numbers (tehtmi)
  --(n){({}())}{}
  --(n)            -- push n
  --   {      }    -- sum and repeat
  --    (    )     -- push
  --     {}()      -- top + 1
  --           {}  -- pop 0
  if length - 12 >= 2 then
    for _, res in get_pushes(length - 12) do
      if res.value < 0 then
        local code = "{({}())}{}"
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, -triangle(-res.value - 1), res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, -triangle(-res.value), res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, -triangle(-res.value) + res.pvalue, 0)
      end
    end
  end

  -- cubic (tehtmi)
  -- (n){(({}[()])){({}[()])}{}}{}
  -- (n^3-3*n^2+8*n-6)/6
  -- (-6 + n*(8 + n*(-3 + n)))/6
  --[[ superceded by negative cubic because
       it is the same cost of -ncubic(-n)
  if length - 28 >= 2 then
    for _, res in get_pushes(length - 28) do
      if res.value > 0 then
        local code = "{(({}[()])){({}[()])}{}}{}"
        local v = res.value + 1
        v = (-6 + v*(8 + v*(-3 + v)))//6
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, v - res.value, res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, v, res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, v + res.pvalue, 0)
      end
    end
  end
  --]]

  -- negative cubic (tehtmi)
  -- (n){(({}())){({}())}{}}{}
  -- (n^3-3*n^2+8*n-6)/6
  -- (-6 + n*(8 + n*(-3 + n)))/6
  -- [[
  if length - 24 >= 2 then
    for _, res in get_pushes(length - 24) do
      if res.value < 0 then
        local code = "{(({}())){({}())}{}}{}"
        local v = -res.value + 1
        v = (-6 + v*(8 + v*(-3 + v)))//6
        v = -v
        register_push(res.prefix .. "(" .. res.suffix .. ")", code, v - res.value, res.pvalue + res.value)
        register_push(res.prefix, "(" .. res.suffix .. ")" .. code, v, res.pvalue)
        register_push("", res.prefix .. "(" .. res.suffix .. ")" .. code, v + res.pvalue, 0)
      end
    end
  end
  --]]

  -- polynomial (Wheat Wizard, modified by tehtmi)
  -- <(n)>{A({}[()])B}{} where A, B are ({})({})({})... repeated a, b times
  -- <(n)>                -- push n (without adding)
  --      {          }    -- repeat until top is zero
  --       A              -- top * a
  --        ({}[()])      -- top = top - 1; += top - 1
  --                B     -- (top - 1) * b
  --                  {}  -- pop 0
  -- triangular numbers are with a = b = 0
  -- from B and base:
  -- (n - 1) * (B + 1) * (n - 2) * (B + 1) * ...
  -- (B + 1) * (1 + ... + n - 1)
  -- (B + 1) * n * (n - 1) / 2
  -- from A:
  -- n * A + (n - 1) * A + ...
  -- A * (1 + ... n)
  -- A * (n + 1) * n / 2
  -- total: (B + 1) * n * (n - 1) / 2 + A * (n + 1) * n / 2
  --        [(A + B + 1) * n^2 + (A - B - 1) * n] / 2
  -- S := 4 * (A + B)
  -- [[
  if length - 18 >= 2 then
    for S = 4, length - 14, 4 do
      for _, res in get_pushes(length - 14 - S) do
        if res.value > 0 then
          for _, A in ipairs(poly_multipliers) do
            if A.l > S then
              break
            end
            for _, B in ipairs(poly_multipliers) do
              if A.l + B.l < S then
                -- continue
              elseif A.l + B.l > S then
                break
              else
                local a = A.m
                local b = B.m

                local logic = "{" .. A.s .. "({}[()])" .. B.s .. "}{}"
                local v = res.value
                v = ((a + b + 1) * v * v + (a - b - 1) * v) // 2
                register_push(res.prefix .. "(" .. res.suffix .. ")", logic, v, res.pvalue + res.value)
                register_push(res.prefix, "(" .. res.suffix .. ")" .. logic, v + res.value, res.pvalue)
                register_push("", res.prefix .. "(" .. res.suffix .. ")" .. logic, v + res.value + res.pvalue, 0)
              end
            end
          end
        end
      end
    end
  end
  --]]

  -- negative polynomial (tehtmi)
  -- <(n)>{A({}())B}{}
  -- [[
  if length - 16 >= 2 then
    for S = 4, length - 12, 4 do
      for _, res in get_pushes(length - 12 - S) do
        if res.value < 0 then
          for _, A in ipairs(poly_multipliers) do
            if A.l > S then
              break
            end
            for _, B in ipairs(poly_multipliers) do
              if A.l + B.l < S then
                -- continue
              elseif A.l + B.l > S then
                break
              else
                local a = A.m
                local b = B.m

                local logic = "{" .. A.s .. "({}())" .. B.s .. "}{}"
                local v = -res.value
                v = ((a + b + 1) * v * v + (a - b - 1) * v) // -2

                register_push(res.prefix .. "(" .. res.suffix .. ")", logic, v, res.pvalue + res.value)
                register_push(res.prefix, "(" .. res.suffix .. ")" .. logic, v + res.value, res.pvalue)
                register_push("", res.prefix .. "(" .. res.suffix .. ")" .. logic, v + res.value + res.pvalue, 0)
              end
            end
          end
        end
      end
    end
  end
  --]]

  -- addition
  -- [[
  if length >= 4 then
    for part1 = 4, length // 2, 2 do
      for _, res1 in get_pushes(part1) do
        for _, res2 in get_pushes(length - part1) do
          register_push(res2.prefix .. res1.prefix, res1.suffix .. res2.suffix, res1.value + res2.value, res1.pvalue + res2.pvalue)
        end
      end
    end
  end
  --]]

  -- pseudo-exponentiation (tehtmi)
  -- (n)<>(m){({}[()])<>(({}){})<>}{}<>{}
  -- (n)<>(m)                             -- push n and m on opposite stacks
  --         {                    }       -- sum and repeat
  --          ({}[()])                    -- top(m) - 1
  --                  <>(({}){})<>        -- n = 2*n; += n
  --                               {}     -- pop 0
  --                                 <>   -- swap to result
  --                                   {} -- pop and add n
  -- [[
  if length - 34 >= 4 then
    local subl = length - 34
    for part1 = 2, subl - 2, 2 do
      for _, res2 in get_pushes(part1) do
        local b = res2.value
        if b > 0 and b < 55 then -- overflow could be a problem, so bound...
          for _, res1 in get_pushes(subl - part1) do
            -- 2n + 4n + 8n + ... + (2^m)*n + 2^m * n
            -- n( 2 + 4 + 8 + .. 2^m + 2^m)
            -- n( 3 * 2^m - 2 )
            local a = res1.value
            local body = "(" .. res1.suffix .. ")<>" .. res2.prefix .. "(" .. res2.suffix .. "){({}[()])<>(({}){})<>}{}<>{}"
            local v = a * (3 * (1 << b) - 2) + b * (b - 1) // 2 + a + b + res2.pvalue
            register_push(res1.prefix, body, v, res1.pvalue)
            register_push("", res1.prefix .. body, v + res1.pvalue, 0)
          end
        end
      end
    end
  end
  --]]
end

--print(os.clock(), "seconds (startup)")

local start = os.clock()
for i = 2, k_max_len - 2, 2 do
  --print(i)
  process(i)
end

plen_cache = nil

local final = {}
for i = 1, k_limit do
  if pcache[i] ~= nil then
    final[i] = pcache[i].prefix .. "(" .. pcache[i].suffix .. ")"
  end
end

pcache = nil

-- hard coded to 10000 for ppcg test
local sieve = {}
for i = 1, 10000 do sieve[i] = true end
for i = 2, 10000 do
  for j = i * i, 10000, i do
    sieve[j] = false
  end
end

--print(os.clock() - start, "seconds (calculation)")

--local bf = require("execute2")

local count = 0
local sum = 0
local sum2 = 0
local maxlen = 0
local pcount = 0
for i = 1, k_limit do
  local res = final[i]
  final[i] = nil
  --print(i, #res, res)
  --local ev = res and bf.eval1(bf.compile(res)) or -1; assert( res == nil or ev == i, string.format("Failed %d %s %d", i, res or "", ev))
  if sieve[i] and i > 1000 then
    sum = #res + sum
    pcount = pcount + 1
  end
  if res then
    sum2 = #res + sum2
    maxlen = math.max(maxlen, #res)
    count = count + 1
  end
end
print("sum", sum)
--print("coverage", count / k_limit, "missing", k_limit - count)
--print("sum2", sum2)
--print("maxlen", maxlen)
assert(pcount == 1061)

Similar idea to the other answers where known-useful functions are used to build up larger numbers from good representations of simpler numbers.
One difference is that instead of solving subproblems in terms of smaller numbers, I'm solving subproblems in terms of numbers with shorter representations. I think this makes it more elegant to take advantage of negative numbers as well as handling the case where smaller numbers are represented in terms of larger numbers.
Also, trying to find all numbers that can be represented in a certain size rather trying to represent a particular number as shortly as possible actually simplifies certain calculations. Instead of working a formula in reverse to see whether it can be applied to a number, the formula can be worked forwards and applied to every number.
Another difference is that known solutions are stored in two pieces -- an (optional) "prefix" and a "suffix" (more like an infix). The valuation of the prefix is expected to be ignored when calculating the given number -- the prefix just contains code that sets up the suffix to run (generally by pushing one or more things to the stack). So, given a prefix and a suffix, the corresponding number can be pushed onto the stack with prefix(suffix).
This split basically solves the same problem as the unpack function in Wheat Wizard's answer. Instead of wrapping code with <...> only to undo this later, such code is simply added to the prefix.
In a few cases, the prefix actually does get evaluated (mainly for the pseudo-exponentiation operation), so its valuation is also stored. However, this doesn't really cause a big problem, as the generator isn't trying to construct specific numbers. It seem to theoretically imply that there could be two pieces of code of the same length and generating the same number that wouldn't be redundant in the cache due to having different prefix valuations. I didn't bother accounting for this though, as it doesn't seem to matter much (at least in this domain).
I imagine it would be easy to whittle down the byte count just by adding more cases, but I've had enough for the moment.
I've run to 1000000, but only done sanity checking up to 100000.
Pastebin of output on given primes.

What do k_limit and k_max_len do?  I'm not sure I understand the header.

Rather than trying to calculate particular numbers, I'm calculating all useful (ie giving not-too-large numbers shorter than any other found program) programs up to a certain length -- k_max_len. It could as easily check that it has found all the numbers you asked for after processing each length, but it was useful for me to be able bound the max length during testing so the program would run faster. (Processing larger lengths can be very slow.) k_limit is basically the input parameter -- it will output programs for numbers up to this -- assuming k_max_len was large enough to find them.

Python, 59136 58676 characters
Brainflak number golfing function:
m=11111
R=range(0,m)
R[1]="()"
R[2]="()()"
l=2
def a(v,r):
 if v>0 and v<m:
  if isinstance(R[v],int) or len(r)<len(R[v]):
   R[v]=r
   if v<R[0]:
    R[0]=v
def s(v,k):
 S=0
 while v>0:
  S+=v
  v-=k
 return S
p=lambda r:"("+r+")"
w=lambda r:"{({}["+r+"])}{}"
def q(r,v):
 for i in range(1,v):
  r="("+r+")"
 for i in range(1,v):
  r+="{}"
 return r
def e(r,v,k):
 for i in range(0,k):
  r=q(r,v)
 return r
while l<m:
 R[0]=l+1
 a(l*2,q(R[l],2))
 a(l*3,q(R[l],3))
 a(l*5,q(R[l],5))
 a(l*7,q(R[l],7))
 for i in range(1,l):
  a(l+i,R[l]+R[i])
  a(l-i,R[l]+"["+R[i]+"]")
  if l%i==0:
   t=s(l-i,i)
   a(s(l,i),p(R[l])+w(R[i]))
   a(l+2*t,p(R[l])+q(w(R[i]),2))
   a(l+4*t,p(R[l])+e(w(R[i]),2,2))
   a(l+8*t,p(R[l])+e(w(R[i]),2,3))
   a(l+16*t,p(R[l])+e(w(R[i]),2,4))
   a(l+32*t,p(R[l])+e(w(R[i]),2,5))
   a(l+64*t,p(R[l])+e(w(R[i]),2,6))
   a(l+128*t,p(R[l])+e(w(R[i]),2,7))
   a(l+3*t,p(R[l])+q(w(R[i]),3))
   a(l+9*t,p(R[l])+e(w(R[i]),3,2))
   a(l+27*t,p(R[l])+e(w(R[i]),3,3))
   a(l+5*t,p(R[l])+q(w(R[i]),5))
   a(l+6*t,p(R[l])+q(q(w(R[i]),3),2))
   a(l+10*t,p(R[l])+q(q(w(R[i]),5),2))
   a(l+15*t,p(R[l])+q(q(w(R[i]),5),3))
   a(l+12*t,p(R[l])+q(q(q(w(R[i]),3),2),2))
   a(l+18*t,p(R[l])+q(q(q(w(R[i]),3),3),2))
   a(l+20*t,p(R[l])+q(q(q(w(R[i]),5),2),2))
   a(l+24*t,p(R[l])+q(q(q(q(w(R[i]),3),2),2),2))
   a(l+36*t,p(R[l])+q(q(q(q(w(R[i]),3),3),2),2))
   a(l+40*t,p(R[l])+q(q(q(q(w(R[i]),5),2),2),2))
 l=R[0]
f=lambda v:p(R[v])

Prime number iteration:
def isPrime(v):
 i=2
 while i*i<=v:
  if v%i==0:
   return False
  i+=1
 return True

for i in range(1000,10000):
 if isPrime(i):
  print f(i)

Output:
Pastebin
Explanation:
We pre-populate a list R of Brain-flak representation evaluating to individual integers over a larger than necessary range [1,m-1] to define our function f. The representations are formed by taking the lowest unused representation (indexed by l) and forming many new representations from it, keeping only the shortest. The lowest unused representation assumes that all number 1 to l have been assigned a representation, and that these representations have already been used to produce new numbers. If a value less than l gets a shorter representation we must go back and reproduce numbers beginning form that point. The function f produces a program saving the number to the stack by adding parenthesis.
I didn't know any Brainflak when I began this, and greatly appreciate Eamon Olive's answer for pointing out the formula for triangle numbers. Mostly I've generalized the summation and been relentless about checking sums and differences. Adding lots of multiples of sums has had a great effect.
For those who care, here is the scratch code I used to see which formulas were worth it.
Representation Formulas:

Multiplication by small primes:
(X){}
((X)){}{}
((((X)))){}{}{}{}
((((((X)))))){}{}{}{}{}{}
Addition X+Y:
XY
Subtraction X-Y:
X[Y]
Summation to and including X of increment Y:
(X){({}[Y])}{}
Multiples of summations to X of increment Y, plus X:
(X)({({}[Y])}{}){}
(X)(({({}[Y])}{})){}{}
(X)(({({}[Y])}{}){}){}
etc...

I thought 5* wasn't helpful, but I now see it saves 10 characters on my answer. I thought I'd tried those summations, but I'll double-check!

Summations of increments plus multiples saves me another 46 bytes, and even then I have to rinse and repeat three times to catch them all.

Turns out that if I use subtraction then I don't use 5* again.

ruby, 60246 bytes
$brain_flak = Hash.new{|h, k|
    a = []
    a.push "()"*k
    if k > 1
        if k > 10
            # Triangle Numbers:
            n = (Math.sqrt(1+8*k).to_i-1)/2
            if (n*n+n)/2 == k
                a.push "("+h[n]+"){({}[()])}{}"
                a.push  h[n+n]+")({({}[()])}{}"
            end
        end
        (k**0.51).to_i.downto(2){|i|
            # multiplication:
            if k%i==0
                a.push "("*(i-1) + h[k/i] + ")"*(i-1)+"{}"*(i-1)

            end
        }
        (k/2).downto(1){|i|
            # Addition
            a.push h[k-i] + h[i]
        }
    end

    h[k] = a.min_by{|x|x.length}
}
$brain_flak[0] = "<><>"

def get_code_for (i)
  "(#{$brain_flak[i]})"
end

I use a hash. I finds the best golf for a given number and uses the smaller ones to find the larger ones.
Recursive hashes are so much fun!

Python, 64014 characters
I didn't know anything about brainflak before this challenge and only fiddled around with it a bit on tryitonline, so there could be obvious shortcuts I missed. This is a quite boring solution, just splits the input into x=x/2+x%2 or x=x/3+x%3, whichever is shorter.
k=lambda x:"(("+o(x/3)+")){}{}"+(x%3)*"()"if x>3else"()"*x
m=lambda x:"("+o(x/2)+"){}"+(x%2)*"()"if x>6else"()"*x
o=lambda x:min(k(x),m(x),key=len)
b=lambda x:"("+o(x)+")"

Call it like so: b(42)
output on pastebin

Lua, 64664 bytes
Program prints the total length of the programs and the program for the 203rd prime (theres a line you can change to change which one is printed, or uncomment a line to print all the programs)
Right now the only optimization is x = 2*n + 1
Hopefully I will have time to add some more optimizations to lower the score.
local primeS = [[<INSERT PRIMES HERE>]]

local primes = {}

for num in primeS:gmatch("%d+") do
    table.insert(primes, num+0)
end

local progs = {}
progs[0] = ""
progs[1] = "()"
progs[2] = "()()"

local function half(n)
    if progs[n] then return progs[n] end
    local p = ""
    local div = math.floor(n/2)
    local rem = n%2 == 1 and "()" or ""
    return "("..progs[div].."){}"..rem
end

for i = 3, 10000 do

    local bin = half(i)

    progs[i] = progs[i-1] .. "()"

    if #bin < #progs[i] then
        progs[i] = bin
    end

    if i % 1000 == 0 then
        print(i)
    end

end

local n = 203 -- This is the program it outputs
print(n..", ("..progs[203]..")")

local len = 0
for i,v in ipairs(primes) do
    len = len + #progs[v] + 2
    --print(v.." ("..progs[v]..")\n")
end
print("Total len: "..len)

Husk, 64664, 35 bytes
?*"()"¹+*"()"%2¹`+"){}":'(₀½-%2¹¹<6

Try it online!
Husk is a golfing language so making a high scoring solution is a little hard, simply because long Husk code quickly becomes unwieldy.  I just gave this a shot to practice my Husk.
This implements the same algorithm as my Brain-Flak solution from earlier.


text:
Write a Sine-Deriving Machine
The Challenge
Your challenge is to write a program that evaluates the following function:
f(x, t) = d^x / dt^x (sin t)
That is, the x-th derivative of sin t. In case you aren't familiar with calculus, here is a table of derivatives for the sine function:
...
f(-1, t) = -cos t
f(0, t) = sin t
f(1, t) = cos t
f(2, t)= -sin  t
...
The sequence repeats these 4 functions.
The Inputs
Your program should take in an integer to be used as the x value in the function, and a float to be used at the t value in the function.
Your program may use radians or degrees for the sine function.
The Output
Your program should output the value of f(x, t) given the integer x and float t.
Scoring
This is code-golf, so the shortest answer (in bytes) wins.

Are you sure d^-1 / dt^-1 (sin t) = -cos t ?

What precision should this be to?

Test cases would be great.

Okay so trigonometry builtins seem to be allowed.
Just a comment, who is not familiar with calculus does not understand the table either :P

Today, I am more in the mood of writing an exponential function e^x deriving machine.

I think you should repeat the challenge forbidding the π/2 left shift technique!

Actually, 5 bytes
╦*½+S

Try it online
Takes input as t\nx.
Explanation:
╦*½+S
╦*     pi*n
  ½    half that
   +   add t
    S  sine

Python, 42 bytes
from math import*
lambda x,n:sin(x+pi/2*n)

Uses the fact that differentiating shifts the function by pi/2 left.

I'm such an idiot

C (gcc), 30 bytes
#define f(x,n)sin(x+n*acos(0))

Haskell, 16 bytes
x%n=sin$x+pi/2*n

Defines a binary operator %.
λ 2.0 % (-3)
-0.4161468365471426

Uses the fact that differentiating shifts the function by pi/2 left.
Making it point-free was longer (takes n x):
(sin.).(+).(pi/2*)

Convex (IDE version only), 6 bytes
P½*+ms

Try it online!
After futher investigation, with the help of Dennis in chat, it was found that the command-line version of Convex (what TIO uses) has a bug that breaks the code (the link above contains a workaround). However, the IDE version of Convex, avaliable on GitHub before the challenge was posted, does not have this bug. Here is a link to the IDE version that was avaliable before the challenge was posted: Convex IDE.

Mathematica 14 bytes
With help from Martin Ender,
Sin[#2+Pi/2#]&

Shouldn't x be #2?

At the same time, you don't need the *, so you'll end up with the same byte count.

J, 17 bytes
4 :'1&o.d.(4|x)y'

Computes the (x%4)th derivative of sine, and then apply to right argument.
Usage:
>> f =: 4 :'1&o.d.(4|x)y'
>> _1 0 1 2 3 (f"0 0) 0
<< _1 0 1 0 _1

where >> is STDIN and << is STDOUT.

Why do you need to compute the (x%4)? Wouldn't it be simpler to just use the xth derivative?  (Not a J user so this might be a stupid question)

@StevenH. Because stupid question requires negative numbers.

Julia, 17 bytes
x\t=x*π/2+t|>sin

Try it online!

Lua 5.x, 37 bytes
x,n=...return math.sin(x+math.pi/2*n)

usage:
> print(loadfile('sine.lua')(1,0))
0.8414709848079
> print(loadfile('sine.lua')(math.pi,0))
1.2246467991474e-16
> print(loadfile('sine.lua')(math.pi,1))
-1.0
> print(loadfile('sine.lua')(math.pi,2))
-2.4492935982947e-16
> print(loadfile('sine.lua')(math.pi,3))
1.0

Matlab, 19 bytes
@(x,t)sin(t+x*pi/2)

So why the downvote?

C (gcc), 53 46 45 bytes
#import<math.h>
#define f(x,n)sin(x+M_PI/2*n)

Probably Ideone doesn't have glibc, says M_PI is undeclared.

M_PI is not in math.h: http://stackoverflow.com/questions/5007925/using-m-pi-with-c89-standard.

But...it's there on glibc? https://sourceware.org/git/?p=glibc.git;a=blob;f=math/math.h;h=2f77deec87707721ed677def6e29341c9f9d3a06;hb=HEAD#l406

Not in "C", the language you specified in the top of your answer. C as implemented by gcc has it, so you can write "C (gcc)", but C is a language defined by an abstract standard, and makes no mention of M_PI.

R, 26 bytes
function(t,x)sin(t+pi/2*x)

Exactly what it says on the tin...

JavaScript (ES6), 29 bytes
x=>t=>Math.sin(t+Math.PI/2*x)

Usage:
f=x=>t=>Math.sin(t+Math.PI/2*x)
f(x)(t)

SQF, 29 bytes
Using the file-as-a-function format:
params["x","y"];sin(x+pi/2*y)

Call as [x, t] call NAME_OF_COMPILED_FUNCTION

SmileBASIC, 25 bytes
INPUT X,N?SIN(X+N*PI()/2)

Probably shorter in some BASIC dialect that has a constant named PI rather than PI(). (Yes, PI() is not actually a function, those parentheses are a lie.)

05AB1E, 7 bytes
žq*;+Å½

Port of @Mego♦'s Actually answer.
Try it online or verify some more test cases.
Explanation:
žq        # Push PI
  *       # Multiply it with the first (implicit) input `t`
   ;      # Halve it
    +     # Add the second (implicit) input `x`
     Å½   # Take the Sine of that (and output it implicitly)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.
In either case, propagate the particle/wave to the right by one unit.
Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:
. →  .
 . →   .
  . →    .
   . →     .
    . →      .
     . →       .
      . →        .
       . →         .
In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:
/ → /\
\ → \/
/\ → /\/
\/ → \/\
/\/ → /\/\
\/\ → \/\/
/\/\ → /\/\/
\/\/ → \/\/\
In either case, the output may not have trailing spaces but an optional trailing newline is allowed.
The shortest code in bytes wins.

Comments are not for extended discussion; this conversation has been moved to chat.

C, 69 bytes
p;f(char*s){p=s[strlen(s)-1]^46;p^=p?93:3022856;printf("%s%s",s,&p);}

This requires a little-endian machine, and output to a terminal that support ASCII escape codes.
p=s[strlen(s)-1]^46 grabs the last ASCII code of the input string, and XORs it with the ASCII code of a dot.
p^=p?93:3022856 will cause p to be p^93 if the ASCII code is not a (back)slash, where p^46^93 == p^115, which will toggle between back and forward slash. If p is a dot, it will instead be 3022856, which is little-endian for "\b .".
printf("%s%s",s,&p); prints the input string followed by the integer p, interpreted as a little-endian byte string.

This is pure genius.

You can save one byte by replacing 3022856 with '. \b', a multibyte character literal. Awesome answer !

Could anyone come up with a version of this that doesn't use any stdlib stuff? :)

Jelly, 17 14 bytes
ṪO*2.ị“ .\/\”ṭ

Try it online! or verify all test cases.
How it works
ṪO*2.ị“ .\/\”ṭ  Main link. Argument: s (string)

Ṫ               Tail; pop and yield the last character.
 O              Ordinal; map “./\” to [46, 47, 92].
  *2.           Elevate the code point to the power 2.5.
                This maps [46, 47, 92] to [14351.41, 15144.14, 81183.84].
     ị“ .\/\”   Index into that string.
                Jelly's indexing is modular, so this takes the indices modulo 5,
                which gives [1.41, 4.14, 3.84].
                Also, for a non-integer index, ị retrieves the elements at both
                adjacent integer indices (1-based). Here, these are [1, 2], [4, 5],
                and [3, 4], so we get " .", "/\", or "\/".
             ṭ  Tack; append the characters to the popped input string.

Huh. Just realised this is 22 bytes in UTF-8. Wonder if other code pages can be used to reduce the byte count of other prorams.

CJam, 16 bytes
l)_'.={S\}"\/"?|

Try it online! or verify all test cases.
How it works
l                 Read a line from STDIN.
 )_               Shift out the last character and copy it.
   '.=            Compare the copy with a dot.
              ?   If the last character is a dot:
      {S\}            Push " " and swap the dot on top.
          "\/"    Else, push "\/".
               |  Perform set union, ordering by first occurrence.
                    " " '.  | -> " ."
                    '/ "\/" | -> "/\"
                    '\ "\/" | -> "\/"

Note to self: learn how set union works. This seems to be where most of the bytes were saved when compared to mine.

Python, 41 bytes
lambda s:[s+'\/'[s[-1]>'/'],' '+s][s<'/']

Casework. Uses the sorted order ' ', '.', '/', '\'. For spaces and period, prepends a space. Otherwise, appends a slash or blackslash opposite to the last character.

Game Maker Language, 107 bytes
s=argument0;if string_pos(" ",s)return " "+s;if string_pos(s,string_length(s))="/"s+="\"else s+="/"return s

Vim, 27 23 keystrokes
First vim answer ever, haven't used vim at all really even.
A/<esc>:s#//#/\\<cr>:s#\./# .<cr>

How it works: It appends a / at the end of line, subs // for /\, subs ./ for  .

You can avoid escaping the /s if you use a different delimiter, for example s#//#/\\ .

Thanks, I had no idea anything like that existed

Python,  44  42 bytes
lambda s:s[:-1]+"\/ /\."[-ord(s[-1])&3::3]

Replaces the last character with the correspond set of two characters. ideone link
(-2 bytes thanks to @xsot's shorter mapping function)

-ord(s[-1])&3 also gives 3 different indices.

@xsot Oh nice, I didn't think of &!

No meme this time? :'(

MATL, 19 bytes
t47<?0w}'\/'yO)o)]h

Try it online! Or verify all test cases.
Explanation
t        % Input string implicitly. Duplicate
47<      % Are entries less than 47 (i.e dot or spaces)?
?        % If all are
  0      %   Push a 0. When converted to char it will be treated as a space
  w      %   Swap, so that when concatenated the space will be at the beginning
}        % Else
  '\/'   %   Push this string
  y      %   Duplicate the input string onto the top of the stack
  O)     %   Get its last element
  o      %   Convert to number
  )      %   Use as (modular) index to extract the appropripate entry from '\/'
]        % End
h        % Concatenate string with either leading 0 (converted to char) or
         % trailing '\'  or '/'. Implicitly display

05AB1E, 17 15 bytes
D'.åiðìë¤„\/s-J

Explanation
D'.åi              # if input contains dot
     ðì            # prepend a space
       ë           # else
        ¤„\/s-     # subtract last char of input from "\/"
              J    # join remainder to input
                   # implicitly print

Try it online

CJam, 35 26 25 bytes
Saved 9 bytes thanks to dennis
Saved 1 more byte, also thanks to dennis
q:I'.&SI+IW='/=I'\+I'/+??

Try it online!
Probably poorly golfed, but I'm not too familiar with CJam. There's probably a better way to check if an element is in an array, but I couldn't find any operators for that.
Explanation:
q:I e# take input
'.& e# push union of input and ".", effectively checking if input contains it
SI+ e# push string with space in beginning
IW='/= e# push 1 if the last chsaracter in the input is /
I'\+ e# push the input with a \ appended
I'/+ e# push the input with a / appended
? e# ternary if to select correct /
? e# ternary if to select final result

W is initially -1 and ? works both with blocks and other stack items, so you can reduce your code to q:I'.#)SI+IW='/=I'\+I'/+??

To test if a character belongs to a string, you can intersect them with &.

I am so bad at CJam lol

Matlab, 74 71 62 57 bytes
@(s)[s(1:end-1) ' .'+(s(1)>46)*'/.'+(s(end)>47)*[45 -45]]

It computes the last two characters based on the s(1) (first character) - to determine if we're dealing with the \/ case, and the last character s(end) to make the correct tuple for the \/ characters.

JavaScript, 79 70 65 58 bytes
(a,b="/\\/",i=b.indexOf(a[a.length-1]))=>i<0?" "+a:a+b[i+1]

Replace b.charAt(i+1) with b[i+1] to save some bytes. Also, this does not work for all test cases. \/ gives /\\, for example.

@user2428118 Thanks, bug fixed and code shortened!

init b and i as params with a default value: (a,b=...,i=...)=> to avoid return

Ah yes, I forgot about that new feature.  Also was able to remove the { } as well because of this.

in fact, with a few more steps, you'll converge to the answer of @TylerY86

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Specifications
Can't use arrow methods in "JavaScript" until the living standard defers to ECMAScript 2015, instead of ECMAScript 5.1. It might not matter for this case. :)

C, 85 bytes
j;f(char*n){j=strlen(n)-1;printf("%s%s",n[j]<47?" ":n,n[j]==46?n:n[j]==47?"\\":"/");}

Ideone
I haven't slept for about 20 hours, my code probably can be golfed a lot.

Brachylog, 35 bytes
t~m["\/.":X]t:"/\ "rm:?{.h" "|r.}c.

Test suite.
(Slightly modified.)

Retina, 19 bytes
\.
 .
/$
/\^H
\\$
\/

^H represents the BS byte. Try it online!

Why the backspace character?

Without it, the next replacement would match the trailing backslash. For example, input / would become /\/.

><>, 47 bytes
i:0(?\
*=?$r\~:1[:"./ \/"{=?@r=?$r~~]:48
l?!;o>

Try it online!
The first line is a standard ><> input loop. The second line chooses the appropriate character from / \ to append to the string, based on the last input character. In addition, if the last input character was a ., the top two elements are switched. Finally, the stack contents are printed in reverse.

C# - 46 bytes
s=>s[0]<47?' '+s:s+(s.EndsWith("/")?'\\':'/')
Try it here.

Haskell, 46 45 44 bytes
f z@(x:_)|x<'/'=' ':z|x<'0'='\\':z|1<2='/':z

Takes advantage of the fact that  < . < / < 0 < \ in the ASCII table to save two bytes

Python 2, 72 bytes
lambda x:x[:-1]+(" .","\/","/\\")[ord(x[-1])/46+(-1,1)[ord(x[-1])%46>0]]

Any help golfing more would be greatly appreciated!
This takes the last character in the input and converts it into its ASCII code to get the corresponding index in the list of two characters. Those two characters are appended to all the characters of the input up until the last one.

C#, 80 63 bytes
s=>{var c=s[s.Length-1];return c<'/'?" "+s:c>'/'?s+"/":s+"\\";}

Can you get it to work using a lambda expression?

s=>{var c=s[s.Length-1];return c<'/'?" "+s:c>'/'?s+"/":s+"\\";} 63 https://dotnetfiddle.net/8x79az

s=>{var c=s[s.Length-1];return c<47?' '+s:s+(c>47?'/':'\\');} 61 https://dotnetfiddle.net/ykKIL1

Added a 46 byte competitor for you. :)

Perl, 30 + 1 (-p) = 31 bytes
s/\./ ./,s|/$|/\\|||s|\\$|\\/|

Needs -p and -M5.010 or -E to run :
perl -pE 's/\./ ./,s|/$|/\\|||s|\\$|\\/|' <<< ".
  .
    .
/
/\/"

Straight forward implementation of the challenge. (Note that the || between the last two regex are or, as it might be hard to read, so the three regex are : s/\./ ./, and s|/$|/\\|, and s|\\$|\\/|)

SQF, 91
Using the function-as-a-file format:
s=_this;switch(s select[(count s)-1])do{case".":{" "+s};case"\":{s+"/"};case"/":{s+"\"};}

Call as "STRING" call NAME_OF_COMPILED_FUNCTION

ECMAScript 6 / 2015 (JavaScript), 41 bytes
s=>s<'/'?' '+s:s+'\\/'[s.slice(-1)>'/'|0]

Good catch Neil.

Your output seems to be incorrect. For the slashes, your code should append the next slash, not prepend it.

Adjusted answer.

Why not +(s+1)?

Better still, s<'/'.

PowerShell v2+, 59 58 52 51 bytes
param($n)(" $n","$n/","$n\")['.\/'.IndexOf($n[-1])]

Takes input $n, dumps it an array index operation. We select the element of the array based on the index ['.\/'.IndexOf($n[-1]) -- i.e., based on the last character of the input $n, this will result in 0, 1, or 2. That corresponds to the appropriate string of the array. In any case, the resulting string is left on the pipeline and printing is implicit.
Test cases
PS C:\Tools\Scripts\golfing> 0..7|%{' '*$_+'.'}|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
. =>  .
 . =>   .
  . =>    .
   . =>     .
    . =>      .
     . =>       .
      . =>        .
       . =>         .

PS C:\Tools\Scripts\golfing> '/,\,/\,\/,/\/,\/\,/\/\,\/\/'-split','|%{"$_ => "+(.\wave-particle-duality.ps1 "$_")}
/ => /\
\ => \/
/\ => /\/
\/ => \/\
/\/ => /\/\
\/\ => \/\/
/\/\ => /\/\/
\/\/ => \/\/\

C#, 54 bytes
s=>s.EndsWith(".")?" "+s:s+(s.EndsWith("/")?"\\":"/");

Provided a 46 byte competitor for you. :)

SED, 41 36 27
saved 7 thanks to charlie
 s|\.| .|;s|/$|/\\|;t;s|$|/|

uses 3 substitutions:
s/\./ ./ adds a space if there is a .
s|/$|/\\|,s|$|/| adds the appropriate slash to the end
uses | instead of / as the delimiter
t branches to the end if the second regex matches so it doesn't add the other slash

I just came to an almost identical solution: s/\./ ./;s./$./\\.;t;s.$./. -- it's 27 bytes. The 3rd substitution is simplified and on my system the -re is not needed. Also, I use . instead of # to stay visually in the input space. ;o)

ARM machine code on Linux, 50 bytes
Hex dump:
b580 1e41 f811 2f01 2a00 d1fb 3901 780b 1a0a 4601 2001 2704 df00 2000 a103 2202 f013 0303 2b03 4159 df00 bd80 2e202f5c 5c2f

First post here, hope I'm doing this right. This is 32-bit ARM assembly, specifically Thumb-2. The input string is a NUL-terminated string taken in through r0, the output is printed to the stdout. In C-syntax, the prototype for the function would be void func_name(char* string). It is AAPCS (ARM calling convention) complaint, if it weren't then 2 bytes could be shaved off.
Here's the equivalent assembly, with comments explaining what's happening:
    @Input: r0 is char* (the string)
    @Output: Modified string to console
    push {r7,lr} @Save r7 and the link register
    subs r1,r0,#1 @Make a copy of the char*, subtracting because we're
    @going to pre-increment.
    loop: @This loop is a little strlen routine
            ldrb r2,[r1,#1]! @In C-syntax, r2=*++r1;
            cmp r2,#0
            bne loop
    @Now r1 points to the null character that terminates the string
    subs r1,r1,#1 @Make r1 point to the last character
    ldrb r3,[r1] @Load the last character into r3
    subs r2,r1,r0 @r2=length(r0) - 1;
    mov  r1,r0 @r0 holds the original char*
    movs r0,#1 @1 is the file descriptor for stdout
    movs r7,#4 @4 is write
    swi #0

    @Now all the characters from the initial string have been printed,
    @except for the last one, which is currently in r3.

    movs r0,#1 @1 is stdout, have to reload this since the system call
    @returns in r0.
    adr r1,msg @Load msg into r1 (the pointer to the string)
    movs r2,#2 @We're going to print two more characters.

    @Now the bit magic. The ascii codes for '\', '.', and '/' map onto
    @0, 2, and 3 when bitwise anded with 3 (0b11).
    @This will be the offset into our string. However, since we must print
    @2 characters, we need our offsets to be 0, 2, and 4.
    @Therefore, we only set the carry if our value is >=3, then add with
    @carry (adcs). Thus we get the correct offset into the string msg.
    ands r3,r3,#3
    cmp r3,#3 @Sets carry if r3>=3
    adcs r1,r1,r3 @Add the offset to r1
    swi #0 @Make the system call
    pop {r7,pc} @Return and restore r7
msg:
    .ascii "\\/ ./\\" @The three different sequences of 2 characters that
    @can go at the end.

R, 119 bytes
a=scan(,"");if((q=strsplit(a,"")[[1]][nchar(a)])=="."){cat(" ",a,sep="")}else{s=switch(q,"/"="\\","/");cat(a,s,sep="")}

Ungolfed :
a=scan(,"")
if((q=strsplit(a,"")[[1]][nchar(a)])==".")
    cat(" ",a,sep="")

else
s=switch(q,"/"="\\","/")
cat(a,s,sep="")

Turtlèd, 32 bytes (noncompeting)
l!-[*+.r_]l(/r'\r)(\r'/)(." .")$

Explanation:
[implicit]                       first cell is an asterisk

l                                move left, off the asterisk, so the '[*+.r_]' loop runs
 !                               take input into string var, char pointer=0, 1st char
  -                              decrement char pointer, mod length input

   [*    ]                       while current cell isn't *:
     +.                          increment string pointer, and write the pointed char
       r_                        move right, write * if pointed char is last char, else " "

          l                      move left

           (/    )               if the current cell is /
             r'\r                move right, write /, move right

                  (\   )         If the current cell is \
                    r'/          move right, write /

                        (.    )  If the current cell is .
                          " ."   Write " .", the first space overwriting the existing '.'

                               $ Program won't remove leading spaces when printing

    [implicit]                   Program prints grid after finishing execution

Java 7, 76 bytes
String c(String i){return i.contains(".")?" "+i:i+(i.endsWith("/")?92:'/');}

Pretty straightforward.
Ungolfed & test code:
Try it here.
class M{
  static String c(String i){
    return i.contains(".")
            ? " " + i
            : i + (i.endsWith("/")
                    ? 92
                    : '/');
  }

  public static void main(String[] a){
    System.out.println(c(" ."));
    System.out.println(c("  ."));
    System.out.println(c("   ."));
    System.out.println(c("    ."));
    System.out.println(c("     ."));
    System.out.println(c("      ."));
    System.out.println(c("       ."));
    System.out.println(c("        ."));
    System.out.println(c("/"));
    System.out.println(c("\\"));
    System.out.println(c("/\\"));
    System.out.println(c("\\/"));
    System.out.println(c("/\\/"));
    System.out.println(c("\\/\\"));
    System.out.println(c("/\\/\\"));
    System.out.println(c("\\/\\/"));
  }
}

Output:
  .
   .
    .
     .
      .
       .
        .
         .
/\
\/
/\/
\/\
/\/\
\/\/
/\/\/
\/\/\

Pyth - 16 bytes
?}\.Q+dQ+Q-"\/"e

Test Suite.

Javascript: 60 bytes
 i=>i.includes(".")?" "+i:i.charAt(i.length-1)=="/"?i+"\\":i+"/"

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
100KB image compression
Your task is to, given an image, compress it to 100000 bytes or less, while following all of the below rules:

No cheating/loopholes.
Your code must not be optimized to work best only on the test set of images, but rather produce a good output in general.
Colours that do not exist in the original input image must also not exist in the output image. You do not necessarily have to use all of the colours in the input image, so you may use a subset of them if you want to, but,  there must not be any extra colours in the output image that were not present in the input image.
The input will be at minimum of image types/file extensions JPG, PNG,  GIF (including animated GIFs), and BMP. Your code may support any additional formats for input and output beyond the minimum described above, if you want to.
The output image must remain in the same file format/extension as the original image, unless your code doesn't support a format and you'd need to convert it. Conversion processing must be done losslessly and outputted to  a lossless file format. Therefore, there must not be anything added or removed at all from the image during the format conversion process.
The maximum filesize of the output image after compression is exactly 100000 bytes.
You must not losslessly compress images. Theoretically speaking, "any lossless compression algorithm that makes some files shorter must necessarily make some files longer."
The output image must have the exact same dimensions/size as the input image.
Theoretically speaking, every possible input your algorithm/code gets must produce an output of 1000000 bytes or less.

Your code must produce good output on most images in general, but, for this challenge, you must test your code on this test set of images and upload your output.
You must also show the code that you used, and not just the output images.
Your score is determined by the sum the squared difference between the input and output images.
As an example:
If the first pixel in the uncompressed image is RGB (2,3,4) and the first pixel in the compressed image is RGB (5,6,7), then the squared distance for that pixel is (2-5)^2+(3-6)^2+(4-7)^2, and then you sum that up for all the pixels.
Thank you, and good luck!

Unfortunately, "best image quality" is way too broad as a winning criterion.  I'd recommend posting challenges in the Sandbox to refine them before posting them here

That said, while this challenge is well written and easy to read (nice job!), it's really similar to another image compression challenge, and I'm not sure how you would score "best image quality" without making it a duplicate.

Better, but a bit unclear. What does "amount of colors" mean? The number of pixels with the same RGB value? The number of R values that are the same (and G/B values)? What if the pixels are in a different spot?

I really like the spirit of the challenge, but if the 'compressor' returns an exact copy of the original image, but is one off with every color, in this grading scheme, it would get 0, as it has none of the original colors. One way is to sum the squared difference between the input and output images.

If, for the first pixel, the uncompressed image is (2,3,4) and the compressed is (5,6,7), then the squared distance for that pixel is (2-5)^2+(3-6)^2+(4-7)^2, and then sum that up for all the pixels. Conversely, you could steal the python code in 'Compress an image to a 4 KiB preview' which is structure-based instead.

Please do not vandalise your question. If you register your account, you can delete it.

How do I make the question no-longer on hold?
I've updated it and made it more clear.

@CodingGolfHockey What should we do if it is impossible to create an image of a given size under 100kB?

If by impossible you mean that your algorithm may produce an output that doesn't follow the rules, then do not post it.
I've edited the challenge to make this more clear.

Looks like I need 5 re-open votes for this to be no longer on hold. I guess I'll have to wait..


text:
Percent-Encode a String
Introduction
As some of you may know, URLs actually have a list of characters that do special things. For example, the / character separates parts of the URL, and the ?, &, and = characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: $&+,/:;=?@. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called percent-encoding.
Percent encoding is when you take a character's hexadecimal value and prepend a % character to the beginning of it. For example, the character ? would be encoded as %3F, and the character & would be encoded as %26. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded.
The Challenge
You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. Built-ins that accomplish this task are not allowed, nor are standard loopholes. For reference, here is a list of every character that needs to be percent encoded:

Control characters (Codepoints 00-1F and 7F)
Extended ASCII characters (Codepoints 80-FF)
Reserved characters ($&+,/:;=?@, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40)
Unsafe characters (" <>#%{}|\^~[]`, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60)

Here is a the same list, but instead as a list of decimal codepoints:
0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255

This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!
Test Cases
http://codegolf.stackexchange.com/  =>  http%3A%2F%2Fcodegolf.stackexchange.com%2F
[@=>]{#}  =>  %5B%40%3D%3E%5D%7B%23%7D
Test String  =>  Test%20String
ÑÉÐÔ®  =>  %D1%C9%D0%D4%AE
  =>  %0F%16%7F (Control characters 0F, 16, and 7F)
 ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ  =>  %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF)
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  =>  %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E

Would you have a testcase that shows the control characters?

@LeakyNun done.

I'm sure codepoint EF doesn't contain the question mark.

@zyabin101 where did you find that? Im not seeing it.

"For example, the character ? would be encoded as %EF..."

@zyabin101 Oops, thanks for catching that!

Could we have one string that tests basically the entire non-extended ASCII alphabet?

@orlp I added that string, as well as the entire printable ASCII range.

Is output case-sensitive? e.g., would %2b be acceptable instead of %2B?

@DJMcMayhem no. It is not case sensitive.

In the last test case, shouldn't the space get encoded as well?

@GamrCorps, will this pass test cases especially for ÑÉÐÔ® in python? -  import re;f=lambda s:re.sub("[^-!'-*.\w]",lambda t:"%%%02X"%ord(t.group(0)),s) I am not sure how does extended ascii supposed to work.

@Dennis indeed, thanks for noticing that.

Will there also be newlines in the input?

@Adnan Considering newlines are part of the 00-1F range, yes, newlines may be found in the input. Also, it does not matter if they are handled as \r\n or just \n

Pyth, 30 28 26 bytes
L?hx+G+rG1CGbb+\%.HCbsmydz

try it online
Explanation
L?hx+G+rG1CGbb+\%.HCbsmydz
L?hx+G+rG1CGbb+\%.HCb       First part, L defines the function y(b)
 ?hx+G+rG1CGbb+\%.HCb       ? is the ternary operator
  hx+G+rG1CGb               This part will be evaluated
  hx                        x will find the first occurence of a
                            character in a list. If it doesn't
                            find one, it will return -1. hx then
                            equals 0 (or false).
    +G+rG1CG                The list of allowed characters, a
                            concetanation (+) of the alphabet (G),
                            uppercase alphabet (rG1) and numbers
                            (CG, see below for details)
            b               The character to find in the list
             b              True branch of the ternary operator,
                            the character is allowed and returned.
              +\%.HCb       False branch, convert to hex and add %
                     smydz  The actual program
                      mydz  Map every character in the input (z)
                            using the function y on every d
                     s      Join the array, and implicit print.

CG is this trick that generate a huge number that contains all possible digits. This is perfect, since we don't care for duplicates when checking whether a string is in another.

This answer does not meet the spec in the question. There are more allowed characters than just A-Za-z0-9. For example, . should be preserved rather than translated to %2E. (cc: @GamrCorps)

Vim, 67 bytes/keystrokes
:s/\c[^a-z!'()*0-9._-]/\='%'.printf("%02x",char2nr(submatch(0)))/g<cr>

Note that <cr> represents the enter key, e.g. 0x0D which is a single byte.
This is a pretty straightforward solution. Explanation:
:s/                                                                    "Search and replace
   \c                                                                  "Case-insensitive
     [^a-z!'()*0-9._-]/                                                "A negative range. Matches any character not alphabetc, numeric or in "!'()*0-9._-"
                       \=                                              "Evaluate
                         '%'                                           "a percent sign string
                            .                                          "Concatenated with
                             printf("%02x",char2nr(submatch(0)))       "The hex value of the character we just matched
                                                                /g     "Make this apply to ever match
                                                                  <cr> "Actually run the command

That printf("%02x",char2nr(submatch(0))) garbage is terribly ungolfy.

"That printf("%02x",char2nr(submatch(0))) garbage is terribly ungolfy" and extremely hacky

Julia, 47 bytes
!s=replace(s,r"[^\w!'()*.-]",c->"%"hex(c[1],2))

Try it online!

Perl, 40 bytes
39 bytes code + -p.
A bit lame, but I think it's the shortest solution...
s/[^!'()*-.\w]/sprintf'%%%02x',ord$&/ge

Usage
echo -n ' !"#$%&'\''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqstuvwxyz{|}~' | perl -pe "s/[^'()*-.\w]/sprintf'%%%02x',ord$&/ge"
%20%21%22%23%24%25%26'()*+,-.%2f0123456789%3a%3b%3c%3d%3e%3f%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5b%5c%5d%5e_%60abcdefghijklmnopqstuvwxyz%7b%7c%7d%7e

Ruby, 37 + 3 = 40 bytes
Run with -p (3 extra bytes), like $ ruby -p percent_encode.rb:
gsub(/[^\w!'()*-.]/){"%%%02X"%$&.ord}

Haskell, 201 179 178 127 119 bytes
import Data.Char;import Numeric;f=(=<<)(\c->if isAlphaNum c&&isAscii c||elem c"-_.~"then[c]else '%':(showHex$ord c)"")

Ungolfed:
import Data.Char
import Numeric

f=(=<<) e
e c = if isAlphaNum c && isAscii c && c `elem` "-_.~" then [c] else '%' : (showHex $ ord c) ""

Can you remove a bunch of the spaces?

You can loose the where, turn the if into guards, make e partial, loose the last argument of showHex, inline p, inline s, loose the signature, reorder the elem and loose even more whitespace. As a first approximation I got down to 118 that way.

Thanks @MarLinn for a bunch of good suggestions on trimming down the code. However, I had some trouble with certain suggestions. First of all, if I remove the signature, GHC will complain that No instance for (Foldable t0) arising from a use of ‘foldr’. It says that the type of the function is ambiguous, resulting in an inferred binding of f :: t0 Char -> [Char]. And second of all, I could not remove the empty string argument from showHex as it returns a ShowS, which is a type alias for String -> String thus needing the empty string.

@sham1, yes, ShowS takes a String... but you have one: the one you're adding with (++). So you can loose both at the same time. That's actually why ShowS looks that way. I don't get the type error, so I guess it's a version thing? Two other things I noticed by now: otherwise can always be replaced by 1<2 (a shorthand for True), but if you return to if instead you can inline e and drop all names. And even turn the fold into a concatMap, i.e. a (>>=). Doesn't save a lot, but at least a little. Might solve the type error, too.

Python 3, 92 bytes
5 bytes thanks to orlp.
1 byte thanks to Sp3000.
import re;lambda s:''.join(re.match("[!'-*.0-9\w-]",c,256)and c or'%%%02X'%ord(c)for c in s)

Ideone it!

re.match("[!'()*.0-9A-Za-z_-]",c)and c or'%%%02X'%ord(c)

@Sp3000 \w includes extended ASCII

Also, '()* -> '-*

I think \w works with the 256 (re.ASCII) option: ideone. It definitely works in Python 3 on ideone, and it should work with u"..." strings in Python 2, but ideone seems to do funky things to the latter (e.g. print len(u"ÑÉÐÔ®") gives 10 on ideone but 5 on repl.it and my computer, despite all being 2.7.10)

C, 83 bytes
f(char*p){for(;*p;++p)printf(isalnum(*p)||strchr("!'()*-._",*p)?"%c":"%%%02X",*p);}

Python, 86 bytes
lambda s:"".join(["%%%02X"%ord(c),c][c<"{"and c.isalnum()or c in"!'()*-._"]for c in s)

Port of my C answer.

Jelly, 28 27 bytes
ḟØWḟ©“!'()*-.”Od⁴‘ịØH”%p®,y

This is a monadic link. Try it online!
How it works
ḟØWḟ©“!'()*-.”Od⁴‘ịØH”%p®,y  Monadic link. Argument: s (string)

 ØW                          Yield “0...9A...Z_a...z”.
ḟ                            Remove these characters from s.
     “!'()*-.”               Yield “!'()*-.”.
   ḟ                         Remove these characters from s.
    ©                        Copy the result to the register.
              O              Ordinal; get the code point of each character.
               d⁴            Divmod 16; yield quotient and remainder modulo 16.
                 ’           Decrement the results.
                  ịØH        Index into “0123456789ABCDEF”.
                     ”p%     Perform Cartesian product with ”%, prepending it to
                             each pair of hexadecimal digits.
                        ®,   Yield [t, r], where t is the string in the register
                             and r the result of the Cartesian product.
                          y  Use this pair to perform transliteration on s.

16/32-bit x86 assembly, 73 bytes
Byte code:
AC 3C 21 72 2A 74 3E 3C 26 76 24 3C 2B 72 36 3C
2C 76 1C 3C 2F 72 2E 74 16 3C 3A 72 28 74 10 3C
5F 74 22 50 0C 60 3C 60 74 02 3C 7B 58 72 16 D4
10 3C 09 1C 69 2F 86 E0 3C 09 1C 69 2F 92 B0 25
AA 92 AA 86 E0 AA E2 B8 C3
Disassembly:
l0: lodsb         ;fetch a character
    cmp  al, 21h
    jb   l1       ;encode 0x00-0x20
    je   l2       ;store 0x21
    cmp  al, 26h
    jbe  l1       ;encode 0x22-0x26
    cmp  al, 2bh
    jb   l2       ;store 0x27-0x2A
    cmp  al, 2ch
    jbe  l1       ;encode 0x2B-0x2C
    cmp  al, 2fh
    jb   l2       ;store 0x2D-0x2E
    je   l1       ;encode 0x2F
    cmp  al, 3ah
    jb   l2       ;store 0x30-0x39
    je   l1       ;encode 0x3A
    cmp  al, 5fh
    je   l2       ;store 0x5F
    push eax
    or   al, 60h  ;merge ranges
    cmp  al, 60h
    je   l3       ;encode 0x40, 0x60
    cmp  al, 7bh
l3: pop  eax
    jb   l2       ;store 0x41-0x5A, 0x61-0x7A
                  ;encode 0x3B-0x3F, 0x5B-0x5E, 0x7B-0xFF

l1: aam  10h      ;split byte to nibbles
    cmp  al, 9    ;convert 0x0A-0x0F
    sbb  al, 69h  ;to
    das           ;0x41-0x46 ('A'-'F')
    xchg ah, al   ;swap nibbles
    cmp  al, 9    ;do
    sbb  al, 69h  ;other
    das           ;half
    xchg edx, eax ;save in edx
    mov  al, '%'
    stosb         ;emit '%'
    xchg edx, eax
    stosb         ;emit high nibble
    xchg ah, al

l2: stosb         ;emit low nibble or original character
    loop l0       ;until end of string
    ret
Call with:
- esi = pointer to buffer that holds source string;
- edi = pointer to buffer that receives encoded string;
- ecx = length of source string.

Python 2, 78 bytes
lambda s:"".join(["%%%02x"%ord(c),c][c.isalnum()or c in"!'()*-._"]for c in s)

More nicely formatted:
lambda s:
    "".join(["%%%02x" % ord(c), c][c.isalnum() or c in"!'()*-._"] for c in s)

SQF, 199 176
Using the function-as-a-file format:
i="";a="0123456789ABCDEF!'()*-.GHIJKLMNOPQRSTUVWXYZ_";{i=i+if((toUpper _x)in a)then{_x}else{x=(toArray[_x])select 0;"%"+(a select floor(x/16))+(a select(x%16))}}forEach _this;i

Call as "STRING" call NAME_OF_COMPILED_FUNCTION

PowerShell v2+, 146 bytes
param($n)37,38+0..36+43,44,47+58..64+91,93+96+123..255-ne33|%{$n=$n-replace"[$([char]$_)]",("%{0:x2}"-f$_)};$n-replace'\\','%5c'-replace'\^','%5e'

Long because I wanted to show a different approach rather than just copy-pasting the same regex string that every else is using.
Instead here, we loop through every code point that must be percent-encoded, and do a literal -replace on the input string $n each iteration (re-saving back into $n). Then we need to account for the two special characters that need escaping, \ and ^, so those are in separate -replace elements at the end. Since we didn't re-save that final string, it's left on the pipeline and printing is implicit.


text:
Testing for admissible sequences
Executive summary: test whether an input sequence of integers is "admissible", meaning that it doesn't cover all residue classes for any modulus.
What is an "admissible" sequence?
Given an integer m ≥ 2, the residue classes modulo m are just the m possible arithmetic progressions of common difference m. For example, when m=4, the 4 residue classes modulo 4 are
..., -8, -4, 0, 4, 8, 12, ...
..., -7, -3, 1, 5, 9, 13, ...
..., -6, -2, 2, 6, 10, 14, ...
..., -5, -1, 3, 7, 11, 15, ...

The kth residue class consists of all the integers whose remainder upon dividing by m equals k. (as long as one defines "remainder" correctly for negative integers)
A sequence of integers a1, a2, ..., ak is admissible modulo m if it fails to intersect at least one of the residue classes. For example, {0, 1, 2, 3} and {-4, 5, 14, 23} are not admissible modulo 4, but {0, 1, 2, 4} and {0, 1, 5, 9} and {0, 1, 2, -3} are admissible modulo 4. Also, {0, 1, 2, 3, 4} is not admissible modulo 4, while {0, 1, 2} is admissible modulo 4.
Finally, a sequence of integers is simply admissible if it is admissible modulo m for every integer m ≥ 2.
The challenge
Write a program or function that takes a sequence of integers as input, and returns a (consistent) Truthy value if the sequence is admissible and a (consistent) Falsy value if the sequence is not admissible.
The input sequence of integers can be in any reasonable format. You may assume that the input sequence has at least two integers. (You may also assume that the input integers are distinct if you want, though it probably doesn't help.) You must be able to handle positive and negative integers (and 0).
Usual code-golf scoring: the shortest answer, in bytes, wins.
Sample input
The following input sequences should each give a Truthy value:
0 2
-1 1
-100 -200
0 2 6
0 2 6 8
0 2 6 8 12
0 4 6 10 12
-60 0 60 120 180
0 2 6 8 12 26
11 13 17 19 23 29 31
-11 -13 -17 -19 -23 -29 -31

The following input sequences should each give a Falsy value:
0 1
-1 4
-100 -201
0 2 4
0 2 6 10
0 2 6 8 14
7 11 13 17 19 23 29
-60 0 60 120 180 240 300

Tips

Note that any sequence of 3 or fewer integers is automatically admissible modulo 4. More generally, a sequence of length k is automatically admissible modulo m when m > k. It follows that testing for admissibility really only requires checking a finite number of m.
Note also that 2 divides 4, and that any sequence that is admissible modulo 2 (that is, all even or all odd) is automatically admissible modulo 4. More generally, if m divides n and a sequence is admissible modulo m, then it is automatically admissible modulo n. To check admissibility, it therefore suffices to consider only prime m if you wish.
If a1, a2, ..., ak is an admissible sequence, then a1+c, a2+c, ..., ak+c is also admissible for any integer c (positive or negative).

Mathematical relevance (optional reading)
Let a1, a2, ..., ak be a sequence of integers. Suppose that there are infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. Then it's easy to show that a1, a2, ..., ak must be admissible. Indeed, suppose that a1, a2, ..., ak is not admissible, and let m be a number such that a1, a2, ..., ak is not admissible modulo m. Then no matter what n we choose, one of the numbers n+a1, n+a2, ..., n+ak must be a multiple of m, hence cannot be prime.
The prime k-tuples conjecture is the converse of this statement, which is still a wide open problem in number theory: it asserts that if a1, a2, ..., ak is an admissible sequence (or k-tuple), then there should be infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. For example, the admissible sequence 0, 2 yields the statement that there should be infinitely many integers n such that both n and n+2 are prime, this is the twin primes conjecture (still unproved).

[_60:0:60:120:180] is giving me true; indeed it does not intersect at least one class in every m from 2 to 5 inclusive; additionally, it intersects only one class in every m from 2 to 5 inclusive.

I have the same for [-60, 0, 60, 120, 180] as @LeakyNun this should be admissible.

-60 0 60 120 180 240 300 intersects every residue class modulo 7, so it is not admissible.

Could we have longer testcases?

@LeakyNun: For any m, the first m primes larger than m form an admissible sequence. (The second-to-last Truthy test case is an example of this with m=7.) Falsy test cases can be generated by starting with the integers 1, ..., m, choosing k ≤ m, and adding random multiples of k to any or all of the starting integers 1, ..., m.

Jelly, 10 bytes
JḊðḶḟ%@ð€Ạ

Try it online! or run all test cases.
               Input: L.
JḊ             Range of [2..len(L)].
  ð    ð€      For x in [2..len(L)]:
   Ḷ             [0..x-1] (residue classes)
    ḟ              without elements from
     %@            L % x.
         Ạ     All truthy (non-empty)?

Brachylog, 25 24 19 bytes
5 bytes thanks to Karl Napf.

lybb'(eM-yA,?:[M]z:%aodA)
l:2'(eM-yA,?:[M]z:%aodA)
l:2'(eMg:?rz:%adlM)

Try it online!
Verify all testcases!
l:2'(eMg:?rz:%adlM)
l:2                  Temp = [2:length(input)]
   '(             )  true if the following cannot be proven:
     eM                  M is an element of the interval
                         indicated by Temp, i.e. from 2
                         to the length of input inclusive,
       g:?rz:%adlM       every element of input modulo M
                         de-duplicated has length M.

Python, 61 60 bytes
q=lambda l,d=2:d>len(l)or q(l,d+1)&(len({v%d for v in l})<d)

All test cases on ideone
Edit: replaced logical and with bitwise & to save one byte

Python, 67 64 bytes
As unnamed lambda:
lambda N:all(len({i%m for i in N})<m for m in range(2,len(N)+1))

Edit1: replaced set() with {}
Edit2: dont't need square brackets around generator in all(...)
Edit3: As pointed out by Jonathan Allan, range must go up to len(N)+1

Old code as function (96 bytes):
def f(N):
 for m in range(2,len(N)+1):
    if len(set(i%m for i in N))==m:return False
 return True

Hereby I give you credits for your approach that saved me 5 bytes.

@LeakyNun You're welcome!

JavaScript (ES6), 59 bytes
a=>a.every((_,i)=>!i++|new Set(a.map(e=>(e%i+i)%i)).size<i)

Uses @KarlNapf's Set of remainders trick.

Well, it is not a trick, just mathematics ;-)

MATL, 11 bytes
"X@QGy\un>v

Truthy is an array (column vector) containing all ones. Falsy is an array containing at least one zero. You can check these definitions using this link.
Try it online! Or verify all test cases: truthy, falsy (slightly modified code, each case produces a horizontal vector for clarity).
Explanation
"       % Take input array. For each; i.e. repeat n times, where n is arrray size
  X@Q   %   Push iteration index plus 1, say k. So k is 2 in the first iteration,
        %   3 in the second, ... n+1 in the last. Actually we only need 2, ..., n;
        %   but the final n+1 doesn't hurt
  G     %   Push input again
  y     %   Duplicate k onto the top of the stack
  \     %   Modulo. Gives vector of remainders of input when divided by k
  un    %   Number of distinct elements
  >     %   True if that number is smaller than k
  v     %   Vertically concatenate with previous results
        % End for each. Implicitly display

I'm still getting oriented at this site, so apologies if this is a well-asked type of question, but: I would think that truthy/falsy values should be actual constants of some sort, not patterns such as "an array containing at least one zero". Shouldn't one process the array (using bitwise AND in this case) to arrive at constants in the end?

@GregMartin That's a very good question. We have pretty solid consensus about its answer; see here

Got it, and now I see the point of your first link. Thanks for the explanation!

Mathematica, 51 bytes
And@@Table[Length@Union@Mod[#,i]<i,{i,2,Length@#}]&


text:
Print alphabet without using strings
The challenge: Write a script to print the alphabet, but you can't use any ASCII strings in your program. Unicode escape characters are allowed (if thats what you call them).
External libraries are allowed, as long as a link to the documentation is provided, and an online example if possible.
As this is code-golf, the answer with the shortest byte count will win!

@Adnan Updated the question with more information - IMO, it is not a duplicate

Another do X without Y challenge... I mean do X without Y challenge.

It's kind of a tricky case, since almost all answers in that challenge also don't use strings. That means that most of the answers can be reused for this challenge.

By the way, you can always use the Sandbox for writing challenges before posting them on the main site :). It's very useful for writing challenges, since you get feedback and find out whether it has been done before or not.

@Adnan Ah thank you, wasn't aware about that - ill be sure to use it for future questions and ill look at it now

Silicon, 1 byte
A

A is preinitialized to the alphabet. Output is implicit.

Neoscript, 27 bytes
{|65:[]:90:map(chr):fuse()}

Lambda returning the alphabet.


text:
The infinitely admissable sequence
In this challenge we'll compute an infinite minimal admissible sequence.
The sequence for this challenge starts with a(1) = 1.
We continue this sequence by finding a(n) as the smallest possible number such that a(n) > a(n-1) and for every prime p, the set {a(i) mod p : 1 ≤ i ≤ n} has at most p-1 elements.
Write a program or function that takes positive integer n and outputs a(n). Shortest code in bytes wins.

Example:
a(6) is 19, rather than, say 17 because [1,3,7,9,13,19] (the previous terms) is admissible while [1,3,7,9,13,17] is not.
[1,3,7,9,13,17] is not admissible, because for the base 3, after taking the modulo of each term with 3, we obtain [1,0,1,0,1,2] which contains every non-negative number smaller than 3, our chosen base.
For [1,3,7,9,13,19] however, it would be impossible to come up with a base such that the list after modulo contains every non-negative integer smaller than such base.

Reference:

OEIS A020498

Testcases:
a(1) = 1
a(2) = 3
a(3) = 7
a(4) = 9
a(5) = 13
a(6) = 19
a(7) = 21
a(8) = 27
a(9) = 31
a(10) = 33
a(100) = 583

Can we use 0-based index?

Related.

@LeakyNun For this one, sure.

Brachylog, 44 bytes
-:[1]r:[1]cit.
t<gX=:?rc.'(l:2eLg:.rz:%adlL)

Try it online!
100 takes about a minute here, so be patient if you want to try 100.
Predicate 0 (main predicate)
-:[1]r:[1]cit.
-:[1]r:[1]c     create array [[1], input-1, 1]
           i    iterate: [1] as input, iterate (input-1) times, predicate 1
            t.  last element is the output

Predicate 1 (auxiliary predicate)
t<gX=:?rc.'(l:2eLg:.rz:%adlL)
t<                              last element of input < Temp
  gX                            [Temp] = X
   X=                           Assign a value to X, which assigns
                                a value to Temp
   X :?rc.                      [Input,X] concatenated is output
         .'(                )   The following about the output cannot
                                be proven:
            l:2eL                   L is a number between 2 and length
                                    of output, inclusive
                Lg:.rz:%a           every element of output, taken modulo L,
                         dlL        after removing duplicates, has length L

ES6, 91 bytes
(n,a=[i=1])=>a[n]||f(n,a.every((_,j)=>(j+=2)>new Set(b.map(e=>e%j)).size,b=[...a,+++])?b:a)

Zero-indexed. Due to its recursive nature, only works for the first 450 terms, but computes a(99)=583 almost instantly.


text:
Langford strings
Challenge description
A Langford string of order N is defined as follows:

The length of the string is equal to 2*N,
The string contains first N letters of the English alphabet, each letter appearing twice,
For each pair of the same letters, there are M letters between them, where M is that letter's position in the alphabet (A = 1, B = 2, ..., Z = 26).

For instance, the only two possible Langford strings of order 3 are BCABAC and CABACB. As you can see, in both of these strings there is one letter between two A's, two letters between B's and three letters between C's. Given a positive integer N, output all Langford strings of order N (in any reasonable format: print them one by one separated by a newline, return a list/array...).
Sample inputs / outputs
3: [CABACB, BCABAC]
4: [DACABDCB, BCDBACAD]
5: # no output #
7: [GCFBECBDGFEADA, GBFCBDECGFDAEA, GBDFBCEDGCFAEA, GCAFACDEGBFDBE, GADAFCEDGCBFEB, GACAFDCEGBDFBE, GDAEAFDCGEBCFB, GBDEBFCDGECAFA, EGBFCBEDCGFADA, CGDFCBEDBGFAEA, EGDAFAEDCGBFCB, EGBCFBECDGAFAD, AGABFDBECGDFCE, EGADAFECDGBCFB, AGABEFBCDGECFD, BGDBCEFDCGAEAF, FBGDBCEFDCGAEA, BFGBAEADFCGEDC, CFGACADEFBGDBE, EAGAFBEDBCGFDC, BCGBFCEADAGFED, DAGAFDBECBGFCE, EBGCBFECDAGAFD, CEGDCFBEDBGAFA, CEGBCFBEDAGAFD, BDGBCFDECAGAFE, EFAGACEDFCBGDB, DFAGADEBFCBGEC, AFAGBDEBFCDGEC, DFAGADCEFBCGBE, ECFGBCEBDFAGAD, DEFGADAECFBGCB, CDFGCBDEBFAGAE, EBDGBFEDACAGFC, CDEGCFDAEABGFB, AEAGCDFECBDGBF, FAEAGCDFECBDGB, DFCEGDCBFEBAGA, BFCBGDCEFADAGE, ECFDGCEBDFBAGA, DAFAGDCEBFCBGE, BCFBGCDEAFADGE, AEAFGBDEBCFDGC, ADAFGCDEBCFBGE, AFACEGDCFBEDBG, BFCBEGCDFAEADG, EBFDBGECDFACAG, BEFBCGDECFADAG, EBDFBGEDCAFACG, AEAFCGDECBFDBG, AEADFGCEDBCFBG, ADAEFGDBCEBFCG]
12: # <216288 strings> #

Notes

Langford strings of order N can only be produced when N ≡ 0 (mod 4) or N ≡ 3 (mod 4),
You can use both lower-case and upper-case letters,
You may use subsequent numbers as well (012... or 123... instead of ABC...)
Order of strings in which they should appear as output is unspecified,
Output can be quite lengthy (for instance, there are over 5 trillion distinct Langford strings of order 20), so your program doesn't actually need to output them all, but it has to work in theory (given enough time and memory).
This challenge has been taken from /r/dailyprogrammer, all credit goes to /u/XenophonOfAthens

There's a closely related challenge in the sandbox. While in no way required it's usually a good idea and probably polite to check there as well for duplicates.

Can we just output an array of numbers?

@LeakyNun: Sure, why not. I updated the description.

I refer to this (run the program)

CJam (23 bytes)
{,2*e!{__f{\a/1=,(}=},}

Online demo. This is an anonymous block (function) which takes input on the stack and leaves output on the stack in the form of an array of arrays of 0-based sequential integers.

Brachylog, 43 bytes
:1fd.
ybB:1jp.,B:[.]z:2a
:3f-+$_~h?
t:.m~h?

Try it online!