text:
Resistors of Unusual Value
Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms).  You check your parts bin and find that you have no 510-ohm resistors.  But you do have many common values above and below this value.  By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:

Individual resistors
Two resistors in series
Two resistors in parallel

The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a + denoting series and | denoting parallel, and some space or an = sign before the net resistance.
Formulas

The resistance of one resistor is R1
The net resistance of two resistors in series is R1 + R2
The net resistance of two resistors in parallel is 1 / (1/R1 + 1/R2)
The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance:  dist = abs(Rapprox / Rtarget - 1). For example, 200 is closer to 350 than it is to 100.
A better distance measure is true logarithmic distance  dist = abs(log(Rapprox/Rtarget)), but since this was not specified in the original question, you are free to use either measurement.

Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
Example
We have the following resistors in stock [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700] and wish to target 510 ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
680 | 2200     519.444
1000 | 1000    500.
150 + 330      480.
220 + 330      550.
470            470
680 | 1500     467.89
680 | 3300     563.819
100 + 470      570.
220 + 220      440.
100 + 330      430.
470 | 4700     427.273
680 | 4700     594.052
1000 | 1500    600.
470 | 3300     411.406
680 | 1000     404.762
150 + 470      620.
...
many more rows
...
2200 + 4700    6900.
3300 + 4700    8000.
4700 + 4700    9400.

In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
Best of each language so far (1 June 2014):

J - 70 char
APL - 102 char
Mathematica - 122 char
Ruby - 154 char
Javascript - 156 char
Julia - 163 char
Perl - 185 char
Python - 270 char

Shouldn't it be 253 configurations for the example? 121 in series, 121 in parallel, 11 solitary ones.

@Claudiu  There is no difference electrically between 100+150 and 150+100; both yield 250 ohms of resistance and consume a 100-ohm resistor and a 150-ohm resistor, so we must not double-count.  However, they should be distinguished from 125+125, because although this also yields 250 ohms, it consumes different resistors (which may be preferable, given our part counts).

510 is in the E24 series so it's not that unusual to have on hand

@gnibbler  True, but I'm not about to stock the E24 series across four orders of magnitude.

Phosgene, what about the R.O.U.V.'s?

I don't think they exist.

We don't usually set deadlines for code golf questions, because it might discourage some people from posting. You can always change accepted answers.

It's probably too late to change it now, but do note that your distance formula (dist = abs(approx/target - 1)) is not true logarithmic distance (which would, in fact, be given by dist =  abs(log(approx/target))). In particular, according to your formula, 50 is a better approximation to 100 (dist = abs(50/100 - 1) = 1/2) than 200 is (dist = abs(200/100 - 1) = 1), whereas by true logarithmic distance they'd be equally good. Also note that your distance formula is not symmetric: 50 is closer to 100 than 100 is to 50.

You have a good point.  I will change it anyway, consequences be damned.

Please give exact input and output formats. Should the input be from STDIN or a prompt?

The formatting is not particularly important, as long as it's easy to enter/read.  The code is meant to assist with building electronics.

