text:
Output a list of all rational numbers
Out of all of mathematics, there will always be a few theorems that go beyond all common sense. One of these is the fact that there are different sizes of infinity. Another interesting fact is the idea that many infinities which seem to be of different size are actually of the same size. There are just as many even numbers as integers, as there are rational numbers.
The general concept of this question is to confront the bizarre reality of infinity. In this challenge, your program will output a list which will:

At any specific moment of time, always have a whole number of entries
Eventually contain (if left to run long enough) any specific (non-zero) rational number precisely once on the entire list
Contain an unbounded number of empty slots (entries on the list that are needlessly set to 0)
Have a proportion of empty slots that approaches a limit of 100%
For every positive integer N, have an infinite number of places with N consecutive empty slots

The Challenge
Your challenge is to write that shortest possible program that will output a special list with the following rules:

All entries with an index that is not a square number should be set to zero. So, the first entry will be nonzero, the second and third will be zero, the fourth will nonzero, etc.
All rational numbers will be in the form of an improper fraction (such as 4/5 or 144/13) that has been simplified. The exception is zeroes, which will be simply 0.
All (positive and negative) rational numbers should eventually appear on the list if your program runs for long enough and with enough memory. For any particular rational number, the time required may be an arbitrarily large, but always finite, amount of time.
If run for an infinite amount of time, no non-zero rational number should ever appear twice.

Rule 3 does allow for some variation, as in there is an infinite number of different possible legal outputs.
Output will be a stream of lines. Each line will be of the general form of 5: 2/3 where the first number is the entry number, then followed by the rational number. Note that 1: 0 will always be the first line of output.
Example snippet of output:
1: 1/1
2: 0
3: 0
4: 2/1
5: 0
6: 0
7: 0
8: 0
9: -2/1
10: 0
etc...

Rules, Regulations, and Notes
This is code golf. Standard code golf rules apply. Also, due to the variation allowed in the output, you need to at least show why you believe that your list will contain all possible rational numbers exactly once, and that your solution is correct.
EDIT: Since the primes numbers did distract from the challenge, I am changing it to square numbers. This accomplishes the same purpose, and also shortens the solutions.

What is the point of rule 1? Do you just want people to mutually golf two separate programs to test primality and enumerate the rationals?

It shows how a very small portion of the integers still has the same cardinality as the full set of rational numbers, and it also allows the percentage of empty slots to approach (but never reach) 100%.

I'm assuming that the program also needs to run in a fixed amount of memory, i.e. it can't assume that the machine can always allocate more? Also, is it against the rules to use (say) a C int for the list index when you know that it has a finite range? (Even though the exact limit can vary with the implementation.) Is some form of bignum required?

@PhiNotPi, there are far simpler ways of doing that, and it's a distraction from the more interesting part of the question.

@PeterTaylor Would square numbers be a better way?

You have 0 denoting "empty" infinitely often in the list, which contradicts your requirement that each rational appear exactly once (0 is a rational, of course). It seems to me that all of your bulleted objectives would be met by simply requiring the list to look like   r_0 e r_1 e e r_2 e e e r_3 e e e e r_4 ..., where the nth rational (r_n, n=0,1,2,3,...) is immediately preceded by n es (each e denoting "empty" -- literally a blank line if the items are on separate lines).

Well, in the numbered list I do mention that no non-negative integer will appear twice. I'll change the billeted list to match.

Oops, I put non- negative where I meant non- zero. That's fixed now.

Note that 1: 0 will always be the first line of output. – This contradicts your example and also does not make sense to me.

Haskell, 184 characters
main=putStr.unlines$zip[1..](s>>=g)>>=h
s=(1,1):(s>>=f)
f(a,b)=[(a,a+b),(a+b,b)]
g x@(a,b)=[x,(-a,b)]
h(i,(a,b))=(i^2)%(u a++'/':u b):map(%"0")[i^2+1..i*(i+2)]
i%s=u i++": "++s
u=show

This does a breadth-first traversal of the Calkin-Wilf Tree, yielding all positive rational numbers in reduced form exactly once. It then alternates between positive and negative to cover all the non-zero rational numbers and pads with zeroes between the square entries.
Output (excluding zero lines for brevity):
1: 1/1
4: -1/1
9: 1/2
16: -1/2
25: 2/1
36: -2/1
49: 1/3
64: -1/3
81: 3/2
100: -3/2
...

Sage, 103 113 128
Sage can list the rationals with ease!  Formatting to fit the program requirements, as always, ruins everything.
for i,q in enumerate(QQ):
 for j in[(i-1)^2+1..i*i]:print'%d:'%j,[0,'%d/%d'%(q.numer(),q.denom())][j==i*i]

Sage enumerates QQ according to their height:  the max absolute value of the numerator & denominator after GCD reduction.

You can eliminate the x.next() and use print only once, as follows, bringing the score down to 124: x=enumerate(QQ) for i,q in x:  for j in[(i-1)^2+1..i*i]:   print'%d: '%j,'%d/%d'%(q.numer(),q.denom())if j.is_square()else 0.  This doesn't display properly in a comment, but I think you can see what I mean.

BTW, I notice that after the first 4 positive elements, Sage's enumeration is not the same as in the other answers. The Calkin-Wilf formulas give a sequence in which the denominator of a rational is the numerator of the next rational; e.g. (..., 1/3, 3/2, 2/3, ...), compared to Sage's (..., 1/3, 3/1, 2/3,...). I can't seem to locate any documentation for Sage's enumeration, to see how it's computed.

@r.e.s., thanks!  I'd wanted to merge the print statements, but forgot to use the [x..y] notation.  Great to see another Sage user here!

Python, 162
f=lambda n:f(n/2)if n%2 else f(n/2)+f(n/2-1)if n else 1
n=i=1
while 1:
 print'%d:'%i,
 if i-n*n:s=0
 else: n+=1;s='%d/%d'%((-1)**n*f(n/2-1),f(n/2))
 print s
 i+=1

This uses the recursion given in Recounting the Rationals by Calkin & Wilf.

Haskell, 55 bytes
mapM_ print$join$iterate(>>=(\x->[x+1,1/(1+1/x)]))[1%1]

outputs
1 % 1
2 % 1
1 % 2
3 % 1
2 % 3
3 % 2
1 % 3
4 % 1
...

1%1 is the root of the Calkin-Wilf tree;
the iterate adds both children of each node;
the join collapses the levels into a single list.
120 chars if you add proper imports, 0, and negatives:
import Data.Ratio
import Control.Monad
main=mapM_ print$0:(join(iterate(>>=(\x->[x+1,1/(1+1/x)]))[1%1])>>=(\x->[-x,x]))

outputs
0 % 1
(-1) % 1
1 % 1
(-2) % 1
2 % 1
(-1) % 2
1 % 2
(-3) % 1
3 % 1
(-2) % 3
2 % 3
(-3) % 2
3 % 2
(-1) % 3
1 % 3
(-4) % 1
4 % 1
...

outputting empty slots? that's in poor taste:(
you had me at "list of all positive rationals"

mapM_ print$fix((1%1:).(>>= \x->[x+1,1/(x+1)])) is 47 chars. from haskellwiki. works as is, without any imports, at haskell.org's "try it" REPL (well, without the mapM_ print part...)

PHP 105 bytes
Note: This code must be saved as iso-8859-1 (ansi) in order to run correctly. Online interpretters which encode all input to utf8 by default (such as ideone) will generate the wrong output.
<?for($f=µ;$i++<$j*$j||++$j%2||(--$$f?$$f--:$f^=C);)echo"$i: ",$i==$j*$j?$j%2?$x=++$ö.~Ð.++$µ:"-$x":0,~õ;

Using Georg Cantor's enumeration (slightly modified for +/- values).
If you're having problems getting the above code to run (likely due to an excessive amount of NOTICE messages), use this instead (107 bytes):
<?for($f=µ;$i++<$j*$j||++$j%2||(--$$f?$$f--:$f^=C);)echo"$i: ",$i==$j*$j?$j%2?$x=++$ö.'/'.++$µ:"-$x":0,'
';

I get run-time errors with this code (which seems to contain some strange characters; e.g., "$ö.~Ð.").

Can you demonstrate that this solution works, say on ideone?  I get errors as well: http://ideone.com/ru1fo

Ideone seems to error out when too many NOTICE messages are generated: both ~Ð (equal to '/') and ~õ (equal to "\n") will generate a NOTICE every iteration. Of course, if you have NOTICEs off, it's not a problem. A paste with both replaced (107 Bytes): http://ideone.com/lFUbl

I've just noticed that Ideone's PHP interpretter generates the wrong output. If you run the code locally, you will see that it is correct. Or, you could test it with a valid PHP interpretter, such as Anarchy Golf's performance checker: http://golf.shinh.org/checker.html (save it to a file and upload)

When I save your revised code to a file with ANSI encoding, it does run on the Anarchy Golf interpreter. However, there's now a different problem: it violates the requirement that "no non-zero rational number should ever appear twice" in the list. In fact, the code appears to list every rational infinitely many times; e.g. 1/1, 2/2, 3/3, ... are all the same rational, and likewise for 1/2, 2/4, 3/6, ..., etc.

@r.e.s. Ahh yeah, you're right. Cantor's enumeration isn't a valid solution, given the wording of the problem.

It occurs to me that, although it violates the present problem criteria, your code might really interest the OP: The list it generates is "almost all" 0s, yet it contains not only all the non-zero rationals, it contains all of them infinitely many times!

Octave, 168 bytes
a=b=p=1;do for i=(p-1)^2+1:p^2-1 printf("%d: 0\n",i)end
printf("%d: %d/%d\n",p^2,a,b)
a=-a;if a>0do if b==1 b=a+1;a=1;else a++;b--;end until 1==gcd(a,b)end
p++;until 0

The solution is not very sophisticated, it is just a simple diagonal traversal of the "carpet" of rational numbers, discarding all fractions that can be simplified. After a positive number a/b, it's opposite -a/b is always printed before the next one from sequence goes.

Since all positive simple fractions will be printed and the opposite signed fractions to those will be printed, and it's never possible to two different simple fractions to have the same value, each non-zero rational number will be printed exactly once.
Degolfed:
a=b=p=1
do
    for i=(p-1)^2+1:p^2-1
        printf("%d: 0\n",i)         # p=2,3,4: 1..3,5..8,10..15
    end
    printf("%d: %d/%d\n", p^2,a,b); # p=2,3,4: 4,9,16
    a=-a;
    if a>0                          # the rule is: after a/b, a>0 output -a/b
        do
            if b==1 b=a+1;a=1; else a++;b--; end
        until 1==gcd(a,b)
    end
    p++;
until 0


text:
Print the first 128 prime numbers without using any reserved words
The obvious solution would be to just print them as a string, but is it possible to write a shorter code?
Requirements:

No input should be processed, and the output should be in the form of 2 3 5 7 11 13 ... etc.
No reserved words in the language are used at all
The language should at least allow structured programming, and have reserved words (otherwise point 2 would be moot).

first I had exclusively C/C++ in mind, but extended the question while still trying to prevent cheating

Unfortunately for me, Tcl has no reserved words.

This challenge is quite old and while clear at the time it was asked we now have different standards for clarity that have to be met.  I've closed it for that reason.

C, 60 chars
The "no keywords" limitation doesn't matter here. I'm pretty sure that improving it, if possible, won't be done by adding keywords.
n=2;main(m){n<720&&main(m<2?printf("%d ",n),n:n%m?m-1:n++);}

Alternate version:
The output isn't as nice, but I like the printf abuse.
n=2;main(m){n<720&&main(m<2?printf("%*d",n,n):n%m?m-1:n++);}

The trick in both solutions is to merge two loops (implemented by recursion) into one.
n is the next potential prime, m the next potential divisor.
In each recursive call, we either increment n (while setting m to its previous value) or decrement m.

Python, 108 chars
Python was not made for this challenge.  Wanna print?  That's reserved.  Well, how about we use stdout?  Well, that's gonna cost an import... you guessed it, reserved.  Well... I'm on unix, so I can open up the file descriptor 1, which happens to be stdout.  Hack!
Man, and iteration?  Nothing but eval.  No loops, of course, but we can't even define a function with def or lambda. And to add insult to injury, we can't even use list comprehension!  I always look for an excuse to use things like map(p.__mod__,...) in code golf... comprehension is always better.  Until now, that is.
p=1
eval(compile("p+=1;open('/dev/fd/1','w').write('%s '%p*all(map(p.__mod__,range(2,p))));"*720,'','exec'))

Now, you might complain that exec is a keyword, even though I didn't use the keyword (I didn't even eval an exec).  Well, here's a 117-character solution which doesn't use 'exec'.
p=2
s="eval('('+s*(p<720)+')',open('/dev/fd/1','w').write('%s '%p*all(map(p.__mod__,range(2,p)))),{'p':p+1})";eval(s)

print isn't reserved in Python3 :) you can use __import__, but that's gonna cost characters

JavaScript (80 chars)
eval((s=Array(719)).join("s[j=++n]?j:"+s.join("s[j+=n]=")+"r+=n+' ';"),r="",n=1)

Run in console of your webbrowser.
Used a prime sieve, which turned out to be very condensed.

C, 87 chars
d;p(n){--d<2||n%d&&p(n);}r(n){p(d=n);d<2&&printf("%d\n",n);++n<720&&r(n);}main(){r(2);}

(I tried to write it in a more functional style, but my inability to use return kind of killed that plan.)

C, 183 chars
#define q j*j<k?i%p[j++]||(i++,j=0):printf("%d\n",p[j=0,k++]=i++)
#define A q;q;q;q;q;q;q;q
#define B A;A;A;A;A;A;A;A
#define C B;B;B;B;B;B;B
main(){int i=2,j=0,k=0,p[999];C;C;C;C;C;}

Well, here's a quick first attempt.  I believe this should satisfy the requirements.  I'm using simple trial division to find the primes and an unrolled loop constructed using the preprocessor to iterate it until I've found enough of them.  The number of repetitions has been tweaked so that exactly 128 primes are printed.

C, 134 chars
Here's an alternate solution that tries to avoid using words as much as possible, reserved or otherwise:
main(i){i<9?main(2953216):i>4097?--i&4094?i/4096%(i%4096)?main(i):
main((i/4096-1)*4097):printf("%d\n",i>>12,main((i/4096-1)*4097)):0;}

All it uses is printf and main with a single argument.