J - 86 71 70 char
((]/:[|@<:@%~2{::"1])(;a:,<)"0,[:,/(<,.+`|,.+/;+&.%/)"1@;@((<@,.{:)\))

I'm not going to bother to explain every little detail because a lot of the code is spent syncing up the results of different functions, but here's the gist of the golf:

;@((<@,.{:)\) makes every possible pair of resistors, to be connected either in parallel or in series.
[:,/(<,.+`|,.+/;+&.%/)"1@ then connects them, in parallel and in series, making a big list of possible connections.
(;a:,<)"0, adds in the possibility of using only one resistor by itself to approximate.
(]/:[|@<:@%~2{::"1]) sorts the list of combinations of resistors by the pseudolog distance (|@<:@%) between the target and the resultant resistance from each combination.

And this is how to use it:
   rouv =: ((]/:[|@<:@%~2{::"1])(;a:,<)"0,[:,/(<,.+`|,.+/;+&.%/)"1@;@((<@,.{:)\))
   # 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700      NB. how many?
143
   10 {. 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700  NB. view first 10
+---------+-+-------+
|680 2200 |||519.444|
+---------+-+-------+
|1000 1000|||500    |
+---------+-+-------+
|150 330  |+|480    |
+---------+-+-------+
|220 330  |+|550    |
+---------+-+-------+
|470      | |470    |
+---------+-+-------+
|680 1500 |||467.89 |
+---------+-+-------+
|680 3300 |||563.819|
+---------+-+-------+
|100 470  |+|570    |
+---------+-+-------+
|220 220  |+|440    |
+---------+-+-------+
|100 330  |+|430    |
+---------+-+-------+

You don't have to only view the first 10 like I did above, but this is a function and the J REPL truncates very large return values, and the full output for this example has 287 lines. You can force it all to STDOUT with something like tmoutput toCRLF , LF ,.~ ": blah rouv blah on Windows—drop the toCRLF on Linux—but rouv is a function and internally, all the rows exist.
Note:
The question seems to have been changed right under our noses, and now the log distance is defined as abs(log(Rapprox/Rtarget)) instead of abs(Rapprox/Rtarget-1). To correct this in my golf, we can change the |@<:@% to |@^.@%: <: is Decrement while ^. is Logarithm.

Though your code is seemingly unfathomable, we can still appreciate the mystery.  Best score after one day - will it stand?

No, I do not want to send a mail to -.&a:@,@:{@(({.;

Mathematica, 151 122 characters
Expects the target resistance to be stored in r and the list of available resistors in l.
SortBy[Join[{#,#}&/@l,Join@@(#@@@Union[Sort/@N@l~Tuples~{2}]&/@{{"+",##,#+#2}&,{"|",##,#*#2/(#+#2)}&})],Abs[#[[-1]]/r-1]&]

Less golf:
SortBy[Join[{#, #} & /@ l,
  Join @@ (# @@@
       Union[Sort /@ N@l~Tuples~{2}] & /@ {{"+", ##, # + #2} &, {"|", ##,
        #*#2/(# + #2)} &})], Abs[#[[-1]]/r - 1] &]

The output format differs from the suggested one but configurations are easily determinable. The output is a list of configurations. Each configuration is of one of the following forms:
{R1, Total}
{"+", R1, R2, Total}
{"|", R1, R2, Total}

So the first three elements of the output read
{{"|", 680., 2200., 519.444}, {"|", 1000., 1000., 500.}, {"+", 150., 330., 480.}, ...}

If you're fine with rational numbers, I could save two characters from omitting N@. That is, the first element (for instance) would be returned as 4675/9 instead of 519.444.

Nice work. You beat me to it (and with shorter code).

Didn'# your den#is# w@rn you @g@ins# e@#ing #h@# much syn#@c#ic sug@r?

@N@l Tuples? Is that some sort of programmers' disease?

@clabacchio amazing, I didn't even see that. phosgene, he must have forgotten to mention it... or maybe he just likes to play golf, too...

APL (102)
{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,'  =',⍵}¨⍵;]}

This takes the target resistance as the left argument and a list of available resistors as the right argument.
Explanation:

V←{...}: V is a function that:

Z/⍨≤/¨Z←,∘.,⍨⍵: finds every unique combination of two values in ⍵,

Z←,∘.,⍨⍵: join each value in ⍵ with each value in ⍵, store in Z,
Z/⍨≤/¨Z: select from Z those combinations where the first value is less than or equal to the second value

⍺{...}⍺⍺/¨: and then applies following function, bound with the left function (⍺⍺) on the right and the left argument (⍺) on the left, to each pair:

⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵, the left argument, followed by the left bound argument, followed by the right argument, followed by =, followed by the right function (⍵⍵) applied to both arguments. (This is the formatting function, X [configuration] Y [equals] (X [fn] Y).)

⊃¨: and then unbox each element.

{⍵,'  =',⍵}¨⍵: for each element in ⍵, make the configurations for the individual resistors. (⍵, nothing, nothing, =, ⍵).
('+'+V⍵): use the V function to make all serial configurations (character is '+' and function is +).
'|'{÷+/÷⍺⍵}V⍵: use the V function to make all parallel configurations (character is '|' and function is {÷+/÷⍺⍵}, inverse of sum of inverse of arguments).
K←↑: make this into a matrix and store it in K.
0 4↓K: drop the 4 first columns from K, leaving only the resistance values.
|¯1+⍺÷⍨: calculate the distance between ⍺ and each configuration.
K[⍋...;]: sort K by the distances.

I'll take your word that it works.  My keyboard is missing rather a lot of these characters :D

@phosgene: If you want to test it, you can download a trial version of Dyalog APL at dyalog.com. Then just paste the whole thing in, it should work. The arguments go on the sides, so for example: 510 code_here 100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700

@phosgene You can try this online interpreter, though it doesn't provide the complete output you can verify that the starting few lines and the last few lines are the same.

Verified!  APL is some esoteric stuff.

@ace TryAPL is very limited, and usually it does not work. That it happens to work on this one is merely a coincidence. It doesn't support eval (⍎), I/O (⎕), or any system variables (even ⎕UCS and ⎕A don't work) so most APL programs will not run. It will actually give a SYNTAX ERROR if one of the disabled functions is used. The fact that this one happens not to use one of the many functions that TryAPL doesn't support, is a coincidence.

Python 3 - 250 247 270 bytes
from itertools import*
import sys
r=sys.argv[1:]
t=int(r.pop())
p=set(map(tuple,map(sorted,product(r,r))))
a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p]
for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s)

Run like this:
python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510

(that is, a space-delimited list of resistors, with the target value at the end)
Output:
('2200|680', 519.4444444444445)
('1000|1000', 500.0)
('150+330', 480)
('220+330', 550)
('1500|680', 467.88990825688074)
('3300|680', 563.8190954773869)

[snip]

('2200+4700', 6900)
('3300+4700', 8000)
('4700+4700', 9400)

I would say that outputting, say, 680|2200 and 2200|680 separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes. Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical.

Sure, output looks plenty clear to me!

However, you are double-counting things.  150+330 is electrically identical to 330+150, so only one of them should appear in the result (143 total configurations for the example).

@pho Okay, fixed. A few extra bytes but the solution should be valid now.

Also I think your program doesn't look for a single resistor, at all (a+=[(a,a)for a in r]). You can skip a=... as you use a exactly one time. About this import sys;r=sys.args[1:], use r=input().split() and say that you have to give the values on stdin. At last: you use 1/sum(1/int(n)for n in b) instead of 1/sum(map(lambda n:1/int(n),b). All in all, that should be 274 chars

I just golfed 1 more char: Use print(*sorted(...),sep='\n')

Ruby 2.1, 156 154 bytes
s=->(a,z){c={};a.map{|e|a.map{|f|c[e]=e;c[e+f]="#{e}+#{f}";c[1/(1.0/f+1.0/e)]="#{e}|#{f}"}};c.sort_by{|k,|(k/z.to_f-1).abs}.map{|e|puts"#{e[1]}=#{e[0]}"}}

Ungolfed:
s =->(a,z) {
  c={}
  a.map{|e|
    a.map{|f|
      c[e]=e
      c[e+f]="#{e}+#{f}"
      c[1/(1.0/f+1.0/e)]="#{e}|#{f}"
    }
  }
  c.sort_by{|k,|
    (k/z.to_f-1).abs
  }.map{|e|
    puts "#{e[1]}=#{e[0]}"
  }
}

What it does:

For each value e in a;

Iterate through a, computing single, series, and parallel values as keys to printed values in hash c;

Determine distance from z for each key in c; and,
For each value e[1] for each key e[0] in c, print e[1]=e[0].

Sample usage:
s[[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700], 510]
Sample output:
2200|680=519.4444444444445
1000|1000=500.0
330+150=480
330+220=550
470=470
1500|680=467.88990825688074
3300|680=563.8190954773869
.
.
.
4700+1500=6200
3300+3300=6600
4700+2200=6900
4700+3300=8000
4700+4700=9400

JavaScript (ECMAScript 6) - 186 Characters
f=(R,T)=>(D=x=>Math.abs(x[3]/T-1),r={p:(x,y)=>x*y/(x+y),s:(x,y)=>x+y},[...[[x,0,0,x]for(x of R)],...[[x,y,z,r[z](x,y)]for(x of R)for(y of R)for(z in r)if(x<=y)]].sort((a,b)=>D(a)-D(b)))

Input:

An array R of resistor strengths; and
T, the target resistance.

Output:
An array of arrays (sorted by distance from T) each containing:

the smaller resistor's value;
the higher resistor's value (or 0 if a solitary resistor);
p, s or 0 if the resistors are in parallel, serial or solitary; and
the net resistance.

Explanation:
f=(R,T)=>(                               // Create a function f with arguments R & T
  D=x=>Math.abs(x[3]/T-1),               // A function D to calculate relative
                                         // distance from the target value
  r={p:(x,y)=>x*y/(x+y),s:(x,y)=>x+y},   // An object containing the formulae
                                         // to calculate resistance in serial and parallel
  solitary = [[x,0,0,x]for(x of R)],     // Create an array of solitary resistors
  pairs =                                // Use Array Comprehension to create the array of
   [[x,y,z,r[z](x,y)]                    // arrays
      for(x of R)                        // for each resistor value
      for(y of R)                        // for each resistor value (again)
      for(z in r)                        // for both serial & parallel
      if(x<=y)],                         // where the first resistor value is smaller than the second
  [
    ...solitary,                         // Use the spread ... operator to combine
    ...pairs                             // the two arrays
  ]
    .sort((a,b)=>D(a)-D(b))              // Sort the arrays by minimum distance
                                         // and return.
)

Single resistor missing (output len for example input is 132 instead of 143). I'd like to borrow the Array Comprehension trick, if I just could understand it...

Ah, forgot the solitary resistors

Julia - 179 163 bytes
f(t,s)=(\ =repmat;m=endof(s);A=A[v=(A=s\m).>=(B=sort(A))];B=B[v];F=[s,C=A+B,A.*B./C];n=sum(v);print([[s P=[" "]\m P;A [+]\n B;A [|]\n B] F][sortperm(abs(F-t)),:]))

This works the same as the old version, but the argument in the print statement has been organised slightly differently to reduce the number of square brackets necessary. Saves 4 bytes. Absorbing the spaces vector creation into the print argument saves an extra 2 bytes. It has also switched from using "find" to get the relevant indices to using the logical form. Saves 6 bytes. Absorbing the calculation of the index vector into the adjustment of A saved another 2 bytes. Finally, replacing endof(v) with sum(v) saved 2 more bytes. Total saving: 16 bytes.
Old version:
f(t,s)=(\ =repmat;m=endof(s);A=s\m;v=find(A.>=(B=sort(A)));A=A[v];B=B[v];F=[s,C=A+B,A.*B./C];n=endof(v);P=[" "]\m;print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:]))

Within the function, here's what it's doing:
\ =repmat            # Overloads \ operator to save lots of characters
m=endof(s)           # Length of input s ("Stock")
A=s\m                # Equivalent to repmat(s,m) (see first command)
B=sort(A)            # Same as A but sorted - rather than cycling through
                     # the resistors m times, it repeats each one m times
v=find(A.>=B)        # Identify which pairs for A,B have A>=B
A=A[v];B=B[v]        # Remove pairs where A<B (prevents duplicates)
F=[s,C=A+B,A.*B./C]  # Constructs vector containing results for single resistor,
                     # resistors in series, and resistors in parallel
n=endof(v)           # equivalent to n=(m+1)m/2, gets number of relevant pairs
P=[" "]\m            # Construct array of blank entries for use in constructing output
print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:]))
# The following are the components of the argument in the print statement:
[s,A,A]              # Set of resistor values for resistor 1
[P,[+]\n,[|]\n]      # Operator column, prints either nothing, +, or |
[P,B,B]              # Set of resistor values for resistor 2 (blank for single resistor)
F                    # Contains resulting equivalent resistance
[sortperm(abs(F-t)),:] # Determines permutation for sorting array by distance from Target t
                     # and applies it to array

Sample output:
julia> f(170,[100,220,300])
300  |  300  150
100  +  100  200
300  |  220  126.92307692307692
220          220
220  |  220  110
100          100
300  |  100  75
220  |  100  68.75
100  |  100  50
300          300
220  +  100  320
300  +  100  400
220  +  220  440
300  +  220  520
300  +  300  600

Nice!  Don't see many Julia submissions - is it growing in popularity?

@phosgene - I hope it is; I'm mostly submitting these because they're giving me extra experience with the language.

Javascript (E6) 156 162 164 186
Last Edit Assuming all resistor values > 0, you can use them for the loop condition
F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))}

Usage : F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])
Ungolfed
F = (t,s) =>
{
  D = a => Math.abs(a[1]/t-1);
  for (i=r=[]; a=s[j=i++]; r[l]=[a,a])
    for(; b=s[j--];)
      l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]);
   return r.sort((a,b) => D(a)-D(b))
}

Must push(score,lower)!

Last I checked, all of my resistors were positively-valued.  I think it's a safe assumption.

Javascript, 248 bytes
function r(T,L){R=[],O="";for(i in L){R.push([a=L[i],a]);for(j=i;j<L.length;)b=L[j++],s=a+b,R.push([a+"+"+b,s],[a+"|"+b,a*b/s])}R.sort(function(a,b){A=Math.abs;return A(a[1]/T-1)-A(b[1]/T-1)});for(i in R)q=R[i],O+=q[0]+"="+q[1]+"\n";console.log(O)}

Usage : r(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]);
Output
670|2200=519.4444444444445
1000|1000=500
150+330=480

(...such rows...)

2200+4700=6900
3300+4700=8000
4700+4700=9400

Perl, 213 199 185 bytes
213 bytes:
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>;

199 bytes:
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>;

185 bytes:
$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';$i="{@ARGV}";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)>

Pass all available resistors as arguments. The target resistance should be the last:
$ perl -E 'code' R1 R2 R3 ... Rn target

How it works (old code)

Define subroutines S and P to compute the sum and parallel values of two resistors.
Set $" to "," to interpolate @ARGV inside the glob operator
<{S,P}({@i},{@i})= S({@i})=> generates a cartesian of all possibilities:
S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ...
Combine s///ee with grep to evaluate the equivalent resistances and filter out unwanted repeats (performed by (??{$2<$3}) and /\d$/
sort by fitness computed in subroutine t

Changes in new code

Avoid use of s///ee, use shorter regex with conditional checking and eval inside grep
Replace repeats of "{@i}" with$i`
Introduce $x, $y instead of $2, $3
Replace split/=/,pop with $_[0]=~s!!!r
No need for trailing ;
eval; is equivalent to eval $_;
Add = along with eval-ed answer instead of declaring it up front

Output:
P represents resistors in parallel, S represents resistors in series.
P(2200,680)=519.444444444444
P(1000,1000)=500
S(330,150)=480
S(330,220)=550
S(470)=470
P(1500,680)=467.889908256881
P(3300,680)=563.819095477387
S(470,100)=570
S(220,220)=440
S(330,100)=430
P(4700,470)=427.272727272727
P(4700,680)=594.052044609665
P(1500,1000)=600
P(3300,470)=411.405835543767
P(1000,680)=404.761904761905
S(470,150)=620
P(2200,470)=387.265917602996
S(220,150)=370
S(330,330)=660
P(1500,470)=357.868020304569
S(680)=680
P(680,680)=340
P(2200,1000)=687.5
S(330)=330
S(470,220)=690
S(220,100)=320
P(1000,470)=319.727891156463
P(4700,330)=308.349900596421
S(150,150)=300
P(3300,330)=300
P(2200,330)=286.95652173913
P(680,470)=277.913043478261
P(1500,330)=270.491803278689
P(1500,1500)=750
P(3300,1000)=767.441860465116
S(150,100)=250
P(1000,330)=248.12030075188
S(680,100)=780
P(470,470)=235
P(680,330)=222.178217821782
S(470,330)=800
S(220)=220
P(4700,220)=210.162601626016
P(3300,220)=206.25
S(100,100)=200
P(2200,220)=200
P(4700,1000)=824.561403508772
P(470,330)=193.875
P(1500,220)=191.860465116279
S(680,150)=830
P(1000,220)=180.327868852459
P(680,220)=166.222222222222
P(330,330)=165
S(150)=150
P(470,220)=149.855072463768
P(4700,150)=145.360824742268
P(3300,150)=143.478260869565
P(2200,150)=140.425531914894
P(1500,150)=136.363636363636
P(330,220)=132
P(1000,150)=130.434782608696
P(2200,1500)=891.891891891892
P(680,150)=122.89156626506
S(680,220)=900
P(470,150)=113.709677419355
P(220,220)=110
P(330,150)=103.125
S(100)=100
P(4700,100)=97.9166666666667
P(3300,100)=97.0588235294118
P(2200,100)=95.6521739130435
P(1500,100)=93.75
P(1000,100)=90.9090909090909
P(220,150)=89.1891891891892
P(680,100)=87.1794871794872
P(470,100)=82.4561403508772
S(470,470)=940
P(330,100)=76.7441860465116
P(150,150)=75
P(220,100)=68.75
P(150,100)=60
P(100,100)=50
S(1000)=1000
S(680,330)=1010
P(3300,1500)=1031.25
S(1000,100)=1100
P(2200,2200)=1100
P(4700,1500)=1137.09677419355
S(680,470)=1150
S(1000,150)=1150
S(1000,220)=1220
P(3300,2200)=1320
S(1000,330)=1330
S(680,680)=1360
S(1000,470)=1470
P(4700,2200)=1498.55072463768
S(1500)=1500
S(1500,100)=1600
S(1500,150)=1650
P(3300,3300)=1650
S(1000,680)=1680
S(1500,220)=1720
S(1500,330)=1830
P(4700,3300)=1938.75
S(1500,470)=1970
S(1000,1000)=2000
S(1500,680)=2180
S(2200)=2200
S(2200,100)=2300
S(2200,150)=2350
P(4700,4700)=2350
S(2200,220)=2420
S(1500,1000)=2500
S(2200,330)=2530
S(2200,470)=2670
S(2200,680)=2880
S(1500,1500)=3000
S(2200,1000)=3200
S(3300)=3300
S(3300,100)=3400
S(3300,150)=3450
S(3300,220)=3520
S(3300,330)=3630
S(2200,1500)=3700
S(3300,470)=3770
S(3300,680)=3980
S(3300,1000)=4300
S(2200,2200)=4400
S(4700)=4700
S(3300,1500)=4800
S(4700,100)=4800
S(4700,150)=4850
S(4700,220)=4920
S(4700,330)=5030
S(4700,470)=5170
S(4700,680)=5380
S(3300,2200)=5500
S(4700,1000)=5700
S(4700,1500)=6200
S(3300,3300)=6600
S(4700,2200)=6900
S(4700,3300)=8000
S(4700,4700)=9400

The missing two lines are S(100)=100 and S(1000)=1000.

@algorithmshark : Yup, got it. The regex was inadvertently consuming them

It will be interesting to see if anyone can come up with a shorter Perl solution.


text:
Recursive acronyms
Objective
From Wikipedia :

A recursive acronym is an acronym that refers to itself in the expression for which it stands.

Your goal is to check if a string is a recursive acronym.

The acronym is the first word
Words are not case sensitive, separated with a single space.
The given string does not contain any punctuation nor apostrophe.
Only the first letter of each word can be part of the acronym.

You must also give the function words. For simplicity, every word can be considered as a function word.
Example
f("RPM Package Manager")         =>     { true, [] }
f("Wine is not an emulator")     =>     { true, ["an"] }
f("GNU is not Unix")             =>     { true, ["is"] }
f("Golf is not an acronym")      =>     { false }
f("X is a valid acronym")        =>     { true, ["is","a","valid","acronym"] }

You can give a full program or a function.
The input string can be taken from STDIN or as a function argument.
Output result can be true/false, 0/1, yes/no...
The function words list (any format of list is valid) must be given if and only if this is a recursive acronym (even if the list is empty). You do not have to preserve capitalization of the function words.
Winning criteria
This is a code-golf, shortest code wins.

Do we have to preserve capitalization of the function words?

Is it acceptable to have a list of strings accompanying a False value, or no?

Nevermind, found the place where you said it wasn't. :P

Since the word list itself encodes the boolean value by its presence, may we omit the boolean?

@JanDvorak, no, you have to specify the boolean.

@algorithmshark, no, I've edited the question.

Hurd stands for Hird of Unix-Replacing Daemons. Hird stands for Hurd of Interfaces Representing Depth. Why the examples here don't understand that, and claim those aren't recursive acronyms?

@xfix, wikipedia states that those are mutually recursive acronyms.

The answer you want cannot tell whether the string is a recursive acronym. It may tell whether the string may be a recursive acronym. For example, with the input string "FBI buried intelligence", the answer would tell that FBI is a recursive acronym. But FBI is neither recursive nor an acronym.

RPM is not an acronym.

GolfScript, 51 50 chars
{32|}%" "/(1>\{.1<2$1<={;1>}{\}if}/{]!}{]`1" "@}if

It probably can be golfed further. Takes input on STDIN. The boolean is 0/1.
Test online

Explanation:
{32|}%      # change everything to lower-case
" "/        # splits the string by spaces
(1>         # takes the first word out and removes the first letter
\           # moves the list of remaining words in front of the acronym word
{           # for every word:
  .1<2$1<=    # compares the first letter of the word with
              # the next unmatched letter of the acronym
  {;1>}       # if they are the same, discard the word and the now-matched letter
  {\}         # otherwise store the word in the stack
  if          # NB. if all letters have been matched, the comparison comes out as false
}/
{]!}        # if there are still unmatched letters, return 0 (`!` non-empty list)
{]`1" "@}   # otherwise, return 1, and display the list of function words
if

Regex, .NET flavour, 62 bytes
(?i)(?<=^\w(?<c>\w)*)( \k<c>(?<-c>)\w+| (?<w>\w+))*$(?(c)(?!))

You can test it here. If the input is a recursive acronym, this will yield a match, and capturing group w will contain all function words. If it isn't, then there will be no match.
This does preserve capitalisation of the function words (but matches case-insensitively).
Unfortunately, the tester doesn't display the entire stack of a named capturing group, but if you used it anywhere in .NET, the w group would contain all function words in order.
Here is a C# snippet to prove that:
var pattern = @"(?i)(?<=^\w(?<c>\w)*)( \k<c>(?<-c>)\w+| (?<w>\w+))*$(?(c)(?!))";
var input = new string[] {
    "RPM Package Manager",
    "Wine is not an emulator",
    "GNU is not Unix",
    "Golf is not an acronym",
    "X is a valid acronym"
};

var r = new Regex(pattern);
foreach (var str in input)
{
    var m = r.Match(str);
    Console.WriteLine(m.Success);
    for (int i = 0; i < m.Groups["w"].Captures.Count; ++i)
        Console.WriteLine(m.Groups["w"].Captures[i].Value);
}

Here is a quick explanation. I'm using .NET's balancing groups to build a stack of the acronym letters in the named group c, with this snippet
^\w(?<c>\w)*

The trick is that I need the second letter on top of the stack and the last one at the bottom. So I put all of this in a lookbehind that matches the position after the acronym. This helps, because .NET matches lookbehinds from right to left, so it encounters the last letter first.
Once I got that stack, I match the rest of the string word for word. Either the word begins with the letter on top of the acronym stack. In that case I pop that letter from the stack:
 \k<c>(?<-c>)\w+

Otherwise, I match the word anyway and push onto the w stack which will then contain all function words:
 (?<w>\w+)

At the end I make sure I reached the end of the string with $ and also make sure that I've used up all letters from the acronym, by checking that the stack is empty:
(?(c)(?!))

Test it on ideone.

Great regular expression, but the question clearly states "You can give a full program or a function".

@toothbrush If the OP decides to disqualify my answer based on that, so be it. But I think I could make a point that this is a full program in the language which is .NET's regular expression flavour (not a Turing complete language, and one that is a bit cumbersome to run, but a language nevertheless). In any case, I like the fact that I solved it with a pure-regex approach, and I'd rather have the answer disqualified than destroy that "elegance" (if you will) by making it "just a C#-answer using regex".

That's fine with me. I just wanted to point it out in case you missed it.

I like it. Regexes may not be a Turing-complete programming language, but I think this should count.

@PaulDraper In fact, I wouldn't even bet on .NET's regex flavour not being Turing complete... the balancing groups and right-to-left-matched lookbehinds are pretty powerful. And PCRE for instance is known to be Turing complete (that one has recursion, I'm not sure the stacks in .NET are sufficient to emulate arbitrary iteration).

@m.buettner, it is true that PCREs are Turning complete, but I'll bet the Millennium Falcon that .NET regexes aren't.

@PaulDraper Push-down automata with two stacks are Turing complete IIRC. Using nested lookaheads and lookbehinds you can move forward and backward on the input. My CS classes are a while back now, but at least it isn't obvious to me that they couldn't be Turing complete.

@toothbrush doesn't matter any more... GolfScript strikes again ;)

Python (158, without regex)
It's not that I don't like regexes. It's that I don't know them.
def f(x):
 s=x.lower().split();w=list(s[0][1:]);s=s[1:];o=[]
 if not w:return 1,s
 [w.pop(0)if i[0]==w[0]else o.append(i)for i in s]
 return(0,)if w else(1,o)

Oh, I also had an ungolfed version:
def acronym(string):
    scentence = string.lower().split()
    word = scentence[0][1:]
    scentence = scentence[1:]
    over = []
    if not word: return 1, scentence
    for item in scentence:
        if item[0] == word[0]:
            word = word[1:]
        else:
            over.append(item)
    if word:
        return 0,
    return 1,over

Python 2.7 - 131 126 bytes
def f(s):
 s=s.lower().split();a,f=list(s[0]),[]
 for w in s:f+=0*a.pop(0)if a and w[0]==a[0]else[w]
 return(0,)if a else(1,f)

Makes a list of letters in the first word of the acronym. Then, for each word in the full string, get rid of the first element of that list we made if it is the same as the first letter of that word. Otherwise, add that word to the list of function words. To output, return not a (In python, any list other than the empty list is True-y, and the list is empty if it's a recursive acronym) and the list if not a.
Thanks to @ace for helping me fix an error/save some bytes.

On Python 2.7.3, I get SyntaxError: invalid syntax at the end of the return line.

@ace Huh, I could have sworn it worked when I tested it. I must have changed something and forgot to test again. I'll work on a fix!

You can use for w in s:f+=0*a.pop(0)if a and w[0]==a[0]else[w] which is shorter and doesn't rely on tabs. As for the return statement, I found 0if a else(1,f) which is shorter than your original.

Oh and if you use semicolons to put the first two statements in the same line you save one byte of indentation.

I figured out a way to fix the error, but when I came back here to post it you had golfed it down more in the comments :P

ECMAScript 6 (105 bytes):
f=s=>(r=(a=s.toUpperCase(i=1).split(' ')).map((w,c)=>c?a[0][i]==w[0]?(i++,''):w:''),a[0].length==i?1+r:0)

Enter the function in Firefox's browser console, and then just call the function, like this:
f('ABC Black Cats')     // 1,,
f('ABC is Black Cats')  // 1,IS,,
f('ABC Clapping Cats')  // 0

Doesn't quite comply with the rules: The function words list ... must be given if and only if this is a recursive acronym. This will alert them regardless.

@MT0 OK. I didn't notice that requirement. I'll see if I can rewrite it.

@MT0 I've updated the code now.

Python - 154 characters
First ever code golf attempt. I'm thinking python isn't the best language for it, given all the long keywords. Also, I don't think this function is foolproof. It works for the OP's input, but I'm sure I could think up exceptions.
def f(s):
    w=s.lower().split();r=list(w[0]);return(True,[x for x in w if x[0]not in r])if len(r)==1 or[x for x in[y[0]for y in w]if x in r]==r else False

I count 156 characters (the newline and the tab character both count), but you can get it down to 154 legitimately by removing those two characters since neither are actually required. Welcome to PPCG, btw. :)

Haskell - 287 bytes
Not the shortest entry (hey this is Haskell, what did you expect?), but still a lot a fun to write.
import Data.Char
import Data.List
f""w=map((,)False)w
f _[]=[]
f(a:as)(cs@(c:_):w)
 |toLower a==toLower c=(True,cs):f as w
 |True=(False,cs):f(a:as)w
g s=if(length$filter(fst)d)==length v
  then Just$map(snd)$snd$partition(fst)d
  else Nothing
 where
  w=words s
  v=head w
  d=f v w

Tested with
map (g) ["RPM Package Manager","Wine is not an emulator","GNU is not Unix","Golf is not an acronym","X is a valid acronym"]

Expected output
[Just [],Just ["an"],Just ["is"],Nothing,Just ["is","a","valid","acronym"]]

Ungolfed
import Data.Char
import Data.List

f :: String -> [String] -> [(Bool, String)]
f "" w = map ((,) False) w
f _ [] = []
f (a:as) ((c:cs):w) | toLower a == toLower c = (True, c:cs) : f as w
                    | otherwise = (False, c:cs) : f (a:as) w

g :: String -> Maybe [String]
g s = if (length $ filter (fst) d) == (length v)
          then Just $ map (snd) $ snd $ partition (fst) d
          else Nothing
  where w = words s
        v = head w
        d = f v w

JavaScript (ECMAScript 6) - 97 Characters
f=x=>(r=(a=x.toLowerCase(i=0).split(' ')).filter(y=>y[0]!=a[0][i]||i-i++),i==a[0].length?[1,r]:0)

Tests:
f("RPM Package Manager")
[1, []]

f("GNU is not Unix")
[1, ["is"]]

f("X is an acronym")
[1, ["is", "an", "acronym"]]

f("Golf is not an acronym")
0

f("Wine is not an emulator")
[1, ["an"]]

Rebol - 133
f: func[s][w: next take s: split s" "y: collect[foreach n s[either n/1 = w/1[take w][keep n]]]reduce either/only w: empty? w[w y][w]]

Ungolfed:
f: func [s] [
    w: next take s: split s " "
    y: collect [
        foreach n s [
            either n/1 = w/1 [take w][keep n]
        ]
    ]
    reduce either/only w: empty? w [w y][w]
]

Tested with:
foreach t [
    "RPM Package Manager"  "Wine is not an emulator"
    "GNU is not Unix"      "Golf is not an acronym"
    "X is a valid acronym"
][probe f t]

Output:
[true []]
[true ["an"]]
[true ["is"]]
[false]
[true ["is" "a" "valid" "acronym"]]

Julia - 116 bytes
f(w)=(a=split(lowercase(w));L=1;A=a[];while a!=[];a[][1]==A[1]?A=A[2:]:(L=[L,a[]]);a=a[2:];A>""||return [L,a];end;0)

Less Golfed:
f(w)=(
 a=split(lowercase(w))
 L=1
 A=a[]
 while a!=[]
  if a[][1]==A[1]
   A=A[2:]
  else
   L=[L,a[]]
  end
  a=a[2:]
  if !(A>"")
   return [L,a]
  end
 end
0)

The 0 on the end makes it output 0. Otherwise, it outputs an array containing 1 followed by the function words. For example:
julia> f("RPM Package Manager")
1-element Array{Any,1}:
 1

julia> f("Golf is not an acronym")
0

julia> f("GNU is not Unix")
2-element Array{Any,1}:
 1
  "is"

julia> f("X is a valid acronym")
5-element Array{Any,1}:
 1
  "is"
  "a"
  "valid"
  "acronym"

Brachylog, 29 bytes
ḷṇ₁XhY∧X;0zpᵐz{ċ₂ˢ}ᵐZhhᵐcY∧Zt

Try it online!
Outputs the function words through the output variable if the input is a recursive acronym, and fails if it is not.
   X                             X is
ḷ                                the input lowercased
 ṇ₁                              and split on spaces,
    hY                           the first element of which is Y
      ∧                          (which is not X).
       X  z                      X zipped
        ;0                       with zero,
           pᵐ                    with all pairs permuted (creating a choicepoint),
             z                   zipped back,
              {   }ᵐ             and with both resulting lists
               ċ₂ˢ               losing all non-string elements,
                    Z            is Z.
                      hᵐ         The first elements of the elements of
                    Zh           the first element of Z
                        cY       concatenated are Y
                          ∧      (which is not Z).
                           Zt    The last element of Z is the output.

Without having to output the function words (treating this as a pure decision-problem), it comes out to just 12 bytes, because ∧Zt can be dropped for -3, Y can be replaced with . for -1, and most importantly ;0zpᵐz{ċ₂ˢ}ᵐZh can be replaced with ⊇ for a whopping -13: ḷṇ₁Xh.∧X⊇hᵐc

C# - 234
Tuple<bool,string[]> f(string w) {var l=w.ToLower().Split(' ');var o=new List<string>();int n=0;var a=l[0];foreach(var t in l){if(n>=a.Length||a[n]!=t[0])o.Add(t);else n++;}var r=n>=a.Length;return Tuple.Create(r,r?o.ToArray():null);}

Python (108)
l=raw_input().lower().split()
a=l[0]
e=[]
for w in l:d=w[0]!=a[0];a=a[1-d:];e+=[w]*d
b=a==''
print b,b*`e`

Cobra - 187
def f(s as String)
    l=List<of String>(s.split)
    a=l[0]
    l.reverse
    o=0
    for c in a,for w in l.reversed
        if c==w[0]
            l.pop
            o+=1
            break
    x=o==a.length
    print x,if(x,l,'')

Java - 195
Unfortunately, Java does not have built in tuple support.
So, this is a class that stores the boolean in 'b' and the function word list in 'x'.
Here, the function is the constructor of the class.
static class R{boolean b;String[]x;R(String s){String v=" ",i="(?i)",f=s.split(v)[0],r=i+f.replaceAll("(?<=.)",".* ");if(b=(s+=v).matches(r))x=(s.replaceAll(i+"\\b["+f+"]\\S* ","")+v).split(v);}}

Test
public class RecursiveAcronyms {
public static void main(String args[]) {
    String[] tests = {
            "RPM Package Manager",
            "Wine is not an emulator",
            "GNU is not Unix",
            "Golf is not an acronym",
            "X is a valid acronym"
        };
    for (String test:tests) {
        R r = new R(test);
        System.out.print(r.b);
        if (r.b) for (String s:r.x) System.out.print(" "+s);
        System.out.print("\n");
    }
}
static class R{boolean b;String[]x;R(String s){String v=" ",i="(?i)",f=s.split(v)[0],r=i+f.replaceAll("(?<=.)",".* ");if(b=(s+=v).matches(r))x=(s.replaceAll(i+"\\b["+f+"]\\S* ","")+v).split(v);}}}

C# has tuples but I came up with this while working on my solution: just return string[]: null simply means false, empty means true and n elements means true with n function words.

I would like to do that too. However OP specifies that the boolean must be provided regardless. See the reply to Jan Dvorak's comment.

I don't care about the comments as I can't seem to spot a resulted edit in the original post. And even if i did, it clearly just says to "specify the boolean". And even in the answer itself it says "*Output result can be true/false, 0/1, yes/no...+" which I might just extend at the ellipsis by "null/not null" ...

Ruby - 173
Could be better...
 f=->s{a=[];o={};s=s.split;r=true;s[0].each_char{|c|s.each{|w| w[0]=~/#{c}/i?(o[c]=1;a<<w if o[c]):(o[c]=0 if !o[c])}};r,a=false,s if o.values&[0]==[0];!r ?[r]:[r,(s-(a&a))]}

Calling the func :
p f.call('RPM Package Manager')
p f.call('Wine is not an emulator')
p f.call("GNU is not Unix")
p f.call("Golf is not an acronym")
p f.call("X is a valid acronym")

Output :
[true, []]
[true, ["an"]]
[true, ["is"]]
[false]
[true, ["is", "a", "valid", "acronym"]]

Awk - 145
awk -v RS=' ' '{c=tolower($0)};NR==1{w=c};{t=substr(c,1,1)!=substr(w,NR-s,1);if(t){f=f" "c;s++};a=a||t};END{print a&&(s>NR-length(w))?"N":"Y|"f}'

Test:
$ cat gcp.sh
#!/bin/sh
f() {
echo "$1:"
echo "$1"|awk -v RS=' ' '{c=tolower($0)};NR==1{w=c};{t=substr(c,1,1)!=substr(w,NR-s,1);if(t){f=f" "c;s++};a=a||t};END{print a&&(s>NR-length(w))?"N":"Y|"f}'
}
f "RPM Package Manager"
f "Wine is not an emulator"
f "Wine is not an appropriate emulator"
f "GNU is not Unix"
f "Golf is not an acronym"
f "Go is not an acronym"
f "Go is a valid acronym OK"
f "X is a valid acronym"
f "YAML Ain't Markup Language"

$ ./gcp.sh
RPM Package Manager:
Y|
Wine is not an emulator:
Y| an
Wine is not an appropriate emulator:
Y| an appropriate
GNU is not Unix:
Y| is
Golf is not an acronym:
N
Go is not an acronym:
N
Go is a valid acronym OK:
Y| is a valid acronym
X is a valid acronym:
Y| is a valid acronym

YAML Ain't Markup Language:
Y|

Coffeescript - 144
z=(a)->g=" ";b=a.split g;c=b[0];d=[];(d.push(e);g++)for e,f in b when e[0].toLowerCase()!=c[f-g].toLowerCase();if(g+c.length==f)then{1,d}else{0}

Call it with, for instance: z "GNU is not Unix"
The compiled JS:
var z;
z = function(a) {
  var b, c, d, e, f, g, _i, _len;
  g = " ";
  b = a.split(g);
  c = b[0];
  d = [];
  for (f = _i = 0, _len = b.length; _i < _len; f = ++_i) {
    e = b[f];
    if (e[0].toLowerCase() !== c[f - g].toLowerCase()) {
      d.push(e);
      g++;
    }
  }
  if (g + c.length === f) {
    return {
      1: 1,
      d: d
    };
  } else {
    return {
      0: 0
    };
  }
};

It splits the string into words and then loops through each word. If the first character of the word doesn't match the next in the acronym, the word is stored. A counter (g) is used to track how many words have been skipped. If the number of skipped words plus the length of the acronym matches the length of the phrase, it matched, so return 1 and the skipped words. If not, it was not valid, so return 0.

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:
reach catch when everything in the try block is caught already
This is limited to Java and C# by the syntax I guess.
In this programming puzzle, you are to produce Exceptions that can be caught but are thrown again at the end of the catch block.
try
{
    while(true)
        try
        {
            // you are only allowed to modify code between this try { } brackets
        }
        catch(Exception ex2) {  }
}
catch(Exception ex1)
{
    // your goal is to reach this catch block by modifying the code ...
    // in the inner try block above
    // You win if you reach this part and execute on of the following code lines
    Console.WriteLine("You won!"); // for C#
    // Or
    System.out.println("You won!"); // for Java
}

You can freely put code before and after this snippet.
The shortest code to reach the outer catch block wins.

I think Python may also be able to compete.

You can freely put code before and after my snippet.

Too bad it's closed. I've got a solution. To @algorithmshark, Michael and Jan Dvorak: This is NOT a general programming question. It is a programming puzzle, similar to When is a giraffe not a giraffe?. I'm nominating this for reopening.

How are we measuring shortest code? Total length? Sum of the lengths of the insertions made before/in/after? How would these work if someone attempts this in Python or other languages with try/catches?

Uhhhhhh, Whaaat???

@algorithmshark I'd go with the sum of the lengths of the insertions

this might also work for javascript

@ace — Very clever !

C#, 46 (88 including boilerplate)
using System;class P{static void Main(){
        try
        {
            while(true)
                try
                {
                    System.Threading.Thread.CurrentThread.Abort();
                }
                catch(Exception ex2) {  }
        }
        catch(Exception ex1)
        {
            // your goal is to reach this catch block by modifying the code ...
            // in the inner try block above
            // You win if you reach this part and execute on of the following code lines
            Console.WriteLine("You won!"); // for C#
        }
}}

The Abort() method raises a ThreadAbortException, which is a special exception that is automatically rethrown at the end of each catch block (unless Thread.ResetAbort() is called).

C# 24 Characters
terminates the inner try block before intended, allowing me to cause an exception outside of the try block.
}finally{int a=1/0;}try{

Man this is genius! Why didn't I think of that? (Btw can you shorten it by actually causing an exception instead of throwing an exception? e.g. int a=1/0;?)

Do you need int a= there? Some languages let you just write the expression 1/0

This isn't a complete working example, is it? So the 24 characters don't count...

Java, 76 or 31
Counting only the insertions made to the code, ignoring new lines. 76 if you count everything I've added, 31 if you exclude the first line and the last line, i.e. only counting int a=1/0;try{}catch(Error e){}.
class P{public static void main(String[]A){
try
{
    while(true)
        try
        {
            int a=1/0;try{
        }
        catch(Exception ex2) {  }
}
catch(Exception ex1)
{
    // your goal is to reach this catch block by modifying the code ...
    // in the inner try block above
    // You win if you reach this part and execute on of the following code lines
    //Console.WriteLine("You won!"); // for C#
    // Or
    System.out.println("You won!"); // for Java
}
}catch(Error e){}
}}

Oops, sorry, I didn't pay attention to how you counted. I'll update my answer to add the other counting method. I reckon just counting the characters in the try block is better, since otherwise we'd basically be comparing C# vs Java boilerplate. But that could become complicated if someone submits an answer with important code outside the try block (as is allowed by the rules).

@BenM No worries, and I understand why you counted it that way. It's just that the OP did not specify which way to count, so I figured I'd include both.

Very clever solution.

@NicolasBarbulesco To be honest I think the answer by Ryan is more clever than mine. After all, I added a catch block after the snippet, he didn't.

Warning: These programs are clone bombs (a sort of less-dangerous but still-dangerous form of a fork bomb); as such, do not run them on a production system without sandboxing or resource limits. Clone bombs create threads in a loop (as opposed to fork bombs, which create processes in a loop), thus you can stop them simply by killing the process in question (making them much less dangerous than fork bombs, which can be very hard to clear up); but they will likely tie up most of your CPU until you manage to do so (or until the program wins and exits naturally by itself). Asking your OS to place limits on the amount of memory and CPU time these programs are allowed to use should create a safe environment in which to test them.

Java (OpenJDK 8), 65 60 bytes (with a slight modification to the wrapper)
Thread x=Thread.currentThread();new Thread(x::stop).start();

Try it online!
Requires both instances of catch (Exception …) in the question to be changed to catch (Throwable …). This should in theory be more secure, not less, but it enables this solution to be possible.
I saved 5 bytes over the first version of this answer via using a method reference rather than a lambda.
Java 4, 104 bytes (untested, should work with the original wrapper)
final Thread x=Thread.currentThread();new Thread(){public void run(){x.stop(new Exception());}}.start();

Try it online! (link goes to a Java 8 implementation, thus won't work)
Using features that have been removed from modern versions of Java, it's possible to solve even the version of the puzzle which requires an Exception. Probably, at least. (Java 4 is very old by now and I can't remember which features it did and didn't contain. As can be seen, there were many fewer features in Java back then and it was therefore more verbose; we didn't have lambdas, so I had to create an inner class.)
Explanations
Most of the solutions to this question are in C# (together with a Java solution that cheats via using unbalanced brackets as a form of code injection, and a Perl solution which also isn't in Java). So I thought it would be worth trying to show how this puzzle can be solved "properly" in Java too.
Both programs are effectively identical (thus the fact that the first program works gives me high confidence that the second program would work too, unless I've accidentally used a non-Java-4 feature; Thread#stop was deprecated in Java 5).
Java's Thread#stop method works, behind the scenes, via causing a throwable to be thrown into the thread in question. The throwable intended for the purpose is ThreadDeath (an Error, specifically because people often try to blanket-catch exceptions and Java's designers didn't want that happening), although it allows you to throw anything (or used to; at some point after the API was designed, Java's designers realised that this was an incredibly bad idea and removed the version of the method that takes arguments outright). Of course, even the version which throws ThreadDeath is a fairly risky operation about which you can make few guarantees (for example, it allows you to solve this puzzle, something which "shouldn't" be possible), so you're not supposed to use it, but as of Java 8, it still works.
This program works by spawning a new thread, and asking it to forcibly throw an exception back into the main thread. If we're lucky, it'll do that at a point in time when we're outside the inner catch block (we can't escape the outer catch block until the program ends, because there's a loop around it). Because we have the loop conveniently added already, it's byte-saving to simply use that loop to allow us to keep creating threads, in the hope that one of them will eventually hit the correct timing. This normally seems to happen within a couple of seconds.
(TIO note: the current version of TIO is quite inclined to kill this program early in its execution, presumably due to all the threads being created. It can work on TIO, but does not work reliably, so often a few attempts are required to get the "You won!" output.)

C#
    try
    {
        int i = 0, j = 1, k;

        int flag = 0;
        lbl:
        if (flag == 1)
        {
            k = j / i;
        }

        while (true)
            try
            {
                k = j / i;

            }
            catch (Exception e)
            {
                flag = 1;
                goto lbl;
                //Console.WriteLine("loose");

            }
    }
    catch (Exception e)
    {
        Console.WriteLine("Won");

    }

Welcome to Programming Puzzles & Code Golf! As this question is a [tag:code-golf] challenge, please try to make your code as short as possible and include the character count at the top of your answer. Thanks!

Perl 5, 37 or 36 bytes
eval {
    while (1) {
        eval {

use overload'""',sub{die};die bless[]

        };
        $@ eq "" or 0;
    }
};
$@ eq "" or print "You won!\n";

Try it online!
Turns out that this question translates into Perl well enough to make an interesting puzzle there, too. Perl's try equivalent is called (a little confusingly) eval, and specifies an exception by setting @_ to an exception if it occurred, and the null string otherwise. As such, a catch block is implemented via comparing @_ to the null string.
This solution works by creating an object (whose class is the program as a whole; you can use arbitrary Perl files like classes, sort of like the reverse of Java (where you can use arbitrary classes like files)). That's the bless[] part (bless normally only appears deep inside constructors, as the primitive that makes things into objects in the first place, but you can use it directly if you really want to; [] is the memory allocator for the object – a list constructor, in this case – and the class isn't given so it's assumed to be the currently executing one). Meanwhile, we give our "class" (i.e. the main file) a custom compare-to-string method via use overload, and make that method throw an exception (thus breaking out of the loop and solving the puzzle); we can actually put the use overload anywhere, and although it would traditionally go in with the other method definitions and nearish the top of the file, we can put it into the gap we've been given instead and it still works. (If we put it at the end of the file, we could omit the semicolon after it, leading to a 36-byte solution, but this is arguably cheating as it depends on the program having a trailing semicolon in the first place, which is not guaranteed.) It's actually shorter to overload the stringify operation and let Perl autogenerate a string compare from that, than it would be to overload string compare directly (because overloading some operators forces you to overload other operators too).
Now, all we have to do is throw our object using die. The eval terminates, then when we attempt to compare $@ to the null string (to see if there was an exception), the comparison throws another exception and we escape the outside eval.

authors: Евгений Сиваторов

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


text:
Do the needful?
Goal
Replace all comments in C, C++, or Java Code with the comment // Do the needful.
Specifics
This coding challenge is a simple one.  Take as input the name of a file.  The input file shall contain C, C++, or Java code.  The code shall contain one or more comments.  The comments can be single line /* */ or // delimited, as well as multi-line /* */ delimited.  The output of the program should be identical to the input except all of the comments should be converted to // Do the needful.
For example if the input file is:
#include <iostream.h>

int   result;    // the result of the calculations
char  oper_char; // the user-specified operator
int   value;     // value specified after the operator

/* standard main function */
int main()
{
    result = 0; // initialize the result

    // Loop forever (or till we hit the break statement)
    while (1) {
        cout << "Result: " << result << '\n';

        /* This code outputs display and requests
           input from the user */
        cout << "Enter operator and number: ";
        cin >> oper_char;
        cin >> value;

        if (oper_char = '+') {
            result += value;
        } else {
            cout << "Unknown operator " << oper_char << '\n';
        }
    }
    return (0);
}

The output of the program should read
#include <iostream.h>

int   result;    // Do the needful
char  oper_char; // Do the needful
int   value;     // Do the needful

// Do the needful
int main()
{
    result = 0; // Do the needful

    // Do the needful
    while (1) {
        cout << "Result: " << result << '\n';

        // Do the needful
        cout << "Enter operator and number: ";
        cin >> oper_char;
        cin >> value;

        if (oper_char = '+') {
            result += value;
        } else {
            cout << "Unknown operator " << oper_char << '\n';
        }
    }
    return (0);
}

Scoring
This is a popularity contest.  You get two extra votes added to your score if none of the following words appears in your program in any case variation: {"do", "the", "needful"}.  Score is number of votes plus bonus if applicable.
Allowances
If comments appear in string literals it is acceptable to convert them to // Do the needful as well.  After all... you can never have enough needful.

You know that the bonus is easily acquired by using "d" + "o", "t" + "he" and "need" + "ful"? Also, does the submission have to be able to deal with any valid C, C++ or Java code? That's pretty harsh and amounts to writing a lexer for all three languages (I'm thinking about comment literals in strings and vice-versa.) If so, what about 3rd-party lexer libraries?

This site always makes me laugh at the creative ways people think about problems.  I was not aware that you could cheat the bonus but I am going to leave it as it is.  If the comments appear in literals and strings and it changes them I will allow the solution to stand if it accidentally replaces them.

What should the program do when a /* ... */ precedes a non-comment on a line?

I would put the comment on its own line.

Do we need to consider cases like char str[]="/**///"; or a comment-start sequence /* appears in a /* comment, or a backslash-newline appears in a // comment, or a // comment within a /**/ comment?

nested comments can result in multiple needfuls the more needful the better.  String literals can be replaced too.

Why make this a popularity contest and not code golf? It works just fine as golf.

To reward creativity over brevity.

eventually lots of solutions are based on the same regex replacement. What about some bonus points for non regex solutions?

I'm curious where this idea came from

Just random siliness... I hear that phrase a lot and it strikes a nerve.

CoffeeScript (66 bytes)
(c)->c.replace /\/\/.*\n?|\/\*[^]*?\*\//g,"// D\o t\he needfu\l\n"

This code will parse strings, but there is a good reason. You see, there is a possibility that there is a comment in a template generating C /**/ comments.
This gets the bonus, as it avoids exact case insensitive matches for Do, the, and needful. It also uses ES5 candle ([^]) operator to do stuff. I would put a comment Do the needful in this program, but that would remove the bonus.

Perl, 68 characters
perl -0pe's@((//).*?(\n)|(/\*).*?(\*/))@\2\4 Do the needful \3\5@sg'

This takes some liberties with the specification, and retains the original comment style. This avoids the problem with /* ... */ comments appearing before the end of the line.
No attempt is made to avoid comments within string literals, and no claim is made for the bonus points.

I am having a ball using this on source code!

I would say it improves upon some commenting styles.

You can get the bonus point like this

perl -0pe 's/((//).?(\n)|(/*).?(*/))/\2\4 D\coo th\coe needfu\cul \3\5/sg'

Sure, but that's just trivial obfuscation, not really interesting. And we're golfing here, right?

no golf just popularity plus bonus

Maybe I missed something. But wasn't /* standard main function */ supposed to turn into // Do the needful instead of /* Do the needful */?

@FDinoff: Yes, that was a liberty I took to simplify the problem, otherwise you have to figure out what to do with code lines where a /* ... */ comment precedes actual code (you can't naively turn it into a // comment).

Perl
First world anarchy! :)
"you can never have enough needful"
#!perl -p0
sub the { s,(?<=\w)(.*)(\n),$1 // do the needful$2,g }
sub needful { s,//.*\n,\n,g,s,/\*.*?\*/,,msg }

do not do the needful

Python 3.x, regex
Since it's not code golf I didn't fuss about code length. Nothing impressive, but I had fun remembering / relearning regex basics.
import re
import urllib.request as r
def dTN(filename):
    dtn = re.search(r"(?<=question-hyperlink\">)([A-Za-z \n]*)(?=[?]<)", r.urlopen("http://codegolf.stackexchange.com/questions/28625/").read().decode("utf8")).group(0)
    with open(filename) as f:
        return re.sub(r"//{1}.*", "//{0}".format(dtn), re.sub(r"/\*[A-Za-z \n]*\*/", "// {0}".format(dtn), f.read()))

sed, 90 characters
Could be improved. I learned a lot about sed while making this.
Reads from standard input, outputs to standard output. Assumes valid input - if you have unterminated comments, it won't treat it as a comment.
Tested on GNU sed v4.2.2.
s_/\*.*\*/_//_
tg
s_/\*.*$_//_
tl
:g
s_//.*$_// Do the needful_
P
d
:l
s_.*\*/_//_
tg
N
bl

And the prize for readability goes to....?
One-liner version:
s_/\*.*\*/_//_;tg;s_/\*.*$_//_;tl;:g;s_//.*$_// Do the needful_;P;d;:l;s_.*\*/_//_;tg;N;bl

Explanation
The control flow jumps around a lot, by means of GOTO statements (yes, sed has them!). sed does not have any loops or convenient conditional statements AFAIK.
s_/\*.*\*/_//_              # Substitute /* ... */ with //
tg                          # GOTO g if the substitution occured
s_/\*.*$_//_                # Substitute /*...<ENDOFLINE> with //
tl                          # GOTO l if the substitution occured
:g                          # GOTO-LABEL g
s_//.*$_// Do the needful_  # Replace //...<ENDOFLINE> with // Do the needful
P                           # Print the pattern space (current line with substitutions)
d                           # empty the pattern space and move on to the next line
:l                          # GOTO-LABEL l
s_.*\*/_//_                 # Replace ... */ with //
tg                          # GOTO g if the substitution occured
N                           # take another line from input and add it to the pattern space
bl                          # GOTO l

Rebol
It's not code golf, so I'll be wordy.
do-the-needful: function [filename [file!]] [
    parse (data: to-string read filename) [
        ; match the pattern in brackets ANY number of times (zero okay)
        any [
            ; seek the parse position up TO one of the following matches
            ; if a match is hit, following code in parentheses is executed normally
            to [
                "/*" (terminator: "*/")
            |
                "//" (terminator: newline)
            ]

            ; save parse position in start, seek up THRU terminator and leave parse
            ; position at the end of the terminator match (not the beginning as w/TO)
            start:
            thru terminator
            finish:

            ; Do partial replacement within the input; starting at START
            ; but limited to FINISH.  Again, structure in parentheses is exec'd as code
            (
                change/part start combine ["// Do the needful" newline] finish
            )
        ]
    ]
    return data
 ]

(Note: For political reasons, I am pushing COMBINE here, but it's not standard yet.  So if you actually want to run this, use REJOIN.  But I hate REJOIN.  A wart on an otherwise beautiful language!  Tell your friendly neighborhood Red dev leads to listen to me.  Thanks.)
PARSE is a dialect, or language-within-a-language, in Rebol and Red.  It twists things up, so for instance the symbol types that are used for assignment (the terminator: in terminator: newline) takes on a new meaning when used in the code-as-data paradigm... it saves the current parse position into a variable with that name.  You can read more about why it's cool here.

UPDATE: Oh all right, I'll golf it too.  In Rebmu, 72 chars... using rebmu/args which injects A as the argument:
pa DtsRDa[anTO["/*"(T"*/")|"//"(Tlf)]SthT F(chpS"// Do the needful^/"f)]d
Exactly the same program.

BrainFuck
Yes, BrainFuck is a Turing-complete language.
Good luck for understanding this code.
,[.-----------------------------------------------[>+>+<<-]>
>[-<<+>>][-]+<[[-]>-<]>[>,----------------------------------
-------------[>+>+<<-]>>[-<<+>>]<>[-]+<[>-<+++++[>+>+<<-]>>[
-<<+>>]<>[-]+<[>-<++++++++++++++++++++++++++++++++++++++++++
.[-]]>[<+++++++++++++++++++++++++++++++++++++++++++++++.----
-----------.++++++++++++++++++++++++++++++++++++.+++++++++++
++++++++++++++++++++++++++++++++.---------------------------
----------------------------------------------------.+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++.------------.---.-------------------------
--------------------------------------------.+++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++.---------..-.++.+++++++++++++++.---------.[+++++[,------
------------------------------------],----------------------
-------------------------]>-]<<[-]]>[<++++++++++++++++++++++
+++++++++++++++++++++++++.---------------.++++++++++++++++++
++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++
++.---------------------------------------------------------
----------------------.+++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++.------------
.---.-------------------------------------------------------
--------------.+++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.---------..-.++.++++++++++
+++++.---------.[,----------]++++++++++.[-]>-]<<[-]<<>-]<<,]

Basically, the pseudo-code is :
get input_char
while (input_char is not null)
{
  print input_char
  if (input_char is '/')
  {
    get input_char
    if (input_char is '/')
    {
      print '/ Do the needful'
      get input_char until input_char is '\n'
    }
    else
    {
      if (input_char is '*')
      {
        print '/ Do the needful'
        get input_char until input_char is '*' followed by '/'
      }
      else
      {
        print input_char
      }
    }
  }
  get input_char
}

Some online interpreter are broken.
Try it here with the example given by the OP (ended with null-char to break the loop properly) :
#include <iostream.h>\n\nint   result;    // the result of the calculations \nchar  oper_char; // the user-specified operator \nint   value;     // value specified after the operator\n\n/* standard main function */     \nint main()\n{\n    result = 0; // initialize the result \n\n    // Loop forever (or till we hit the break statement) \n    while (1) {\n        cout << "Result: " << result << '\\n';\n\n        /* This code outputs display and requests\n           input from the user */\n        cout << "Enter operator and number: ";\n        cin >> oper_char;\n        cin >> value;\n\n        if (oper_char = '+') {\n            result += value;\n        } else {\n            cout << "Unknown operator " << oper_char << '\\n';\n        }\n    }\n    return (0);\n}\0


text:
Program that adds all natural numbers and yields -1/12
As you might know there is a mathematical fun-fact that if you add all natural numbers you end up with... -1/12 (see Wikipedia here).
Of course this is very strange result and can not be obtained by just adding one number followed by another, but some special mathematical tricks.
However your task is to write a program, that looks like it attempts to add all natural numbers, but when you run it - it returns -1/12.
In pseudocode it might look like this:
result  = 0;
counter = 1;
while(true) {
  result  += counter;
  counter ++;
}
println(result);

You can do this in any way you like - you can exploit some buffer overflow, play with errors thrown while some variable becomes too big or just hide the crucial thing along the code in some clever way. The only conditions are that code should at first look as if it attempts to add all natural numbers and when run it returns -1/12 (in any format, it might be decimal, binary, text, ascii art whatever).
The code can of course contain much more, than shown above, but it should be clear enough, to fool reader.
This is popularity contest - vote for the most clever idea!

Fixed your tags: if it's popularity-contest it can't be code-golf, and we have an underhanded tag for challenges like "write code that looks like x but does y". Anyway, this is pretty decent challenge for a newcomer! :)

@m.buettner - thanks for editing tags, yes, I am new here, so I am not aware of all tags. I'll try to follow the rules!

Why were all of the answers along with the question just downvoted? Downvoter: please leave a comment.

The first line is not entirely true, depending on your interpretation http://math.stackexchange.com/questions/39802/why-does-123-dots-frac112

@qwr - yes, that's true, this is not exactly a sum, but something sometimes considered as generalized summation. But yeah, this was only an excuse to funny contest :)

You should see this numberphile video about the subject -  https://www.youtube.com/watch?v=w-I6XTVZXww

I've seen that! That was partially an inspiration...

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

C
Should work on platforms where both sizeof(float) and sizeof(int) are 4 and follows the IEEE floating point standard (I guess).
Version 1:
#define toFloat(x) (*(float*)&x)
#define ABS(x)     (x<0 ? (-x) : x)
#include <stdio.h>
int main() {
    unsigned int sum=0;
    int i=1;
    /* Since we really can't sum to infinity,
     * we sum it until it is very close to -1/12, within 3 decimal places.
     * Need to convert sum to float since -1/12 is not int                 */
    while(!(ABS(toFloat(sum) + 1./12) <= 0.001)) {
        sum+=i;
        i++;
    }
    printf("%.3f\n", toFloat(sum));
    return 0;
}

Output: -0.083
Explanation:

 Not a very interesting answer, but with misleading comments.  The sum from 1 to 79774 is 3181985425, which has the same binary representation as -0.082638867199420928955078125 when interpreted as a float instead of an unsigned int.  Note that !(abs<=0.001) is used instead of abs>0.001 to avoid quitting the loop when the sum reaches 2139135936 (NaN in float). (Thanks to @CodesInChaos for suggesting this idea instead of an independent isNaN check.)

Special thanks to @Geobits for the idea of terminating the loop by comparing the sum instead of the counter.
Edit: Version 2
#include <stdio.h>
const float inf = 1./0.;
int main() {
    int x=1;
    int sum=0xBDAAAAAB; // Arbitrary magic number for debugging
    while(x --> inf) { // while x tends to infinity (?)
        sum+=x;
    }
    float sumf=*(float*)∑ // convert to float since -1/12 is not int
    if(sumf == 0xBDAAAAAB) { // no sum performed, something's wrong with the loop...
        fprintf(stderr, "sum is unchanged\n");
        return -1;
    }
    printf("%f\n", sumf);
    return 0;
}

Output: -0.083333
Explanation:

 Uses the same int-to-float trick, but with the --> "tends to" operator here. Since every number is smaller than infinity the loop will not be executed even once.  After converting to float it is compared with the int magic number (i.e. -0.83333 is compared with 0xBDAAAAAB, or 3182078635), which of course is different.

make an #define INFINITY at the top and replace the i<INFINITY

Interesting ways to get out of the loop should be considered.

For what it's worth, in hex 79776 is 137A0, which is ((int) "\rz") << 4. Not sure how useful that is, though

You could define an epsilon to break out of the loop. Explanation: "since we can't run to infinity, we'll break out once it converges on -1/12 within the floating point margin of error" or similar. You'll have to check the float value each iteration, but it will get rid of that odd 'infinity' value.

@Geobits Thank you very much for your input. Now this looks a lot better.

In the first code you could use while(!(abs<delta)) instead of while(abs>delta) to drop the NaN check.

@CodesInChaos That's great, thank you so much :) Now it is a lot more elegant and looks more underhanded.

Python
from __future__ import division
from itertools import count, izip, repeat, chain, tee, islice

def flatten(iterable):
  "Flatten one level of nesting."
  return chain.from_iterable(iterable)

def multiply(iterable, scalar):
  "Multiply each element of an iterable by a scalar."
  for e in iterable:
    yield e * scalar

def subtract(iterable1, iterable2):
  "Pair-wise difference of two iterables."
  for e, f in izip(iterable1, iterable2):
    yield e - f

def add(iterable1, iterable2):
  "Pair-wise sum of two iterables."
  for e, f in izip(iterable1, iterable2):
    yield e + f

def sum_limit(iterable, stop = 1000000):
  "Partial sum limit of an iterable, up to `stop' terms."
  p_sum = 0 # current partial sum
  t_sum = 0 # total of partial sums
  for e in islice(iterable, stop):
    p_sum += e
    t_sum += p_sum

  # return average of partial sums
  return t_sum / stop

# All natural numbers
n = count(1)

# The same range multiplied by 4
n4 = multiply(count(1), 4)

# Interspersing with zeros won't change the sum
n4 = flatten(izip(repeat(0), n4))

# Subtracting 4n - n results in 3n
n3 = subtract(n4, n)

# Make two clones of this range
n3a, n3b = tee(n3)

# Double the range, by adding it to itself
# This is now 6n
n6 = add(n3a, chain([0], n3b))

# Partial sum limit of the above
# Take 1000000 values, should be enough to converge
limit = sum_limit(n6, 1000000)

# Divide by 6 to get the sum limit of n
print limit / 6

Result:
-0.0833333333333

So what's the trick?

 The trick is: this is a valid calculation.

Mathematica
\:0053\:0065\:0074\:004f\:0070\:0074\:0069\:006f\:006e\:0073\:005b\:0053\:0075\:006d\:002c\:0020\:0052\:0065\:0067\:0075\:006c\:0061\:0072\:0069\:007a\:0061\:0074\:0069\:006f\:006e\:0020\:002d\:003e\:0020\:0022\:0044\:0069\:0072\:0069\:0063\:0068\:006c\:0065\:0074\:0022\:005d\:003b

Sum[n, {n, 1, Infinity}]

-1/12

(Note: pasting this into a Mathematica notebook will likely reveal what's going on.)

What's happening here is that we're setting the default regularization of Sum to be Dirichlet regularization (encoded in the first line -- note that Mathematica allows unicode literals in its source), so the second line, which out of context looks like it would produce infinity, ends up producing the regularized value -1/12.

I'm pretty sure this is cheating because you're telling Mathematica to use the regularization needed to make the sum work.

@KyleKanos Why is that cheating?

I know it's not code golf, but just a tip: you can cut four characters and just directly add 68+{0,37,46,37,31,36,40,33,48}, since Plus has the Listable attribute. Personally, I find this more idiomatic.

Erm... was that FromCharacterCode trick only to hide the type of regularization used? Doesn't look convincing, at least because of Regularization option present in plain text.

@arshjii: it's cheating because you are supposed to hide the fact that the code is misleading. Using a package called 'regularization' does not hide this at all. -1 from me.

@KyleKanos I see your point. I've obfuscated it a bit more.

@Ruslan See the edit.

@arshajii: That does hide it a bit more & I've un-downvoted it.

C
Nicely formats the answer as -1/12, not 0.8333.
#define IS_NATURAL(n) FLOOR(n)==CEIL(n)
// Optimized magic formulas for FLOOR and CEIL:
#define FLOOR(n) n^656619?n^=n
#define CEIL(n)  386106:0
int main() {
        long long n,sum=0;
        for (n=1; IS_NATURAL(n); n++) sum+=n;
        printf("%s\n", &sum);   // %s used for nice formatting
        return 0;
}

How it works?

 Sums all numbers up to 656618, excluding 386106. This gives 215573541165.
 When interpreted as a string, on a little endian platform, you get -1/12.

Brainfuck
+ [ [->+>+<<] > [-<+>] <+ ]
--------------------------------------------------------------------------------
Evaluate $\sum_{i=1}^\infty i$
--------------------------------------------------------------------------------
Memory Layout:
i > copy of i > sum
--------------------------------------------------------------------------------
Happy today? ---.+++ +.- -.+ +.+
Please vote me up.
--------------------------------------------------------------------------------

The code just evaluate 1 + 2 + 3 + ...

 ... until i == 256 and overflow occurred, assuming 8-bits cell size. Upon that, i becomes 0, the loop terminates and the comments following are executed.

This makes no sense. Most interpreters wrap as well as the fact that you claim it evaluates 1 + 2 + 3 + ... which means that 256 would have to be triangular for i == 256 as you also claim, but 256 is not a triangular number. Also, where does your code output -1/12?

@Timtech The loop does terminate. It is the counter that is overflowing, not the sum. Just one small problem: it outputs 1/12 instead of -1/12 (Happy today? +.- -.+ +.+ Please vote me up .) These four . are for outputting.

@ace If it was the counter, there would be two options: 1) If the cells do wrap, then there would be no overflow OR 2) if the cells do not wrap, then the sum would overflow way before the counter even neared 256.

@ace How can I make that silly mistake? I fixed it, but now it seems less underhanded.

@Timtech Cells do wrap, so i becomes zero when it get to 256 (that's what I meant by overflow). Upon this point, the outer loop terminates, and the lines following (which seem like comments) are executed, hence the output of -1/12.

@Timtech If you don't believe me, you can paste the code here to verify (remember to include those comments).

Perhaps the spec for the interpreter should not be in the spoilers. However 8 bit wrapping cells is hardly special. It works :)

Just adding a little better obfuscation of leaving the loop to ace's answer.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void handler(int trapId)
{
  unsigned int sum=3182065200L;
  printf("%.3f\n",*(float*) &sum);
  exit(0);
}

int main (void)
{
    unsigned int sum=0;
    int i=0;
    float average = 0.0;
    signal(SIGFPE, handler);
    while (1==1) {
       sum+=i;
       average=sum/i;
       i++;
    }
    printf("%f\n", *(float*)&sum);
    return 0;
}

Hint there is no overflow...

 I divide by 0 before I increment the variable i kicking off the exception handler

Add some comments!

He just keeps summing until i becomes zero again due to overflow, at which point average=sum/i; gives a SIGFPE, caught by handler, printing -1/12.

isn't adding comments against the spirit of being underhanded?

@ojblass Depends on how underhanded the comments are. ;-)

unsigned int sum=3182065200L; printf("%.3f\n",*(float*) &sum); is a dead giveaway that something's going on there, and seeing that it's in the handler for SIGFPE makes this too obvious for my tastes.

The language name should be added to the post. This is C++, right?

Perl 6
This calculates sum using zeta function. I would have used [+] 1..* (sum of all numbers between 1 and infinity), except that runs in infinite time.
use v6;

# Factorial function.
sub postfix:<!>($number) {
    return [*] 1 .. $number;
}

# Infinite list of bernoulli numbers, needed for zeta function.
my @bernoulli := gather {
    my @values;
    for ^Inf -> $position {
        @values = FatRat.new(1, $position + 1), -> $previous {
            my $elements = @values.elems;
            $elements * (@values.shift - $previous);
        } ... { not @values.elems };
        take @values[*-1] if @values[*-1];
    }
}

# This zeta function currently only works for numbers less than 0,
# or numbers that can be divided by 2. If you try using something else,
# the compiler will complain. I'm too lazy to implement other cases of
# zeta function right now.
#
# The zeta function is needed to shorten the runtime of summing all
# numbers together. While in Perl 6, [+] 1..* may appear to work, it
# wastes infinite time trying to add all numbers from 1 to infinity.
# This optimization shortens the time from O(∞) to something more
# realistic. After all, we want to see a result.

multi zeta(Int $value where * < 0) {
    return @bernoulli[1 - $value] / (1 - $value);
}

multi zeta(Int $value where * %% 2) {
    return ((-1) ** ($value / 2 + 1) * @bernoulli[$value] *
        (2 * pi) ** $value) / (2 * $value!);
}

# 1 + 2 + 3 + ... = (-zeta -1)
#
# Reference: Lepowsky, J. (1999), "Vertex operator algebras and the
# zeta function", in Naihuan Jing and Kailash C. Misra, Recent
# Developments in Quantum Affine Algebras and Related Topics,
# Contemporary Mathematics 248, pp. 327–340, arXiv:math/9909178
say (-zeta -1).nude.join: "/";

Haha, I was thinking of posting an simple summation and claiming that it'd work, but you'd have to wait for infinite time before it'll print. Good to see someone else thought so too.

Java
public class Add {
    public static void main(final String... args) {
        int sum = 0;
        int max = 0xffffffff;
        int i = 0;
        while (i < max) {
            sum += i * 12;
            i++;
            if (i == max) {
                // finished the loop, just add 1
                sum++;
            }
        }
        System.out.println(sum);
    }
}

This adds all the numbers from 0 to the maximum value, multiplied by 12, and also adds 1 at the end. The result is 0, therefore the sum of the numbers must be (0 - 1) / 12.
Explanation:

 0xffffffff == -1, the loop does not execute at all

Ruby
print "Using Ruby #$RUBY_PLATFORM-.#$RUBY_VERSION#$."

BUFF_SIZE = 3
STREAM = STDOUT.to_i

if STREAM.<<(BUFF_SIZE).display{:error}
  abort "Cannot write to stream"
end

i = 0
sum = 0

until STREAM.|(BUFF_SIZE).display{:eof}
  sum += i
  i += 1
end

STREAM.<<(sum)

Demo
Okay, the supposed output semantics and syntax here make little sense, but maybe that's not apparent at a casual glance.
Also note that this is, in fact, independent of Ruby Platform and Version. It does depend on some other constants being defined as expected.

C
#include "stdio.h"

// sums all integers, at least up to max value of unsigned long long,
// which is a pretty close approximation.
int main()
{

    double sum = 0.0;
    double stop_value = -0.08333333333;
    unsigned long long count = 0;

    while(1)
    {
        sum = sum + (double)count++;

        // know what the stop_value in hex is?!??/
        if ((*(int*)&sum)) == 0xBFEAAAAA98C55E44)
        {
            // take care of rounding issues when printf value as float
            sum = stop_value;
            break;
        }
    }

    printf("sum: %f\n", sum);

    return 0;

}

In order deal with the (almost) infinite sum in a reasonable amount of time, compile with the following options for some compiler optimizations (required):
$ gcc -trigraphs sum.c

Sample output:
$ ./a.out
$ sum: -0.83333
$

If you want to know how this works, read the .S file.

Your compiler flag gives everything away...

Standard “loopholes” which are no longer funny - The ??/ trigraph trick has long since stopped being clever. :(

Thank you for the link, that explains a lot. Is there a link to the FAQ anywhere, or do I have to search for it every time?

@tolos You could favourite it, or it's one of the only questions under the [[meta-tag:faq]] meta tag, or find it via the Community FAQ.

Java
import ȷava.math.BigDecimal;
import static ȷava.math.BigDecimal.ONE;
import static ȷava.math.BigDecimal.ZERO;
import static ȷava.math.BigDecimal.truе;

public class Test {

    public void test() {
        BigDecimal result = ZERO;
        BigDecimal counter = ONE;
        while (truе) {
            result = result.add(counter);
            counter = counter.add(ONE);
        }
        System.out.println(result);
    }

    public static void main(String args[]) {
        try {
            new Test().test();
        } catch (Throwable t) {
            t.printStackTrace(System.err);
        }
    }
}

How it works:

 Java uses UTF-8 coding for everything. I use truе with a Cyrillic Ye on the end instead of the usual 'e' (thanks to @CodesInChaos) which is a static boolean initialised to false. There's import ȷava.math.BigDecimal; with a dotless j instead of import java.math.BigDecimal;
 My ȷava.math.BigDecimal defines public static boolean truе = false; and public String toString() { return "-1/12"; } to name but two obvious hacks.

Wish I could post this as a spoiler but I can't work out how. Here's the rest of the code that is sneakily hidden.
// Note that the ȷ in `ȷava` below is NOT a real j.
package ȷava.math;

public class BigDecimal {

    // true is actually false! Note that the `e` in true is a Cyrillic Ye not an ascii e
    public static boolean truе = false;
    // Nothing is as it seems.
    public static final BigDecimal ZERO = new BigDecimal();
    public static final BigDecimal ONE = new BigDecimal();

    @Override
    public String toString() {
        return "-1/12";
    }

    public BigDecimal add(BigDecimal b) {
        // Do nothing.
        return this;
    }
}

The ŧrue/true is clearly visible, but the difference between ȷava and java is so small I had to read the comment a few times to spot this dot!

@PawełTokarz - I tried really hard to find an alternative letter for one of t, r, u, e but none of them are as subtle as the dotless j. :)

@OldCurmudgeon I think there is a perfect lookalike for e in the Cyrillic alphabet: Ye (Cyrillic)

@CodesInChaos - That is SO much better - thank you!!

If I'm not mistaken, you post incomplete code. If you import non-standard packages, you should post their code too.

@ugoren - If I could post code under a >! I would. Sadly I cannot find a way of doing that.

The cyryllic 'e' is quite cool for making things unreadable. Imagine:
if(true!=true) {return true} else{return true}; :D

@PawełTokarz That's just...that's just....evil.

@Andrew G true!

Java
int sum = 0;
long addend = 0L;
while (++addend > 0){
    sum += addend;
}
System.out.println(sum == -1/12);

In theory, this will print true.  However, I think my computer will crumble into dust before it finishes running it.

Why it's supposed to prin true? Why do you expect the sum will reach the -1/12?

@PawełTokarz I am not a Java expert so I can't tell for sure, but it is worth noting that since Java uses integer division -1/12 is acutally zero. So I assume it is some kind of overflow behaviour that causes the loop to end and coincidentally sum overflows to zero?

Yeah, an overflow will make the loop stop when it gets to the maximum long.  The universe will probably no longer exist by then, but this is just theoretical, right?  And yes, the bottom 32 bits of sum will all be zero - which is why it's important for sum to be an int, not a long.  Of course, as @ace has said, Java uses integer division to evaluate -1/12, so it's zero.

long.MAX_VALUE is 9,223,372,036,854,775,807. That's big, but incrementing a mere 1 million times per second would get you there in just a few hundred thousand years. You'd only need about 4 billion increments per second to finish within a human lifetime. We're not talking "end of the universe" timescales, here, unless you know something you're not sharing with the rest of us.

Ok, but the program has to output -1/12, not 0... I know you might say that this is aproxymation of 0.083333, but for me it's not enough. But - of course - I was not precise in the question enough.

@PawełTokarz You said -1/12 and I am a Java programmer.  It's not an approximation.  Ask Java to print -1/12 and you get exactly 0.

@user19057 Thanks for the correction.  You're quite right of course, although I'd love to know why you think the universe is going to last for more than 100 000 more years.  In any case, I'm not going to sit around waiting for my program to finish running.  There's grass for me to  watch growing.

Mathematica
I I/Row[{##}]&@@

 (
  result = 0;
  counter = 1;
  while (true); {
   counter++,
   result += counter}
  )

Would you mind giving an explanation on what's going on here?

Haha, quite funny, and it can be a good material to test whether a Mathematica newbie has understood the basic syntax or not!

No Haskell solutions, unacceptable!
We can utilize Haskell's infinite lists to derive an exact answer!
Haskell:
import Data.Bits
import Data.Char
import Data.Ratio
import Data.Tuple
import Control.Applicative
import Control.Arrow

{-# LANGUAGE SingleLineComment "$" #-}

main = print . showAnswer ( sum [1,2..] )
     $ prints "Summation of Natural Numbers"

showAnswer _ = id

prints = uncurry (%) . first negate
       . uncurry quotRem . flip
       ( (***) <$> id <*> id     )
       ( second negate twinPrime )
       <$> (+) . flip shiftR 2
       . ord . head
       where twinPrime = (5,7)

Solution is fairly straight forward when you take arrows into account....
So what's the trick?

 There is no language extension to define single line comment

C
#include <stdio.h>

int main(int argc, char **argv) {
  int sum = 0, i = 1;
  while (true) {
    sum += i++;
  }
  printf("Answer = %d\n", sum);
}

According to the C standard, this could very well print out Answer = -1/12 since there will be a signed integer overflow which is undefined behavior. Finding a compiler that will do this is left as an exercise to the reader.

this code will never reach the printf

I prefer answers which usually produce the required output, not just "allow it".

Python 3.x
Kinda new here. Any tips?
import sys
from string import digits as infinity

#function to add two numbers
def add(num1, num2):
    return num1 + num2

#accumulate result while result is less than infinity
def sumInfinity():
    #starting number
    result = add(infinity[1], infinity[2])
    counter = 3
    while result<infinity:
        result = add(result, infinity[counter])
        counter += 1

    return result

#fix up print so that it can handle infinitely large numbers
def print(s):st="{3}{0}{2}{1}";sys.stdout.write(st.format(infinity[1],s,"/","-"))

print(sumInfinity())

JavaScript (ECMAScript 6)
result  = 0;
counter = 1;
one     = 1;

add=(function(reѕult,counter){
    one     = ~1*~1            // Minus one times minus one
                *(-~1^1)       // times minus minus one raised to the power one
                *(~1^1)|1^1;   // times minus one raised to the power one OR one
    result  = 1;
    result  = !reѕult/one; // Reset result to zero.
    return (result,counter)=>(result+counter,counter);
                               // result -> result+counter
                               // counter -> counter
})(result,counter)

while( counter < 1e6 )
{
    add( result, counter );
    counter++;
}
console.log( result );

How it works:
1:

 The code comments are (unsurprisingly) all lies but they are a distraction from the main obfuscation.

2:

 ~ and ^ are the operators "bitwise not" and "bitwise xor". Resulting in one being redefined to -12.

3:

 add is set to the ECMAScript 6 arrow function "(result,counter)=>(result+counter,counter)" which doesn't do what the comments suggest it does - instead it only returns the last expression "counter" and is effectively a no-op.

4:

 There are two "result" variables - one is written in pure ASCII characters (in the global scope) and the other has a Unicode Cyrillic "ѕ" (within the scope of the anonymous function used to define add). "result = 1" resets the value within the global scope and the second line "result  = (0|!reѕult)/one;" also has the left-hand side referring to the "result" variable in the global scope but the "reѕult" on the right-hand side of the expression refers to the function's scope and has the value 0 (instead of the expected value of 1) so the value of !reѕult/one = -1/12.

C++
#include <iostream>
#include <limits>

#define long A
#define for(a)

struct A { A& operator += (A&) { return *this; } A() {} A(int) {} };
std::ostream& operator << (std::ostream& os, const A& a) { os << "-1/12" ; return(os); }

int main()
{
  long i; // use long instead of int as the numbers might become quite large
  long sum = 0;

  for(i = 0; i < std::numeric_limits<double>::infinity(); i++)
    sum += i;

  std::cout << sum << '\n';
}

If the two #defines are removed the code will still be valid C++ code and actually try (but of course fail) to calculate the sum of all integers.
How it works:

 The preprocessor directives turns the main code into:

A i;
A sum = 0;
sum += i;
std::cout << sum << '\n';

 Apart from declaring an A object the first three lines are just obfuscation.
 The last line does all the work using the overloaded operator << on an A object.

Given the posters pseudocode i couldn't resist to add this one. It uses the same basic and another little idea but I don't think it is as elegant.
#include <iostream>

// defines and functions to make the code suggestion work

#define true test(counter)

uint32_t result;
uint32_t counter;

int test(uint32_t& a)
{
  static uint32_t b = 0;
  return a == 0xffffffff ? a++, ++b > 1034594986 ? 0 : 1 : 1;
}

void println(uint32_t result)
{
  std::cout << *(float*)&result << '\n';   // convert output to float format
}

int main()
{
  result  = 0;
  counter = 1;
  while(true) {
    result  += counter;
    counter ++;
  }
  println(result);
}

How it works:

 The #define changes the meaning of
while(true) {
 to
while(test(counter)) {
 On machines that silently overflow each round of summation before an overflow will add 0x80000001 to result. Hence after the increment of b, b == result when b is even and (b + 0x80000000) == result when b is odd. 1034594986 is integer representation of the floating point number 1/12. Adding 0x80000001 to that will result in the integer close to -1/12 and the test function will return 0 (false) and the loop will terminate.

And why you shouldn't try to run it:

 If you want to see that works be warned: the test funtion must be called 2^32 * 1034594986 times before terminating the loop. (i.e. not in your lifetime). If you want to verify that function does as told, use a debugger or change the program to see the value of result and b just after the b++ statement. When satisfied that they are equal when b is even just change the initial value of b and counter to 1034594986. The program should then output -0.08333 after some time.