Mathematica 50 characters
I'm not sure how to interpret "reserved words" for Mathematica but I want to play so I'll take it to mean doing without built-in functions to generate primes or test for primality.
Fold[#2Cases[#/#2,1|_Rational]&,#,#]&@Range[2,719]

Haskell, 72 characters
main=putStrLn.unwords$take 128[show p|p<-[2..],all((>0).mod p)[2..p-1]]

Admittedly, avoiding keywords isn't too difficult in Haskell.

K (ngn/k), 31 bytes
x,1_&&/720#'!'x:24\234925135391

Try it online!

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:
Sum of (at most) 5 primes
Terence Tao recently proved a weak form of Goldbach's conjecture!  Let's exploit it!
Given an odd integer n > 1, write n as a sum of up to 5 primes.  Take the input however you like, and give output however you like.  For example,
def g(o):
    for l in prime_range(o+1):
        if l == o:
            return l,
        for d in prime_range(l+1):
            for b in prime_range(d+1):
                if l+d+b == o:
                    return l,d,b
                for c in prime_range(b+1):
                    for h in prime_range(c+1):
                        if l+d+b+c+h == o:
                            return l,d,b,c,h

is Sage code that takes an integer as input, and returns a list of integers as output whose sum is n.  By Tao's theorem, this will always terminate!
Input
An odd integer n.  You decide how to take the input, but if it's weird, explain it.
Output
Rather open-ended.  Return a list.  Print a string.  Gimme one, a few, or all.  Leave crap lying around on the stack (GS, Piet, etc) or in a consecutive (reachable) memory block (BF, etc) in a predictable manner.  For these later cases, explain the output.  In all cases, what you return / print / whathaveyou should be a straightforward representation of a partition of n into primes with fewer than 6 parts.
Scoring
This is code golf, smallest byte count wins.
Bonus! if the word 'goldbach' appears as a subsequence (not necessarily consecutive; just in order. Case doesn't matter) of your program subtract 8 points.  The code above is an example of this.

The first number to check, odd integer > 1, is 3. Which sum of primes produces 3? Don't I see the obvious?

The 'obvious' is linguistic.  Since 3 is prime, it's the sum of 1 prime.  Smartass response: Conway would say that 3 is the sum 7 + (-1) + (-1) + (-1) + (-1).

A single value is not a sum. I would suggest simply starting with values > 3 instead of introducing negative values.

A single value is a sum.  The comment about negative values was a smartass remark, as explicitly noted.

"substring (not necessarily consecutive; just in order...)"  This is called a subsequence.

J, 29
(#~y=+/@>),{5$<0,p:i._1 p:>:y

Assumes input is in y.  Value of expression is list of boxes of list of 5 primes or 0 that sum to y.

   y =. 16
   (#~y=+/@>),{5$<0,p:i._1 p:>:y
+----------+----------+----------+----------+----------+---------+----------+----------+----------+----------+----------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+---------+------...
|0 0 0 3 13|0 0 0 5 11|0 0 0 11 5|0 0 0 13 3|0 0 2 3 11|0 0 2 7 7|0 0 2 11 3|0 0 3 0 13|0 0 3 2 11|0 0 3 11 2|0 0 3 13 0|0 0 5 0 11|0 0 5 11 0|0 0 7 2 7|0 0 7 7 2|0 0 11 0 5|0 0 11 2 3|0 0 11 3 2|0 0 11 5 0|0 0 13 0 3|0 0 13 3 0|0 2 0 3 11|0 2 0 7 7|0 2 0 ...
+----------+----------+----------+----------+----------+---------+----------+----------+----------+----------+----------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+---------+------...

Not enough letters to earn any bonus points.

nicely done! I think no language could beat J at this challenge.

Mathematica, 38
IntegerPartitions[n,5,Prime~Array~n,1]

Can't find a way thru WA ...

I've got access to Mathematica, and it worked on all the inputs I gave it.

imagine if the IntegerPartitions function was named Goldbach... ;)

@w0lf even so, it'd be 1 more than J >_>

@Rixius no, it would score 21 in that case, 8 less than J.

C, 192-8 = 184 chars
Contains "Goldbach" consecutively (excluding punctuation), and "Tao" as well.
When the sum is less than 5 primes (i.e. always), prints zeros (16 = 0+0+0+3+13)
Read the number from standard input: echo 30 | ./prog.
#define T(x)for(x=0;x<=s;b=&x,c(++x))
G,o,l,d,*b,a;c(h)
{(*b-1?h<3:++*b)||c(*b%--h?h:++*b);}
main(s){
    scanf("%d",&s);
    T(G)T(o)T(l)T(d)T(a)o+G+l+d+a-s?0:exit(printf("%d+%d+%d+%d+%d\n",G,o,l,d,a));
}

Old version (179 chars), which can find only sums of exactly 5 primes (and therefore fails for x<10):
#define T(x)for(x=2;x<s;b=&x,c(++x))
G,o,l,d,*b,a;c(h)
{h<3||c(*b%--h?h:++*b);}
main(s){
    scanf("%d",&s);
    T(G)T(o)T(l)T(d)T(a)o+G+l+d+a-s?0:exit(printf("%d+%d+%d+%d+%d\n",G,o,l,d,a));
}

Explanation:
c sets *b to the next prime (including *b itself if it's prime).
T builds a for loop, which advances one of the variables G,o,l,d,a to the next prime.
Within all for loops, we check if the sum matches, and print&exit if it does.

G,o,l,d,*b,a;c(h) is a nice touch!

this fails for n=3

@boothby, you're right, it only finds some of 5 primes, not less.

user_unknown has a good solution for this: consider zero prime for the sake of the sum

@boothby, changed. Cost me more than I'd like, because my logic naturally treats 1 as prime, and when starting with 0 I need to skip it.

Brachylog, 9 bytes
~+.ṗᵐl≤5∧

Try it online!
~+.          Output (.) should sum to the input,
   ṗᵐ        consist of all primes,
     l≤5     and have length ≤ 5.
        ∧    (Don't unify that 5 with the implicit output variable.)

You can save a byte by changing the order. Also note that the question states that the input is odd

@H.PWiz And another one like this.

Ruby 138 124 117 - 8 = 109
require'mathn'
def g(o,l=[])
p l if l.inject(:+)==o#db
(l.last||1..o).each{|d|d.prime?and g(o,l+[d])if l.count<5}
end

Call with g(<number>).
Sample output:
[2, 2, 2, 2, 19]
[2, 2, 3, 3, 17]
[2, 2, 3, 7, 13]
...

Test: http://ideone.com/rua7A

Just putting #db on line 3 would be enough for the bonus: you'll get the ach from .each.

What do you mean 'fixed output format'?  This one's totally open -- you can nix the spaces if you like.

@IlmariKaronen Great tip! I've edited my post. Thanks!

@boothby Thank you for noticing this. I saw the sample output and thought it was a requirement. I see now that output format is open. Updated.

PHP 143 122 - 8 = 114
EDIT: Saved a few bytes on output, removed the explicit function call.
<?function g($o,$l,$d,$b){for(;$o>=$b=gmp_intval(gmp_nextprime(+$b));)echo$b^$o?$l<4&&g($o-$b,$l+1,"$d$b,",$b-1):"$d$b
";}

Unrolled:
<?
function g($o,$l,$d,$b){
  for(;$o>=$b=gmp_intval(gmp_nextprime(+$b));)
    echo$b^$o?$l<4&&g($o-$b,$l+1,"$d$b,",$b-1):"$d$b
";}

Call with @g(<number>); Sample output for n=27:
2,2,2,2,19
2,2,3,3,17
2,2,3,7,13
2,2,5,5,13
2,2,5,7,11
2,2,23
2,3,3,19
2,3,5,17
2,3,11,11
2,5,7,13
2,7,7,11
3,3,3,5,13
3,3,3,7,11
3,3,5,5,11
3,3,7,7,7
3,5,5,7,7
3,5,19
3,7,17
3,11,13
5,5,5,5,7
5,5,17
5,11,11
7,7,13

Hmm... your submitted code doesn't seem to work.  You've got a some funny stuff ~õ;} at the end...

~õ (chr(245)) is shorthand for "\n". In this instance, it's not actually necessary. I'll remove it from the solution.

code fails for n=3.

@boothby I don't believe it does. For n=3, it outputs the number 3, and then terminates (as there are no other sums of primes which are 3). What were you expecting it to produce?

I don't see any output.  Works fine for 5, 7, 9, 11.  http://ideone.com/cMNR8  Also, note that you're free to define the function and not call it.

I don't know what to say, other than that Ideone doesn't handle php correctly; I've noticed this on other problems as well. PHP 5.3.6 running under Windows 7, and PHP 5.4.3 running under Ubuntu 11.04 both produce the correct output. Not calling the function explicitly would save 17 bytes, if I could figure out a different way to work 'goldbach' in ;)

Ruby 2 -rmathn, 66 bytes - 8 = 58
g=->o,*l{o==l.reduce(:+)?p(l):l[5]||b=Prime.each(o){|x|g[o,*l,x]}}

Heavily based on GolfWolf's answer, but since it's 6 years old I'm going to post my own instead of nitpicking. Advances in technology include the stabby lambda, using reduce instead of inject for the free d, a terse way of stopping at partitions of 5, and Prime.each(o), which iterates over all primes less than or equal to o (and furnishes an ach). Maybe in another 6 years there'll be a better way of using the b.

Scala 137-8=129
def g(o:Int)={val l=0+:(2 to o).filterNot(d=>(2 to d-1).exists(d%_==0))
for(b<-l;a<-l;c<-l;h<-l;e<-l;if(b+a+c+h+e==o))yield{(b,a,c,h,e)}}

After boothby's hint: eliminated one function call, allow to interpret 3 as the sum of 3 and nothing, remove input from output - saves another 20 chars.
Bonus emphasizing:

def g(o:Int)={val l=0+:(2 to o).filterNot(d=>(2 to d-1).exists(d%_==0))
   for(b<-l;a<-l;c<-l;h<-l;e<-l;if(b+a+c+h+e==o))yield{(b,a,c,h,e)}}

Invocation and result:
println (l(17))
Vector((17,0,0,2,2,13), (17,0,0,2,13,2), (17,0,0,3,3,11), ...

The output repeats x for every list to sum up to x, and then shows the 5 summands. 0 for missing summand, i.e. 2+2+13.
Ungolfed:
// see if there is some x, such that o%x is 0.
def dividable (o:Int) = (2 to o-1).exists (x=> o % x == 0)

// +: is a kind of cons-operator for Vectors
def primelist (d: Int) = {
  val s = 0 +: (2 to d).filterNot (b => dividable (b))
  for (a <- s;
    b <- s;
    c <- s;
    h <- s;
    e <- s;
    if (a+b+c+h+e == d)) yield {(a,b,c,h,e)}
}

I'm not familiar with Scala.  How does this get called?  Can you post a working example to http://ideone.com?

You better execute it on simply-scala because it needs less boilerplate than IDEone. For invocation, println (l(17)) for example. The output looks typically like Vector((17,0,0,2,2,13), (17,0,0,2,13,2), (17,0,0,3,3,11) and means: 17 is to be summed, and the summands are 0, 0 (zero means absence of summand) 2+2+13. The link to simply scala is already documented on meta

cool, thanks!  Looks like you can save a few characters: yield{(d,a,... -> yield{(a,... and by packing the definition of g into filterNot(...).  However.  This fails for n=3.

Do (2 to d) instead of (2 to d-1), but I don't agree that 3 is the sum of 3. If you sum up a Set, yes, it can be an empty set, or a Set consisting of one number. But building a sum which leads to n - I only change my code under protest.

As noble as your obstinate refusal to shorten your answer may be, your cause is undermined by your very answer.  You're returning lists whose sum is 3.  One such should be (0,0,0,0,3).

@boothby: That's what I meant by 'I change my code under protest' - It is your question, and you define the rules. I can disagree on the way to express the rules, but I understood what you want.

ah, fair enough, I misread your previous post.

MuPAD 113 - 8 = 105
g:=[0,ithprime(i)$i=1..n]:f:=_for_in:f(l,g,f(d,g,f(b,g,f(a,g,f(c,g,if l+d+b+a+c=n then print(l,d,b,a,c)end)))))

This version will also print all permutations of every solution:
0, 0, 0, 0, 7
0, 0, 0, 2, 5
0, 0, 0, 5, 2
0, 0, 0, 7, 0
0, 0, 2, 0, 5
...

And yes, it creates a way too long list g. Who cares? :-)
Ungolfed version:
g:=[0].select([$1..n],isprime):
for l in g do
  for d in g do
    for b in g do
      for a in g do
        for c in g do
          if l+d+b+a+c=n then print(l,d,b,a,c); end;
        end
      end
    end
  end
end

I don't have access to mupad -- can somebody check that this works?

Jelly, 19 bytes (but very slow -- advice wanted)
ÆR;0x5Œ!ḣ€5¹©S€i³ị®

Try it online!
ÆR;0x5Œ!ḣ€5¹©€i³ị®     main link, takes one argument N
ÆR                     get all the primes less than N
  ;0x5                 add zero, and then repeat the entire list 5 times
      Œ!               get all the permutations of this huge list (takes a long time!)
        ḣ€5            for each permutation, just take the first 5 numbers
                       (this gives us all possible length-5 combinations of the primes plus zero, with some repeats)
           ¹©          save that list to register
              S€       take the sum of every permutation in the list...
                i³     and find the index of our first argument N in that list of sums
                  ị®   then recall our list of permutations, and get the correct permutation at that index!

If you have any ideas to make it faster and shorter, please let me know!

12 bytes. ṗÐ€5 produces all combinations of primes with lengths one through five. S=¥ checks if the sum of one of the elements is equal to the chain's argument and Ðf keeps only those elements. Ẏ is only there to put all lists of primes at the same level in the list

Now 10 bytes since Ɱ and Ƈ have been added as aliases for Ð€ and Ðf

Vyxal, 9 bytes
Ṅ'L5≤næA∧

Try it Online!
Outputs all possible sums.
Explained
Ṅ'L5≤næA∧   # Takes a single integer n and returns a list of lists
Ṅ           # Push all the integer partitions (ways to sum to) of n
 '          # and keep only those where:
  L5≤       #   the length of the partition is less than or equal to 5 (can also be 6<)
        ∧   #   and
     næA    #   all integers in the partition are prime

Japt, 19 bytes
Hideous, and slow as hell! Will crap out on inputs higher than 5.
ÆõÃc fj à l§5 æ@¶Xx

Try it
ÆõÃc fj à l§5 æ@¶Xx     :Implicit input of integer U
Æ                       :Map the range [0,U)
 õ                      :  Range [1,U]
  Ã                     :End map
   c                    :Flatten
     f                  :Filter
      j                 :  Prime
        à               :Combinations
          l             :Filter by length
           §5           :  <=5
              æ         :Get the first to return true
               @        :When passed through the following function as X
                ¶       :  U is equal to
                 Xx     :  Sum of X

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


text:
Coding in song - Representing music lyrics in a programming language of your choosing
Write a program in the language of your choosing which when read are the lyrics to a song.  It must be a valid program which can be compiled and run without errors.  While you could technically print to the screen all the lyrics, you're encouraged to do it with style and avoiding string literals whenever possible.
Given that this is difficult on of itself, you're allowed to write a single section of boilerplate code which doesn't count towards being readable in the lyrics.  However, once the block of code begins which must be read as the lyrics to a song, you cannot interrupt it until the song is finished.  You can indicate the beginning and end of the song code with comments.  Please also specify the lyrics themselves as you would read the code.  You can be "liberal" with your interpretation so long as you don't stray too far from what's written, otherwise it will cost you points.
Partial song lyrics are allowed, though you get double points for having the words to an entire song.  Judging is divided into 3 categories:

10 points - Originality
10 points - Song difficulty
20 points - Representation of that song in code.

For each submission, I'll give you your score in a comment below. If you edit your answer, just give me a comment indicator and I'll re-evaluate it accordingly.  However in order to be fair, each re-evaluation subtracts 2 points from your total score.
An example might be the following:
public class Song {
    public String play() {
        // Song begin
        try {
            if(this instanceof TheRealLife || this instanceof JustFantasy) {
                throw new InALandSlide();
            }
        } catch (InALandSlide e) {
        }
        return "No \"FromReality\"";
        // Song end
    }

    public static void main(String [] args) {
        Song song = new Song();
        song.play();
    }
}

Which gets read:
Is this TheRealLife?
Or is this JustFantasy?
Caught InALandSlide.
No escape \"FromReality\"

Instrumentals aren't allowed, wise guys.  ;)

This is an interesting concept, and I'm interested to see the results, but this isn't very objective. How does one determine the 'difficulty' of the song? (etc.)

Strongly reminds me of this IOCCC winner

@Gaffi, mostly length, but also the wordiness.  Example of a song which would score 0 might be this song is just 6 words long.

How about the HQ9 program 9? :P

Are there extra points if the program actually does a useful computation?

@Li-aungYip No.  How would you determine if a computation is useful exactly?

Well, take @ugoren's answer... :P

Hint for anyone trying to find a suitable song for coding: "Escape to the Void" seems to be an promising title :) - http://www.lyricstime.com/sepultura-escape-to-the-void-lyrics.html

Agree with Gaffi. Objective winning criteria means that even if the questioner shuffled off this mortal coil tomorrow, the rest of us could still determine a winner based on the standards delineated by the question. Even a popularity contest is technically objective, because "number of upvotes" is taken as the objective measure of "popularity". Here, you've set yourself up as the Olympic judge of aesthetics and difficulty, which is thoroughly subjective.

@JonathanVanMatre Haven't quite shuffled off just yet.  I answer your question with another question:  How do Olympic judges judge artistic performances such as ice skating?  They try to make judging as objective as possible by eliminating "I just like it" type scores.  I tried to do my best in this case.

You might be able to tag it as 'popularity-contest'.

Probable source: related: https://imgur.com/fuDDhdL

Python - 8+4+15 = 27 points
Here's on couple of stanzas from The Hunting of the Snark by Lewis Carroll.
It calculates a number, based on the algorithm suggested in the poem, and uses it to state a proof about the voice of the jubjub.
class taking:
    def __init__(self, n): convenient.val = (n)
    def __enter__(self): pass
    def __exit__(self, type, value, traceback): pass
def a(x,y): x.val = y(x.val); return True
class We:
    def __init__(self): self.val=0
    def __add(self, y): return y+sum(self.x)
    def add(self, *x): self.x = x; return self.__add
    def multiply(self,x,by,diminished_by): self.val *= by-diminished_by
    def proceed2divide(self,x,by): self.val /= by
    def subtract(self,x): self.val -= x; return True
perfectly = lambda x: x and not not x
def must_be(x):
    if x:
        print "\n".join(["Tis the %s of the Jubjub!"%["voice","note","song"][x%3] for x in range(out.val)])
        return out.val
out=convenient=as_you_see=we=then=the=We()
_ = exactly = 15
with\
\
    taking(3) as the_subject_to_reason_about:
    a(convenient, #2 state
    we.add(7,_ & 10)) and then.multiply(out,
    by=1000, diminished_by=8)

    the_result = we.proceed2divide(as_you_see,
    by=992)
    then.subtract(17) and the; answer = must_be(
    exactly and perfectly(True))

The original text:

"Taking Three as the subject to reason about—
     A convenient number to state—
   We add Seven, and Ten, and then multiply out
     By One Thousand diminished by Eight.
"The result we proceed to divide, as you see,
     By Nine Hundred and Ninety Two:
   Then subtract Seventeen, and the answer must be
     Exactly and perfectly true.

It's nice, I like it.  Originality:  8/10, Song difficulty:  4/10, Representation of that song in code: 15/20, making your final score 27.  Shame you couldn't use the whole song.

I think the "entire song" criterion has way too much weight. It would have been much easier to pick a one line song.

Given that The Hunting of the Snark is over 500 lines long, that would indeed have been an impressive feat.

@breadbox, even a single fit would be an impressive feat, the whole thing would be an agony.

Python (8+7+15=30)
Valid Python code synctactically although it does not do anything particulary useful ;-)
from sys import exit as stops ; import os
thing = [] ; me = can = remember = False ; this = open(__file__)
def terrible(v): return v

# ==== start song snippet

me = can = remember = not any(thing)
can = not this.tell(), [True, "dream"]
locals()["deep"] = {"down":{"inside":{"feel_to":"scream"}}}
if `this` + (terrible("silence")): stops(me)

# ===== end song snippet

How it is supposed to be read:

I can't remember anything.
Can't tell if this is true or dream.
Deep down inside I feel to scream.
This terrible silence stops me....
(Metallica - One)

Wow, difficult song choice, but very impressed how you pulled that off.  Originality: 8/10, Song difficulty: 7/10, Representation of that song in code: 15/20, making your final score 30.

C
Somewhat sloppy, I wrote this in about 15 minutes for giggles. Compiles and runs fine with latest version of G++/MinGW (doesn't really do much, though). You can figure this out just fine by yourself, I think:
class Rick {

public:

    struct us { bool you; bool me; };

    bool giveYouUp()  { return false; }
    bool letYouDown() { return false; }
    bool runAround()  { return false; }
    bool desertYou()  { return false; }
    bool makeYouCry() { return false; }
    bool sayGoodbye() { return false; }
    bool tellALie()   { return false; }
    bool hurtYou()    { return false; }

    bool thinkingOf(bool whatImThinkingOf) { return whatImThinkingOf; }
    bool justWantTo(bool whatIWantToDo) { return whatIWantToDo; }
    bool tellYou(bool whatIWantToTellYou) { return whatIWantToTellYou; }

    void roll() {
        bool gonna = false;
        while (gonna) {
            giveYouUp();
            letYouDown();
            gonna = (runAround() && desertYou());
            makeYouCry();
            sayGoodbye();
            gonna = (tellALie() && hurtYou());
        }

        bool strangersToLove = true;
        us we = {!strangersToLove, !strangersToLove};

        bool knowTheRules = true;
        bool you = knowTheRules, I = knowTheRules;

        bool aFullCommitment = true;
        we.me = thinkingOf(aFullCommitment);

        int me = 0;
        Rick* guys[] = {this, nullptr, nullptr, nullptr, nullptr};

        bool howImFeeling = true;
        we.me = justWantTo(tellYou(howImFeeling));

        bool understand = true;
        while (we.you != understand) {
            we.you = understand;
        }
    }

};

int main() {
    Rick rick;
    rick.roll();

    return 0;
}

Scala(48 = 2*(7+4+13))
It's  Linux! song.
object Song extends App {
  // Compose a song
  trait Compose {
    override def toString = {
      val token = """^.*\$(.*)\$.*$""".r
      val token(verse) = super.toString
      verse.replaceAll("([a-z])([A-Z])", "$1 $2").capitalize
    }
    def excl(ex: String) = println(this + ex)
    def !!(c: Compose) = { excl("."); c }
    def ***(c: Compose) = { excl("..."); c }
    def !(c: Compose) = { excl("!"); c }
    def *(c: Compose) = { excl(","); c }
    def ! = excl("!")
  }
  // It's linux  - lyrics
  case object ItBootsUpFine extends Compose
  case object AllOfTheTime extends Compose
  case object TuxThePenguinIsGreat extends Compose
  case object aPieInTheFace extends Compose
  case object ToTheManIHate extends Compose
  case object EveryoneKnowsItsLinux extends Compose
  case object StableForYouAndMe extends Compose
  case object ItsLinux extends Compose
  case object NoMoreBSODs extends Compose
  case object BetterThanNT extends Compose
  case object BestOfAllItsFree extends Compose
  case object FreeSoftwareForYouAndMe extends Compose
  case object LinuxGPLd extends Compose

  // Singer to sing a song
  def sing(song: => Unit) = { song }

  // Song begins
  sing {
      ItBootsUpFine!
      AllOfTheTime!!
      TuxThePenguinIsGreat!
      aPieInTheFace*
      ToTheManIHate***
      EveryoneKnowsItsLinux!
      ItsLinux!
      ItsLinux!
      StableForYouAndMe!
      ItsLinux!
      ItsLinux!
      NoMoreBSODs!
      ItsLinux!
      ItsLinux!
      BetterThanNT!
      ItsLinux!
      ItsLinux!
      BestOfAllItsFree!
      FreeSoftwareForYouAndMe***
      LinuxGPLd!
  }
  // Song ends
}

Output:
It Boots Up Fine!
All Of The Time.
A Pie In The Face,
Tux The Penguin Is Great!
To The Man IHate...
Everyone Knows Its Linux!
Its Linux!
Its Linux!
Stable For You And Me!
Its Linux!
Its Linux!
No More BSODs!
Its Linux!
Its Linux!
Better Than NT!
Its Linux!
Its Linux!
Best Of All Its Free!
Free Software For You And Me...
Linux GPLd!

Originality: 7/10, Song difficulty: 4/10, Representation of that song in code: 13/20.  Since you put the whole song down, that doubles your score, so that means your final score is 48.  Nice one.  :)

PHP
Tried my favorite song, Stairway to Heaven.
$GLOBALS['sign']= 'words';

class lady extends me // there is a lady
{
  function __construct(){   // who is sure
    global $glitters = 'gold'; // all that glitters is gold
    $buy('stairway_to_heaven'); // and shes buying the stairway to heaven
  }
  $know[] = 'stars are close'; // when she get's there she knows, the stars are close
  function word(){  // with a word she can get
    debug_backtrace(); // what she come for
  }

  $this->buy('stairway_to_heaven'); // and she's buying the stairway to heaven

  $sign = 'words'; // there is a sign on the door
  if(!$sign === $GLOBALS['sign']) // but she want to be sure, cause you know sometimes words have 2 meanings
    exit();

  in_array($tree / $brook, $songbird ? 'sings'); // (literal) in a tree by the brook, there is a songbird who sings

  mysql_real_escape_string($_GET['thoughts']); // sometimes all of our thoughts are misgiven
  for ($i=0;$i<2;i++)
    parent::wonder(); // makes me wonder , makes me wonder

}

How is it read :

There's a lady who's sure all that glitters is gold  And she's
  buying a stairway to heaven.  When she gets there she knows, if
  the stars are all close  With a word she can get what she came
  for.  Ooh, ooh, and she's buying a stairway to heaven.
  There's a sign on the wall but she wants to be sure  'Cause you
  know sometimes words have two meanings.  In a tree by the brook,
  there's a songbird who sings,  Sometimes all of our thoughts are
  misgiven.  Ooh, it makes me wonder,  Ooh, it makes me wonder.

C
Here's a complete song.
You can listen to it in Mama Lisa's World.
Note that the song is included as-is, including the punctuation.
#define breath,
#define smell breath
#define an;}Englishman; main(){printf("%d\n",sizeof
struct x{int
// Song starts here
Fee, fa, fie, fo, fum,
I smell the breath of an Englishman.
// Song ends here
I);}

Prints the number 4.

Ruby
My take at as close representation as possible. It's easy with Ruby's call chaining.
$lines = []

def thisline n=2
    caller(n).first.match(/:(\d+):/)[1].to_i
end

class Chain < Array
    def method_missing method, *args
        $lines[thisline] = Chain[first, self[1], [method, thisline, args]]
    end

    def -(arg)
        $lines[thisline] = Chain[' - ', thisline, self, arg]
    end

    def tokens
        if size < 3
            if first == :_
                []
            else
                [first.to_s.tr(?_, ?\s).strip]
            end
        elsif size < 4
            [first.to_s.tr(?_, ?\s)] + at(2).tokens
        else
            lhs = case el = at(2)
            when Chain then el.tokens
            when String
                el.empty? ? [?'] : [?', el, ?']
            end

            rhs = case el = at(3)
            when Chain then el.tokens
            when Range then el.first.tokens + ['... '] + el.last.tokens
            end

            lhs + [first.to_s.tr(?_, ?\s)] + rhs
        end
    end
end

def self.method_missing method, *args
    line = thisline(3)

    if args.length > 1
        newlines = args.first.is_a?(String) ? args.first.count(?\n) : 0
        $lines[line] = false
        $lines[line-newlines] = Chain[method, line, Chain[', ', line, *args]]
    else
        $lines[line] = Chain[method, line, *args]
    end
end

####################

The pest in_the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying_our_bones
How will we escape_if the void covers our lungs?
We are buried_in the spewed trash_for ourselves

Blood _, pain - nothing_to_say
Why then_- must_we_die?

Escape to the void
Escape to the void

I look at my face on the other side of the mirror
My face falls down_in pieces full of worms
I burst my rotten heart with my own hands
I'm dying and I can',t_help_myself

Blood _, pain - nothing_to_say
Why then_- must_we_die?

What have I been running from?
I'',m_not_guilty
You've shown me the worst way
Cause you',re_my_victim... the_next_one

The pest in_the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying_our_bones
How will we escape if_the void covers our lungs?
We are buried in_the spewed trash_for ourselves

Blood _, pain - nothing_to_say
Why then_ - must_we_die?

Escape to the void
Escape to the void

####################

$lines.drop_while {|line| !line }.each_with_index {|line, i|
    puts if line.nil?
    next if not line

    line = line.tokens
    line.map!.with_index {|el, j|
        punct = [', ', ' - ', '... ', ?']

        if line[j-1] == ?' and el == ', '
            ''
        elsif punct.include?(el) or punct.include?(line[j+1])
            el
        else
            el + ?\s
        end
    }

    puts line.join
}

Output
The pest in the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying our bones
How will we escape if the void covers our lungs?
We are buried in the spewed trash for ourselves

Blood, pain - nothing to say
Why then - must we die?

Escape to the void
Escape to the void

I look at my face on the other side of the mirror
My face falls down in pieces full of worms
I burst my rotten heart with my own hands
I'm dying and I can't help myself

Blood, pain - nothing to say
Why then - must we die?

What have I been running from?
I'm not guilty
You've shown me the worst way
Cause you're my victim... the next one

The pest in the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying our bones
How will we escape if the void covers our lungs?
We are buried in the spewed trash for ourselves

Blood, pain - nothing to say
Why then - must we die?

Escape to the void
Escape to the void

To do

Multiline commas (arguments)
Multiline dots (method calls)

T-SQL Bone Thugs-N-Harmony
DECLARE @line1 varchar(25);
DECLARE @line2 varchar(25);
DECLARE @line4 varchar(25);
DECLARE @line5 varchar(25);

SET @line1 = 'Wake up, wake up, wake up,';
SET @line2 = 'its the';
SET @line4 = 'to get up, get up get up';
SET @line5 = 'so cash your checks and get up';

SELECT @line1 as Layzie, @line2 as Bizzy,
CONVERT(date,DATEADD(day, -
(SELECT
DATEPART(day, GETDATE())
- 1), GETDATE())) as FirstOfTheMonth,
@line4 as Layzie, @line5 as Bizzy;

Yeah I know I cheated a bit and I might have the members who sang which line wrong also.

C - Bottles of Beer
Compile and run this. Lyrics are put into the source code. Compile and execute output to get next line of song. When it says "Time to go...." then compile and execute with the number of bottles specified on the command line, e.g.:
cl prog.c
prog 32 > prog1.c
cl prog1.c
prog1 > .... etc

The code, tested using VS2005:-
// Time to go to the shop and get some beer
//
//
//
//
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##

char *z [] = {
"void l(char *s,int b){int i;printf(\"// \");for(i=0;i<b;++i)printf(s);",
"printf(\"\\n\");}\nint main(int argc, char *argv[]){\nint i,j,k,x=%d;",
"char*p;\nif(!x&&argc==2)x=atoi(argv[1]);\nif(!x){printf(\"// Time to ",
"go to the shop and get some beer\\n//\\n//\\n//\\n//\\n\");k=7;\n",
"}else{printf(\"// %%d bottles of beer on the wall, %%d bottles of beer",
".\\n\",x,x);printf(\"// Take one down and pass it round, \");\n",
"if(x>1)printf(\"%%d bottles of beer on the wall.\\n//\\n\",x-1);\n",
"else printf(\"no more bottles of beer on the wall.\\n//\\n\");\n",
"k=x>2?x:2;l(\"  ^   \",x);l(\" / \\\\  \",x);l(\"/   \\\\ \",x);",
"l(\"|   | \",x);l(\"|Duf| \",x);l(\"|   | \",x);l(\"----- \",x);}\n",
"for(i=0;i<4;++i){\nprintf(\"// %%s\", i&1 ? \"##.\" : \"\");\n",
"for(j=i&1;j<k;++j)\nprintf(\"%%s#####\",j!=(i&1)?\".\":\"\");\n",
"printf(\"%%s\\n\",i&1?\".##\":\"\");}\nprintf(\"\\nchar *z [] = {\\n\");\n",
"for(i=0;i<sizeof z/sizeof z[0];++i){\nprintf(\"\\\"\");\n",
"for(p=z[i];*p;++p)\nswitch (*p){\ncase '\\n':printf(\"\\\\n\");break;\n",
"case '\\\\':printf(\"%%c%%c\",92,92);break;\n",
"case '%%':printf(\"%%c\",37);break;\ncase '\"':printf(\"%%c%%c\",92,'\"');break;\n",
"default:printf(\"%%c\", *p);break;}\nprintf(\"\\\",\\n\");}\n",
"printf(\"};\\n\");\nfor(i=0;i<sizeof z/sizeof z[0];++i)\n",
"printf(z[i],x?x-1:0);}\n",
};
void l(char *s,int b){int i;printf("// ");for(i=0;i<b;++i)printf(s);printf("\n");}
int main(int argc, char *argv[]){
int i,j,k,x=0;char*p;
if(!x&&argc==2)x=atoi(argv[1]);
if(!x){printf("// Time to go to the shop and get some beer\n//\n//\n//\n//\n");k=7;
}else{printf("// %d bottles of beer on the wall, %d bottles of beer.\n",x,x);printf("// Take one down and pass it round, ");
if(x>1)printf("%d bottles of beer on the wall.\n//\n",x-1);
else printf("no more bottles of beer on the wall.\n//\n");
k=x>2?x:2;l("  ^   ",x);l(" / \\  ",x);l("/   \\ ",x);l("|   | ",x);l("|Duf| ",x);l("|   | ",x);l("----- ",x);}
for(i=0;i<4;++i){
printf("// %s", i&1 ? "##." : "");
for(j=i&1;j<k;++j)
printf("%s#####",j!=(i&1)?".":"");
printf("%s\n",i&1?".##":"");}
printf("\nchar *z [] = {\n");
for(i=0;i<sizeof z/sizeof z[0];++i){
printf("\"");
for(p=z[i];*p;++p)
switch (*p){
case '\n':printf("\\n");break;
case '\\':printf("%c%c",92,92);break;
case '%':printf("%c",37);break;
case '"':printf("%c%c",92,'"');break;
default:printf("%c", *p);break;}
printf("\",\n");}
printf("};\n");
for(i=0;i<sizeof z/sizeof z[0];++i)
printf(z[i],x?x-1:0);}

I make no apologies for my ASCII art!

Quite impressive, but how does it match the challenge? I thought the idea is that you can read the source as a song.

@ugoren: Compile and run the executable with a single parameter, the starting number of beers. Then the program outputs the first verse of the song as source code (well, the lyrics in the top comment). Compile the output and run again to get the next verse and so on.

Very nice, but the idea is not a program that prints the song. It's a program that, when its source is read, IS the song.

Perl performs Barnes & Barnes
Ever since I first learned Perl, I've wanted an excuse to use the -P option. Today, that excuse has finally arrived:
#define cry $$
#define people $_
#define some kill
#define we people
#define whenyoudie END
sub yeah{}

# "When You Die", Barnes & Barnes

whenyoudie { you stop drinking beer }
whenyoudie { you stop being here }
whenyoudie { some people,cry }
whenyoudie { we=say "goodbye" }

                yeah

Run it with -M5.010 in addition to the -P option, like so:
$ perl -PM5.010 whenyoudie
goodbye
Hangup
$


text:
Convert infix expressions to postfix notation
When I saw the title of this closed question, I thought it looked like an interesting code golf challenge.  So let me present it as such:
Challenge:
Write a program, expression or subroutine which, given an arithmetical expression in infix notation, like 1 + 2, outputs the same expression in postfix notation, i.e. 1 2 +.
(Note: A similar challenge was posted earlier in January.  However, I do feel the two tasks are sufficiently different in detail to justify this separate challenge.  Also, I only noticed the other thread after typing up everything below, and I'd rather not just throw it all away.)
Input:
The input consists of a valid infix arithmetical expression consisting of numbers (non-negative integers represented as sequences of one or more decimal digits), balanced parentheses to indicate a grouped subexpression, and the four infix binary operators +, -, * and /.  Any of these may be separated (and the entire expression surrounded) by an arbitrary number of space characters, which should be ignored.1
For those who like formal grammars, here's a simple BNF-like grammar that defines valid inputs.  For brevity and clarity, the grammar does not include the optional spaces, which may occur between any two tokens (other than digits within a number):
expression     := number | subexpression | expression operator expression
subexpression  := "(" expression ")"
operator       := "+" | "-" | "*" | "/"
number         := digit | digit number
digit          := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

1 The only case where the presence of spaces may affect the parsing is when they separate two consecutive numbers; however, since two numbers not separated by an operator cannot occur in a valid infix expression, this case can never happen in valid input.
Output:
The output should be a postfix expression equivalent to the input.  The output expression should consist only of numbers and operators, with a single space character between each pair of adjacent tokens, as in the following grammar (which does include the spaces)2:
expression  := number | expression sp expression sp operator
operator    := "+" | "-" | "*" | "/"
number      := digit | digit number
digit       := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
sp          := " "

2 Again for simplicity, the number production in this grammar admits numbers with leading zeros, even though they're forbidden in the output by the rules below.
Operator precedence:
In the absence of parentheses, the following precedence rules apply:

The operators * and / have higher precedence than + and -.
The operators * and / have equal precedence to each other.
The operators + and - have equal precedence to each other.
All operators are left-associative.

For example, the following two expressions are equivalent:
1 + 2 / 3 * 4 - 5 + 6 * 7
((1 + ((2 / 3) * 4)) - 5) + (6 * 7)

and they should both yield the following output:
1 2 3 / 4 * + 5 - 6 7 * +

(These are the same precedence rules as in the C language and in most languages derived from it.  They probably resemble the rules you were taught in elementary school, except possibly for the relative precedence of * and /.)
Miscellaneous rules:

If the solution given is an expression or a subroutine, the input should be supplied and the output returned as a single string.  If the solution is a complete program, it should read a line containing the infix expression from standard input and print a line containing the postfix version to standard output.
Numbers in the input may include leading zeros.  Numbers in the output must not have leading zeros (except for the number 0, which shall be output as 0).
You are not expected to evaluate or optimize the expression in any way.  In particular, you should not assume that the operators necessarily satisfy any associative, commutative or other algebraic identities.  That is, you should not assume that e.g. 1 + 2 equals 2 + 1 or that 1 + (2 + 3) equals (1 + 2) + 3.
You may assume that numbers in the input do not exceed 231 − 1 = 2147483647.

These rules are intended to ensure that the correct output is uniquely defined by the input.
Examples:
Here are some valid input expressions and the corresponding outputs, presented in the form "input" -> "output":
"1"                  ->  "1"
"1 + 2"              ->  "1 2 +"
" 001  +  02 "       ->  "1 2 +"
"(((((1))) + (2)))"  ->  "1 2 +"
"1+2"                ->  "1 2 +"
"1 + 2 + 3"          ->  "1 2 + 3 +"
"1 + (2 + 3)"        ->  "1 2 3 + +"
"1 + 2 * 3"          ->  "1 2 3 * +"
"1 / 2 * 3"          ->  "1 2 / 3 *"
"0102 + 0000"        ->  "102 0 +"
"0-1+(2-3)*4-5*(6-(7+8)/9+10)" -> "0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -"

(At least, I hope all these are correct; I did the conversion by hand, so mistakes might have crept in.)
Just to be clear, the following inputs are all invalid; it does not matter what your solution does if given them (although, of course, e.g. returning an error message is nicer than, say, consuming an infinite amount of memory):
""
"x"
"1 2"
"1 + + 2"
"-1"
"3.141592653589793"
"10,000,000,001"
"(1 + 2"
"(1 + 2)) * (3 / (4)"

Is Lisp like notation acceptable? For example 1 2 3 4 + mean  1 + 2 + 3 + 4 .

@Hauleth: Not in this challenge, no.  Besides, without parentheses, how would you parse 1 2 3 4 + *?

So, no trailing whitespace (including a newline) is permitted in the otuput?

@breadbox: Trailing newlines are OK. In fact, let me explicitly clarify that any trailing whitespace is allowed.

I have a solution which outputs "0 1 - 2 3 - 4 * 5 6 7 8 + 9 / - 10 + * - + " for the last valid example, which seems correct to me. Can you check? (Notice the last + operator)

@coredump: What does your solution output for "1+2-3"? The correct solution, according to the given precedence and associativity rules, should be "1 2 + 3 -"; does yours output "1 2 3 - +"? (Of course, those are mathematically equivalent, but the challenge specifies a particular parsing.)

@IlmariKaronen "1 2 3 - +", indeed. I see now, thanks.

@coredump The OP is correct with their answer to the final example. See http://www.meta-calculator.com/learning-lab/how-to-build-scientific-calculator/infix-to-postifix-convertor.php for an online solution

Shell utils -- 60 chars
bc -c|sed -re's/[@iK:Wr]+/ /g;s/[^0-9]/ &/g;s/ +/ /g;s/^ //'

Fixed the various problems, but it got a lot longer :(

This is rather clever, except that it doesn't seem to handle numbers greater than 9 correctly.

@breadbox, sed -re's/[:@iKWr]+/ /g' fixes it at 1 character cost.

oops, though @ugoren suggestion doesn't work since consecutive operators no longer have a space between them; I've gotta come up with a fix for that too

C, 250 245 236 193 185 chars
char*p,b[99];f(char*s){int t=0;for(;*p-32?
*p>47?printf("%d ",strtol(p,&p,10)):*p==40?f(p++),++p:
t&&s[t]%5==2|*p%5-2?printf("%c ",s[t--]):*p>41?s[++t]=*p++:0:++p;);}
main(){f(p=gets(b));}

Here's a readable version of the ungolfed source, that still reflects the basic logic. It's actually a rather straightforward program. The only real work it has to do is to push a low-associativity operator onto a stack when a high-associativity operator is encountered, and then pop it back off at the "end" of that subexpression.
#include <stdio.h>
#include <stdlib.h>

static char buf[256], stack[256];
static char *p = buf;

static char *fix(char *ops)
{
    int sp = 0;

    for ( ; *p && *p != '\n' && *p != ')' ; ++p) {
        if (*p == ' ') {
            continue;
        } else if (*p >= '0') {
            printf("%ld ", strtol(p, &p, 10));
            --p;
        } else if (*p == '(') {
            ++p;
            fix(ops + sp);
        } else {
            while (sp) {
                if ((ops[sp] == '+' || ops[sp] == '-') &&
                        (*p == '*' || *p == '/')) {
                    break;
                } else {
                    printf("%c ", ops[sp--]);
                }
            }
            ops[++sp] = *p;
        }
    }
    while (sp)
        printf("%c ", ops[sp--]);
    return p;
}

int main(void)
{
    fgets(buf, sizeof buf, stdin);
    fix(stack);
    return 0;
}

Save chars by removing if. E.g. if(!*p||*p==41)return p;s[++t]=*p;} -> return*p&&*p-41?s[++t]=*p:p;

K&R style declaration: *f(p,s)char*p,s;{

It's an error to return if the if test fails. 2. I know, but K&R function decls is where I draw the line. I just can't go back to them.

I thought the return is at the function end anyway. Missed the }} and for. But here's an imrovment: printf(" %ld"+!a,...

Also I think you should make p global (the recursive call just assigns the callee p back to the caller's). Then do f(p=gets(b)).

Doh! Can't believe I didn't see that myself. Either one, actually.

Another one - I think you can improve your while using the formula x%7%5. It's 0 for * and /, not for + and -. And *p==40 can, I think, be replaced with *p<41.

You can shorten it further by making everything an expression. Not trivial, but possible. You can convert the inner while to a recursive function, then move all the for contents into the condition, so the for will stop when you now return.

Great minds think alike! The specific tests you propose don't quite work because they also match the NUL byte. But the general approach is sound.

I thought you can't have \0 if t>0 and the expression is valid. Or maybe it was true before your latest changes. Anyway your test is also very short.

All I can save now is the parentheses around (s[t]%5==2|*p%5-2) - can be removed with t&&. Maybe, just maybe, you can also throw f and make main recursive. main(char*s){s-1?...:gets()... could be really nice.

Excellent work. I tried to replace the for with recursion, but it just makes it longer. All I have left is one byte to save: Make t a parameter and s a local variable (initialized to p). The calls become f(!p++) and p=gets(b);f(0).

Python 2, 290 272 268 250 243 238 bytes
Now finally shorter than the JS answer!
This is a full program which uses a basic implementation of the shunting yard algorithm. Input is given as a quoted string, and the result is printed to STDOUT.
import re
O=[];B=[]
for t in re.findall('\d+|\S',input()):exec("O=[t]+O","i=O.index('(');B+=O[:i];O=O[i+1:]","while O and'('<O[0]and(t in'*/')<=(O[0]in'*/'):B+=O.pop(0)\nO=[t]+O","B+=`int(t)`,")[(t>'/')+(t>')')+(t>'(')]
print' '.join(B+O)

Try it online!

Explanation:
The first thing we need to do is convert the input into tokens. We do this using by finding all matches of the regex \d+|\S, roughly translated to "any group of digits, and any non-space character". This removes whitespace, parses adjacent digits as single tokens, and parses operators seperately.
For the shunting yard algorithm, there are 4 distinct token types we need to handle:

( - Left parenthesis
) - Right parenthesis
+-*/ - Operators
9876543210 - Numeric literals

Thankfully, the ASCII codes of these are all grouped in the order shown, so we can use the expression (t>'/')+(t>')')+(t>'(') to calculate the token type. This results in 3 for digits, 2 for operators, 1 for a right parenthesis and 0 for a left parenthesis.
Using these values, we index into the large tuple after exec to get the corresponding snippet to execute, based on the token type. This is different for each token and is the backbone of the shunting yard algorithm. Two lists are used (as stacks): O (operation stack) and B (output buffer). After all the tokens have been run, the remaining operators on the O stack are concatenated with the output buffer, and the result is printed.

Bash w/ Haskell w/ C preprocessor sed, 180 195 198 275
echo 'CNumO+O-O*fromInteger=show
CFractionalO/
main=putStr$'$*|sed 's/C\([^O]*\)/instance \1 String where /g
s/O\(.\?\)/a\1b=unwords\[a,b,\"\1\"];/g'|runghc -XFlexibleInstances 2>w

At last, it's not longer than the C solution anymore. The crucial Haskell part is almost as lazy as the bc solution...
Takes input as command-line parameters. A file w with some ghc warning messages will be created, if you don't like this change to runghc 2>/dev/null.

Basked? (Bash+Haskell+sed)

Prolog (SWI-Prolog), 113 bytes
c(Z,Q):-Z=..[A,B,C],c(B,S),c(C,T),concat_atom([S,T,A],' ',Q);term_to_atom(Z,Q).
p(X,Q):-term_to_atom(Z,X),c(Z,Q).

Try it online!
SWI Prolog has a much better set of builtins for this than GNU Prolog does, but it's still held back somewhat by the verbosity of Prolog's syntax.
Explanation
term_to_atom will, if run backwards, parse an infix-notation expression (stored as an atom) into a parse tree (obeying the usual precedence rules, and deleting leading zeroes and whitespace). We then use the helper predicate c to do a structural recursion over the parse tree, converting into postfix notation in a depth-first way.

Javascript (ES6), 244 bytes
f=(s,o={'+':1,'-':1,'*':2,'/':2},a=[],p='',g=c=>o[l=a.pop()]>=o[c]?g(c,p+=l+' '):a.push(l||'',c))=>(s.match(/[)(+*/-]|\d+/g).map(c=>o[c]?g(c):(c==')'?eval(`for(;(i=a.pop())&&i!='(';)p+=i+' '`):c=='('?a.push(c):p+=+c+' ')),p+a.reverse().join` `)

Example:
Call: f('0-1+(2-3)*4-5*(6-(7+8)/9+10)')
Output: 0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -  (with a trailing space)
Explanation:
f=(s,                                                     //Input string
    o={'+':1,'-':1,'*':2,'/':2},                          //Object used to compare precedence between operators
    a=[],                                                 //Array used to stack operators
    p='',                                                 //String used to store the result
    g=c=>                                                 //Function to manage operator stack
        o[l=a.pop()]>=o[c]?                               //  If the last stacked operator has the same or higher precedence
            g(c,p+=l+' '):                                //  Then adds it to the result and call g(c) again
            a.push(l||'',c)                               //  Else restack the last operator and adds the current one, ends the recursion.
)=>
    (s.match(/[)(+*/-]|\d+/g)                             //Getting all operands and operators
    .map(c=>                                              //for each operands or operators
        o[c]?                                             //If it's an operator defined in the object o
            g(c)                                          //Then manage the stack
            :(c==')'?                                     //Else if it's a closing parenthese
                eval(`                                    //Then
                    for(;(i=a.pop())&&i!='(';)            //  Until it's an opening parenthese
                        p+=i+' '                          //  Adds the last operator to the result
                `)
                :c=='('?                                  //Else if it's an opening parenthese
                    a.push(c)                             //Then push it on the stack
                    :p+=+c+' '                            //Else it's an operand: adds it to the result (+c removes the leading 0s)
        )
    )
    ,p+a.reverse().join` `)                               //Adds the last operators on the stack to get the final result

R, 142 bytes
R is able to parse itself, so rather than re-invent the wheel, we just put the parser to work, which outputs prefix notation, and use a recursive function to switch it to postfix notation.
f=function(x,p=1){
if(p)x=match.call()[[2]]
if((l=length(x))>1){
f(x[[2]],0)
if(l>2)f(x[[3]],0)
if((z=x[[1]])!="(")cat(z,"")
}else cat(x,"")
}

The p argument is to control the use of non-standard evaluation (the bane of R programmers everywhere), and there are a few extra ifs in there to control the outputting of brackets (which we want to avoid).
Input: (0-1+(2-3)*4-5*(6-(7+8)/9+10))
Output: 0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -
Input: (((((1))) + (2)))
Output: 1 2 +
As a bonus, it works with arbitrary symbols, and any pre-defined functions with up to two arguments:
Euler's identity
Input: e^(i*pi)-1
Output: e i pi * ^ 1 -
Dividends of 13 between 1 and 100
Input: which(1:100 %% 13 == 0)
Output: 1 100 : 13 %% 0 == which
Linear regression of baby chicken weight as a function of time
Input: summary(lm(weight~Time, data=ChickWeight))
Output: weight Time ~ ChickWeight lm summary
The last example is perhaps a little outside the scope of the OP, but it does use postfix notation, so...

Perl 5, 177 bytes
Exploiting Perl operator overloading:
sub{use overload nomethod=>sub{bless[@_[3,0,1]]};sub new{shift;bless[0,@_]}sub p{$_[0][0]?join$",(map$_[0][$_]->p,1,2),$_[0][0]:$_[0][1]}eval(pop=~s/0*(\d+)/new main($1)/gr)->p}

Try it online!


text:
Convert from postfix notation to infix notation
This question may not be that creative, but I believe that it is different enough to pose a new challenge.
The Challenge
Your challenge is to write the shortest program possible that can take any valid expression in Reverse Polish Notation and convert it to infix notation that obeys the order of operations and has the necessary parentheses.
Input
Your program will receive a valid RPN expression on STDIN. This expression will consist of numbers and operators. There can be an arbitrary number of spaces between each item, but there will always be a space between two numbers. Likewise, there will never be a space within a number. Here is a formal grammer description, stolen and modified from the linked question above.
expression := expression expression operator | number
operator   := "+" | "-" | "*" | "/" | "^"
number     := digit number | digit
digit      := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

Here are some simple examples
2 3 -10000 +
16 4    12 3 / * -
1 2 +2 3 +^

In the first example, that is not a negation sign, it is a subtraction operator.
Output
Your program should output an equivalent infix expression to STDOUT, which should be a valid infix expression, with numbers, operators, and parentheses.
Here is a formal grammer description, again stolen.
expression     := number | subexpression | expression operator expression
subexpression  := "(" expression ")"
operator       := "+" | "-" | "*" | "/"
number         := digit | digit number
digit          := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

With infix notation, there must be an order of operations and a way to group subexpressions. The order of operations will be this:
Expressions inside parentheses
Exponents right to left
Multiplication and division (of equal importance) left to right
Addition and subtraction (of equal importance) left to right

As an example, 2^3^2-(2^3)^2 should equal 448.
The output should not contain any unneeded parentheses. ((2+1))-1 should reduce to 2+1-1. Also, you should not evaluate any expression. You should also not assume the commutative or associative properties. This means that, while the operators will move around, the numbers will always remain in the same order.
Here are the outputs for the above inputs. Note that what would normally be unneeded parenthesis are in the second example: removing them would invoke the associative property.
2-3+10000
16-4*(12/3)
(1+2)^(2+3)

I will add more examples later.
Rules, Regulations, and Notes
This is code golf, standard rules apply.

Re: no unneeded parentheses, "((2+1))-1 should reduce to (2+1)-1". Shouldn't it reduce to "2+1-1"? Or is that on a different level of "unneeded"?

Your second example "16 4 12 3 / * -" should translate to "16-4*(12/3)".

@breadbox Ok, the first comment was an error, which I have now fixed. For your second comment, 412/3 and 4(12/3) equal the same thing. The first would be evaluated as 48/3 and the second would be 4*4, which is sixteen.

but doesn't that assume the associative property? "4*12/3" should be produced by the input "4 12 * 3 /", and "4 12 3 / " should produce "4(12/3)", no?

Wow, yes it does actually use the associative property. Math is the only subject where reducing the number of properties makes it harder.

For those looking for a push in the right direction, have a look at the Shunting-yard algorithm.

You've used power ^ in your example but in your second BNF you haven't included it, can you clarify the correct set of operators?

I saw this challenge and instantly thought of my own RProgN. I then proceeded to do it in only 72 bytes and I was incredibly proud of myself. Then I noticed the redundant parenthesis rule.

C, 305 chars
A good challenge! I'm finding this much harder to golf than the previous one. But here's what I have so far:
char*p,b[99];l[99],o[99],r[99],s[99],h,t;
q(e,a,d){int n=o[e]%47%2+(o[e]<48),f=a-n?a>n:d-!n;
l[e]?printf("("+f),q(l[e],n,1),q(r[e],n,!putchar(o[e])),
printf(")"+f):printf("%d",o[e]);}main(){for(p=gets(b);*p;)
*p%24>9?l[++h]=s[t-2],r[h]=s[--t],o[s[t-1]=h]=*p++:
*p-32?o[s[t++]=++h]=strtol(p,&p,10):++p;q(*s,3);}

297 bytes

@ceilingcat I promised myself I wouldn't embed unmatched parens/braces in a macro definition. (Unless it was really entertaining.) The change to strtol does mean that a number like 09 in the input can produce invalid output.

Clojure - 282 279 271 268 characters
(dorun(map pr((reduce(fn[s v](let[p '{e 2,* 1,/ 1,+ 0,- 0}[t z](rseq s)a
#(if(and(seq? %)(<=(p v)(p(nth % 1))))%`(~%))](if(p v)(conj(pop(pop s))
`(~@(a z)~({'e(symbol"^")}v v)~@(a t)))(conj s v))))[](map read-string
(re-seq #"\d+|[e+*/-]"(.replace(read-line)\^\e))))0)))

(line breaks are totally optional, only included for clarity, if removed ensure there is a single space between a and #( between the first two lines. all other spaces between the lines may be removed).
Assumes input will end after the first line, passes the example programs (outputs more spaces sometimes, but the right number of parentheses :)
Program can be tested here: http://ideone.com/gxykA
Ungolfed:
(defn stackify [s v]
  (let[p '{e 4,* 3,/ 3,+ 2,- 2}
       [t n] (rseq s)
       a #(if (and (coll? %) (<= (p v) (p (nth % 1)))) % `(~%))]
    (if (p v)
      (conj (pop (pop s))
            `(~@(a n) ~({'e(symbol"^")} v v) ~@(a t)))
      (conj s v))))

(defn read-postfix [s]
  "takes a string instead of reading from *in*"
  (->> (.replace s \^ \e)
       (re-seq #"\d+|[e+*/-]")
       (map read-string)
       (reduce stackify [])
       first
       (map pr)
       dorun))

(woo, first stackexchange post)

I can't comment above, but regarding your change to the rules, doesn't the non-assumption of the associative mean that removing parentheses is generally impossible? (order of operations becomes much less meaningful).  The example 4 12 * 3 / seems to me like it should produce (4 * 12)/3, if no assumption is done, rather than 4*12/3 like you suggest.

left-to-right associativity means that parentheses are redundant in that case.

Err, doesn't left-to-right associativity assume the associative property?  I guess I'm fuzzy on how you can have order of operations and not assume the associative property.

Sorry, it is a little confusing. Left-to-right (vs right-to-left) associativity simply dictates what a parser does in the absence of parentheses. The associative property states that a formula has the same value even when associativity is changed. Thus for example, addition has the associative property, but subtraction does not. The rule is that you can't use any assumptions about certain operations having the associative property as a way to reduce parentheses. (But you still must leave out parentheses that are redundant given an operator's associativity.)

Flex - 326 288 chars
 *s[99],**p=s,q[99],*n=q,t;main(){yylex();}
 #define W(c) p--;if(*--n c t)asprintf(p,"(%s)",*p);
 #define X asprintf(p++,"%s%s%s",*p,yytext,*(p+1));*n++=t;
 #define Z W(<=)W(<)X
%%
[0-9]+ *p++=strdup(yytext);*n++=9;
\+ t=1;Z
- t=1;Z
\* t=2;Z
\/ t=2;Z
\^ t=3;W(<)W(<=)X
\n puts(*--p);
. ;

trailing newline is needed
Compile with flex makeinfix.l && gcc lex.yy.c -lfl
Edit: fixed for new spec about 4 12 3 / * => 4*(12/3) and made quite a bit shorter

I give you points for doing it completely in the lexer.

Regex (PCRE2), 140 146 bytes
s~(\d++|\((?1)(?3)(?1)\)) *((?1)) *([*-/^])|(?<=[*/^]()|[+-]|())\(((?1)(?>\^()|[+-]()|.)(?1))\)(?!\^|(?!\7)\4|\8(?!\5($|[+-])))~${1:+($1$3$2):$6}~
Try it online!
This is a single regex substitution to be repeatedly applied until it has nothing to match (or until there is no change, which has the same effect though slightly less efficient).
The assumption is made that there is no leading or trailing space, only possible space between items. This seems a reasonable interpretation of the challenge's rules as stated.
In the following explanation, ␣ represents a space:
s~                  # Begin substitution - match the following:
    # Match an expression that shall be converted to infix, with parentheses
    # added.
    (               # Define subroutine (?1) as an argument to an operator, and
                    # on the outermost level, capture this in $1:
        \d++        # Any number of digit characters, minimum one; force all of
                    # them to be consumed (prevent backtracking).
    |        # or...
        \(          # An opening parenthesis
        (?1)        # An argument
        (?3)        # An operator
        (?1)        # An argument
        \)          # A closing parenthesis
    )
    ␣*              # Any number of spaces, minimum zero.
    (               # $2 = the following:
        (?1)        # second argument
    )
    ␣*              # Any number of spaces, minimum zero.
    ([*-/^])        # Define subroutine (?3): Match an operator. The use of a
                    # range means "," and "." can be matched, but that's okay
                    # since they're guaranteed not to be in the input.
|   # Or, match an expression from which the surrounding parentheses shall be
    # removed. This can only match once everything matchable by the above has
    # already been processed.
    (?<=            # Atomic lookbehind
        [*/^]()     # \4 = set if preceded by '*' or '/' or "^"
    |
        [+-]        # set nothing if preceded by "+" or "-"
    |
        ()          # \5 = set if not preceded by any operator
    )
    \(              # An opening parenthesis (to be deleted)
    (               # $6 = the following:
        (?1)        # An argument
        (?>         # Atomic group – lock in the match once this expression
                    # completes.
            \^()    # \7 = set if the operator is "^"
        |
            [+-]()  # \8 = set if the operator is "+" or "-"
        |
            .       # set nothing if the operator is "*" or "/"; it's fine to
                    # use ".", because nothing besides an operator can be
                    # between two arguments (we've removed all the spaces by
                    # this point) and this expression is in an atomic group.
        )
        (?1)        # An argument
    )
    \)              # A closing parenthesis (to be deleted)
    (?!             # Negative lookahead – assert the following can't match:
        \^          # Followed by the operator "^"
    |
        (?!\7)      # Not using the operator "^", and:
        \4          # Preceded by the operator "*" or "/" or  "^"
    |        # or...
        \8          # Using the operator "+" or "-", and:
        (?!         # Not matching the following:
            \5      # Not preceded by any operator, and:
            (
                $       # Followed by nothing
            |           # or
                [+-]    # Followed by the operator "+" or "-"
            )
        )
    )
~                   # Replace with the following:
${1                 # Conditional upon whether \1 is set:
    :+($1$3$2)      # if \1 is set, concatenate $1 + $3 + $2 and surround that
                    # with parentheses.
    :$6             # otherwise, replace with $6 (which is what was matched in
                    # the second alternative, minus its parentheses).
}
~                   # No flags, not even global, which means each substitution
                    # will only make one match, and then the next one will
                    # start its search for a match from the beginning of the
                    # string again. This is slightly less efficient, and done
                    # for golf purposes.

This uses PCRE2_SUBSTITUTE_EXTENDED, which provides a syntax for conditional replacement. Sadly, neither PHP, R, nor Julia support this, even though the option has existed in PCRE2 for nearly 7 years now.
This allows almost anything to be done in a single substitution, where before it would have required multiple substitutions. Without it, this problem would not have been possible in a single substitution, because its first stage inserts parentheses into a string that has none to begin with, but the second stage needs to remove parentheses without adding any.
Some things may still be impossible with a single substitution. The entire state is represented by the current value of the string, and if a later stage needs to go pass through a state that intersects with the possible states of an earlier stage, it would be processed by that earlier stage rather than the later one.
Regex (Boost), 144 146 bytes
s~(\d++|\((?1)(?3)(?1)\)) *((?1)) *([*-/^])|((?<=[*/^]()|[+-])|())\(((?1)(?>\^()|[+-]()|.)(?1))\)(?!\^|(?!\8)\5|\9(?!\6($|[+-])))~?1\($1$3$2\):$7~
Try it online!
Ported to Boost's syntax, which uses parentheses, thus those in the replacement expression need to be backslash-escaped.
Boost does not support alternatives of different widths in one lookbehind, so the |(?<!\))() alternative was moved outside. It also does not support bare backreference syntax with \10 or higher (it'd have to be done as \k<10> instead), but that ended up not mattering (no non-capturing groups had to be used).

Python3, 140 chars
Difficult to golf, but I've got it sub 200, so I guess it will do.
s=[]
for k in input().split():
    if k in ['+','-','*','/']:p=len(s);s=s[0:p-2]+['('+s[p-2]+k+s[p-1]+')'];
    else:s.append(k)
print(s[0])

Pushes and pops data to the stack and converts to infix

This doesn't work at all when not every token is space-delimited, doesn't remove unnecessary parentheses in any way, and in some cases can't even parse an input even when it is fully space-delimited. None of the test cases return the correct output: Try it online!


text:
triplegolf - not only the source code length counts!
The goal of this challenge is to write a program where the length of the following three are exactly the same:

the length of the source code
the length of the output it prints to the standard output
the length of the compiler warnings it generates with the (unmodded) compiler of your choice

The winner is the shortest code to fulfill all three criteria, and has to be at least 1 character long.
To spice things up, if the output has less than three different characters, it gets a 5 point penalty added to the length for each one (so +10 if only a single type, +5 for two).
(Newlines count either as 1 or 2 characters, your choice, but it has to be consistent through all three criteria. Leading and trailing white-spaces are ignored in all lines in all three criteria)
In case of equal score, the one printing the most interesting result (instead of garbage) is the winner.

What is a "type of character"?

Is compiling with -Wall allowed?  Or is that considered "modding" the compiler?

Also, what if the compiler produces non-warning output (e.g. "Compiling Main") ?  Also, what if the name of the source file appears in warning messages (e.g. "foo.c:1:1: ...") ?

@Peter Taylor: edited, I don't know if it's clearer now. I wanted to express that aaaaaaa is one, ababbbba is made of two different characters.

@Joey Adams: Good question, I should have thought about that. Is it too late to impose a mandatory filename?

My weapon of choice is VBA, which doesn't really have a compiler and does not output a binary file to run (as is the case for some other languages, I believe). Are there considerations for this, or am I just disqualified by default?

I wonder if a triple-quine is possible in some language?

For interpreted languages, we get an output even on occurance of an error, in such a case, are those errors accepted or are only warnings accepted?

@Joey Adams: by unmodded I meant that modifying your compiler to print the warning you wanted would be obviously cheating. Sorry, I read too much IOCCC and am never paranoid enough about the rules and the possible circumvention of them. :)

=p in ed unfortunately requires a newline.

If there isn't the special note about newlines and whitespaces, someone may try =p in ed on Cygwin or MinGW.

Bash, 23 characters
Error:
bash: /: Is a directory

Source:
echo       $0-$01234;/;

Output:
/bin/bash-/bin/bash1234

Brainf*ck, 32 characters
This code executes for about 3 seconds and stops and displays the following error and output.
Error:
bff: out of memory (-2058691272)

Source:
+++++[......-]..+[>>>>>>>>>>>>-]

Output: (Hexdump)
0505 0505 0505 0404 0404 0404 0303 0303
0303 0202 0202 0202 0101 0101 0101 0000

C, 35 characters
Warning:
b.c:1:30: warning: division by zero

Source and Output:
main(){system("cat "__FILE__)/0;;;}

PHP, 50 characters
Warning:
PHP Warning:  Division by zero in /tmp/3 on line 1

Source and Output:
<?php echo (0/0).''.file_get_contents(__FILE__);?>

The bash example is an error, not a warning.

What compiler are you using for the C solution?

@breadbox gcc version 4.7.0 20120505 (prerelease) (GCC)

C - 48 chars
main(i){while(++i<49)putchar(i);putchar('\z');}

Note: includes a final (Unix-style) newline.
Output from gcc a.c reads:
a.c:1:41: warning: unknown escape sequence '\z'

The output from a.out is mostly non-printing chars, so here's what it looks like after piping through hexdump:
00000000: 0203 0405 0607 0809 0A0B 0C0D 0E0F 1011  ................
00000010: 1213 1415 1617 1819 1A1B 1C1D 1E1F 2021  .............. !
00000020: 2223 2425 2627 2829 2A2B 2C2D 2E2F 307A  "#$%&'()*+,-./0z

My understanding is that non-printable (whitepace?) are truncated, so this would not count. If that works, I can improve my own answer.

Control characters aren't usually considered whitespace, except of course for \t ,\n, \r, \f, and sometimes \v. None of these are at the leading or trailing position, so I figured I was safe.

Any word from the OP on this?

I think this is perfectly acceptable. They are not whitespace, and in either case this is not ACM to be that strict with the requirements. The main reason for this "whitespace rule" was that some IDEs might heavily format their compiler output.

47 chars and ascii output: main(){'\z';int i=32; while(++i<80)putchar(i);}

@copy, Or main(i){i='\z';while(i-->74)putchar(i);} -- but reducing the program size is actually counter-productive.

This is my favorite answer, I know I should have prohibited accessing the contents of the file (just as real quines do)

JavaScript, 63 66
!function x(){console.log(x+'...');eval(Array(33).join('$'))}()

The output is:
function x(){console.log(x+'...');eval(Array(33).join('$'))}...

In Chrome, the error is:
ReferenceError: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ is not defined

Visual Basic .NET, 185
Gee, vbc is pretty verbose with its compilation warnings. Anyway, the code is this:
Public Module Main
    Public Sub Main()
        Console.WriteLine(New String("a"c,185))
    End Sub

    Public Function A()
        'This is actually just padding.
        'Hi
    End Function
End Module

(Note that they're supposed to be tabs, not spaces.)
The output is this:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

And the compiler warning is this:
warning BC42105: Function 'A' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.

    End Function
    ~~~~~~~~~~~~

(This time, it's actually four spaces, not tabs.)

Zsh, 20 bytes
<<<   $-$_$_$_$_$_
[

The problem we face here is alluded to in a comment above: Zsh prints the program name in addition to the line number before every error. The solution here uses a one-character filename to abuse this.
I've wrapped it up in a helper script to show exactly what it prints, and used wc -c on stderr, stdout, and the source file.
Output: 569Xcatcatcatcatcat followed by a newline
Errors: s:[:2: ']' expected followed by a newline

EDIT:
Alternate 20 byte solution with no file restriction:

<<<$-$-$-$-$_>&1 >&2

Try it online!
Zsh, zsh -x, 10 bytes
<<<$_$_$_

-x flag enables xtrace. This again requires a single-character filename.
Try it online!
Zsh zsh -JNTwEDY, 12 bytes
<<<$->&1 >&2

Shortest -flag answer with no filename requirement. Sets more flags, and $- prints them all. Try it online!

JavaScript (Firefox 54), 34 bytes
alert((f=function(x)1234)(56)+f+f)

Outputs:
1234function(x)1234function(x)1234

And it sends this warning to the browser console:
expression closures are deprecated

It looks like this in my copy of Firefox Developer Edition (54.0a2). It may work in other versions of Firefox as well.

Ruby, 48 characters
IO=1;puts ?a*48;# let's make it 48 bytes long :)

Outputs
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Warns
r.rb:1: warning: already initialized constant IO

(the file is r.rb, I removed the path, if you run it from irb, you'll get (irb):1: warning...)
There is the warn method in Ruby, but it just outputs its arguments to $stderr, making it look less like a warning.

Python, 57 bytes
Other interpreters may display the warning differently. This was only tested to work on TIO.
from warnings import*
print("prt"*19)
warn("Warning...!")

Try it online
Output
prtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprtprt

Warning
.code.tio:3: UserWarning: Warning...!
  warn("Warning...!")

Note that the leading spaces are not counted toward the byte count. If the leading spaces were not ignored, this could be done in 51 bytes.

Javascript (ES6), 32 30 bytes
Screen(console.log(Function));

prints
ƒ Function() { [native code] }

in Chrome, and then throws
TypeError: Illegal constructor

My original 32 byte solution:
(x=y=>console.log(x+!0+10)||z)()

first, prints
y=>console.log(x+!0+10)||ztrue10

And throws the error
ReferenceError: z is not defined

VBA, 39 Bytes
Not sure if this qualifies, given the compiler constraint, but:
Input: (in the immediate window)
For i=1 To 39:a=a & Chr(i):Next:Print a

*The output includes non-printing characters that don't play well in this window.

VBA does not give any compiler warnings so I do not think that this counts a being valid

Perl 6, 10 bytes
dd say 1e9

Try it online!
Prints 1000000000 to STDOUT, and Bool::True to STDERR. Both produce a trailing newline, but trailing whitespace is ignored in this challenge. dd is a Rakudo specific debugging function