text:
List the first 20 friendly number pairs
I just started reading about friendly numbers and I think they sound great.

In number theory, friendly numbers are two or more natural numbers with a common abundancy, the ratio between the sum of divisors of a number and the number itself. Two numbers with the same abundancy form a friendly pair; n numbers with the same abundancy form a friendly n-tuple.

So, how small  a program can you write to output a list of the first 20 friendly numbers.
Assuming I've understood everything I've read correctly the output of your program should be:
6,28
30,140
80,200
40,224
12,234
84,270
66,308
78,364
102,476
6,496
28,496
114,532
240,600
138,644
120,672
150,700
174,812
135,819
186,868
864,936
222,1036
246,1148

I'd also like to add that the program must calculate the answers and not use any external resources or hard coded answers (thanks Peter).

can you quote the definition here? We StackExchangers don't like having to visit external sites :-)

Two things. Firstly, you ask for the first items but you haven't defined a total ordering on them. Secondly, you make the common beginner's error of not taking requiring the program to do the calculation. I strongly advise you to edit the question to prohibit the use of external resources (or someone will submit a program which downloads the answer) and to require the program to input N and output the first N such pairs (or someone will submit an answer which just uncompresses a precomputed literal string).

In addition to @PeterTaylor's remarks - in case you consider N being variable you'd have to specify how n-tuples with n>2 should be handled.

+1 to @PeterTaylor. Aside from prohibiting external resources, you also need to forbid hard-coding of the numbers.

I think you missed 6,496 and 28,496 in your list.

Thanks Marinus, I've added those in - I'll update my program to fix it too.

It may go without saying, but you should specify known friendly numbers.  There are many small numbers (including 10) which have no known friends but which are not known for certain to be solitary.

@MarkReed That's arguably contradictory. Specifying the output only needs to include known friendly numbers may lead to hard-coded limitations which would not truly have the program calculate friendly numbers on its own. However, it is also worth noting that the only way to prove a number is solitary (without hard-coding it) would be to exhaustively search infinity to determine that it indeed has no friends - something which is obviously impractical.

@lszi I only meant that we can't definitively say that the output is "the first N friendly numbers" since some other number may displace one of the N via discovery of a friend. I did not mean to imply any logical changes to the code, on the wording of the problem.  Also, there are ways to prove solitude without exhaustion, but they're involved and generally quite specific to the number whose solitude is in question.

APL (50)
↑⊃,/{g/⍨{=/{⍵÷⍨+/z/⍨0=⍵|⍨z←⍳⍵}¨⍵}¨g←⍵∘.,⍳⍵-1}¨⍳936

The list is slightly different but oeis.org agrees with me.
Output:
 28   6
140  30
200  80
224  40
234  12
270  84
308  66
364  78
476 102
496   6
496  28
532 114
600 240
644 138
672 120
700 150
812 174
819 135
868 186
936 864

C (132)
x=1,e;float d(a,b){return b?1.f*(a%b==0)*b/a+d(a,--b):0;}main(){while(x<1148)for(e=x++;--e;)d(x,x)-d(e,e)||(printf("%d,%d\n",e,x));}

Thanks to shiona for the ideas on shorter code.
And Felix Eve for the Code(counting down makes more sense if you only search pairs).
With the added Pairs even shorter.
Readable Version:
x=1,e;

float d(a,b)
{
    return b?1.f*(a%b==0)*b/a+d(a,--b):0;
}

main()
{
    while(x<1148)
        for(e=x++;--e;)
            d(x,x)-d(e,e)||(printf("%d,%d\n",e,x));
}

There are a lot of improvements to this. I'll make some edits and put them to a pastebin or something and link here.

Yes I am Pretty sure, that this can be less than the hard coded Results and I found a few Bytes to optimize out.

http://pastebin.com/AVX6KNau It's by no means perfect, but I hope it'll help you make messier C code :D

Yes, I have to try my new C skills at work, I think my code looks too clean :P

No need to include header file. It will compile without header file(with warnings about impicit declaration of built in functions).You can also just declare main() instead of int main().Perhaps you may try this trick too ;) main(x,e,f){x=1;f=21;

Since you couldn't get the default int & no headers trick working, I'm wondering. Is your file .c or .cc (or .cpp). gcc tries to be clever and compiles the two latter as c++. The file I provided does compile for me with gcc 4.8.2 when saved with .c extension.

You are right it actually does compile I thought the warning was an error.

Ruby, 90 characters
h={}
1.upto(1150){|n|s=0
1.upto(n){|x|s+=x if n%x<1}
r=s/n.to_r
p [h[r],n] if h[r]
h[r]=n}

Nice, although it doesn't include the line [6, 496], here are the results: http://ideone.com/HrLpbr

Mathematica 114 112 99  90
Numbers having same abundancy. (90 chars)
This  displays integers with a common abundancy. Notice that 6, 28, and 496 have the same abundancy, which means that (6,28), (6,496) and (28, 496) are friendly number pairs. Likewise, 84, 270, 1488, 1638 have the same abundancy.
Because, as Peter Taylor noted, there is no method suggested for total ordering, it is unclear which pairs constitute the "first 20" friendly number pairs.
Grid@Cases[GatherBy[{k, 1~DivisorSigma~k/k}~Table~{k, 2000}, Last], x_ /; Length@x > 1
:> x[[All, 1]]]

I  used the term abundancY because otherwise the auto-spelling checker coverts the word to abundance.

Mathematica 62 58 55
Grid@Cases[GatherBy[Range[6!],Tr@Divisors@#/#&],{_,__}]

6   28  496
12  234
30  140
40  224
66  308
78  364
80  200
84  270
102 476
114 532
120 672
138 644
150 700
240 600

You may go up to 9! without affecting the char count

Using awk (303, uncompressed)
 awk 'BEGIN{for (i=1;i<=1150;i++)
             { for (j=1;j<=int(i/2);j++)
                  if (i%j=="0") a[i]+=j
                v=sprintf("%.10f",(a[i]+i)/i)
                #print v,i
               b[v]=b[v] FS i
              }
           for (i in b) {l=split(b[i],x,FS);if (l>1) print b[i]}}' file|sort -n

 6 28 496
 12 234
 30 140
 40 224
 66 308
 78 364
 80 200
 84 270
 102 476
 114 532
 120 672
 135 819
 138 644
 150 700
 174 812
 186 868
 222 1036
 240 600
 246 1148
 864 936

C - 188
I assume someone will do this with a language that supports literal newlines and requires less boilerplate.
main(){puts("6,28\n30,140\n80,200\n40,224\n12,234\n84,270\n66,308\n78,364\n102,476\n114,532\n240,600\n138,644\n120,672\n150,700\n174,812\n135,819\n186,868\n864,936\n222,1036\n246,1148");}

PHP - 260
$x=1;while($i<20){$d=0;$y=$x;for($y=$x;$y>0;$y--){if($x%$y==0)$d+=$y;}$f=$d/$x.'';$s[$f][]=$x;if(count($s[$f])>1) {$i++;if(count($s[$f])>2){$o[]=$s[$f][0].','.$s[$f][2];$o[]=$s[$f][1].','.$s[$f][2];}else $o[]=implode(',',$s[$f]);}$x++;}echo implode('
',$o);

Uncompressed:
$x=1;
$o = array();
while($i<20) {
    $d = 0;
    $y = $x;
    for($y=$x;$y>0;$y--) {
        if($x%$y==0) $d += $y;
    }
    $f = $d / $x.' ';
    $s[$f][] = $x;
    if(count($s[$f])>1) {
        $i++;
        if(count($s[$f])>2) {
            $o[] = $s[$f][0].','.$s[$f][2];
            $o[] = $s[$f][1].','.$s[$f][2];
        } else {
            $o[] = implode(',', $s[$f]);
        }
    }
    $x++;
}
echo implode('
', $o);

This answer is longer than my other answer but works properly (doesn't skip any numbers and only has 2 numbers per row) so I'm more happy with this one.

C#: 208
public class A{static double D(int n){return 1f*Enumerable.Range(1,n).Where(i=>n%i==0).Sum()/n;}static void Main(){for(int j,i=1;i++<865;)for(j=1;j++<1000;)if(A.D(i)==A.D(j)&&i<j)Console.WriteLine(i+" "+j);}}


text:
Shortest self-modifying code to wish a happy New Year!
Your code just has to print "Happy 2013".
However, if it detects that it's 2014, it has to modify itself (as a running process!!) and print "Happy 2014" instead.
By self-modifying I mean the running process must really modify itself: it should alter its own instructions while it is executing.
Shortest code wins.
-10% size bonus if it's general, so it works for 2015, etc.
Sorry if the task excludes some languages or systems where it's not possible...

Please explain what "modify itself (as a running process!!)" means.

@DavidCarraher : http://en.wikipedia.org/wiki/Self-modifying_code

Bash / shell script (35 chars - 10% = 31.5)
I think this shell script counts as self-modifying:

$ eval "y()(echo Happy `date +%Y`)";y
Happy 2013
$

At least, it does modify its own function y:

$ set | grep -A3 '^y ()'
y ()
{
    ( echo Happy 2015 )
}
$

@manatwork suggested eval "y()(date +Happy\ %Y)";y, which produces the desired output, but I'm not sure if this counts as self-modifying, to the extent that it self-modifies with the current year.  The generated function is as follows, which won't be a different function on a yearly basis:

y ()
{
    ( date +Happy\ %Y )
}

If it does count, then the score is:
Bash / shell script (29 chars - 10% = 26.1)

A lot of entries don't seem to make any attempt to self-modify.  If we lift this restriction for shell-script, then we can do this which weighs in at:
15 chars - 10% = 13
date +Happy\ %Y

Good one, but can be shorter: eval "y(){ date +Happy\ %Y;}";y. By the way, please add a heading line (with some kind of formatting) to your post containing language, character count and score.

Thanks @manatwork - I'm not sure if that counts or not - see my edit.  But thanks for the suggestion.  This is my first answer on PPCG, so my apologies for not getting the score and formatting thing right.

Ah, you mean, the generated code is also generic, not year-specific. Good point. I thought, as function y not existed before running the code, creating it is a modification. Not sure anymore.

IMHO defining a function on the fly with eval is not self-modification of running code, it's just part of the language.

PHP
Creation of source code statement: 26 - 10% = 23.4
eval('?>Happy '.@date(Y));

Overlay of existing instruction: 255 - 10% = 229.5
This can only possibly work on Linux systems configured with a writable /proc/self/mem, and short_tags = On is also assumed. (If short_tags = Off, replace <? with <?php , for a score of 233.1.)
<?$p='/proc/self/';$f=fopen($p.@mem,'r+');foreach(file($p.@maps)as$L)if(sscanf($L,'%x-%x rw%c',$i,$e,$n)>2)for(fseek($f,$i),$a=@xxxx,$e-=$i-4;$e-=4;){$b=$a;$a=fread($f,4);if($j=@strpos("x$b$a",GO.LF)){fseek($f,$j-9,1);fputs($f,@date(Y));}}$f=0?>Happy GOLF

Reformatted for readability:
<?
$p = '/proc/self/';
$f = fopen($p . @mem, 'r+');
foreach (file($p . @maps) as $L)
if (sscanf($L, '%x-%x rw%c', $i, $e, $n) > 2)
for (fseek($f, $i), $a = @xxxx, $e -= $i - 4; $e -= 4;) {
    $b = $a;
    $a = fread($f, 4);
    if ($j = @strpos("x$b$a", GO.LF)) {
        fseek($f, $j - 9, /* SEEK_CUR */ 1);
        fputs($f, @date(Y));
    }
}
$f = 0
?>Happy GOLF

+1 This is the only real self-modifying code posted yet!

APL, self-modifying*, general – 72 chars
Tested on Dyalog APL. On other systems you might have to adjust the 3+ on line 3.
∇H
y←2012
→(y=z←1⌷⎕TS)/k
x←⎕CR'H'⋄x[2;3+⍳4]←⍕z
⎕FX x⋄H⋄→0
k:⎕←'Happy'y
∇

(*) This function does the following:

set a variable y to some constant year;

test whether y points to the current year; if not:

update its own definition, changing the numeric constant in the first line so that it sets variable y to the current year;
call itself recursively, so that the recursive call uses the new definition.

Whether this is acceptable as self-modifying, I'll leave to the OP to decide.
Example invocation, displaying the function code before and after the invocation. As you can see, line 1 has changed during the invocation:
      ∇H[⎕]∇
[0]   H
[1]   y←2012
[2]   →(y=z←1⌷⎕TS)/k
[3]   x←⎕CR'H' ⋄ x[2;3+⍳4]←⍕z
[4]   ⎕FX x ⋄ H ⋄ →0
[5]  k:⎕←'Happy'y

      H
 Happy  2013

      ∇H[⎕]∇
[0]   H
[1]   y←2013
[2]   →(y=z←1⌷⎕TS)/k
[3]   x←⎕CR'H' ⋄ x[2;3+⍳4]←⍕z
[4]   ⎕FX x ⋄ H ⋄ →0
[5]  k:⎕←'Happy'y

Forth: 22 / 32 Chars.   ( Using gforth )
s" Happy 2022" swap +!              ( 22 chars )

A compiled but slightly longer version is shown here,
as the result can be decompiled, and its effects demonstrated.
Principle of operation is identical to the shorter version above.
Consider the longer version as demonstratable proof of concept.
: happy s" Happy 2022" swap +! ;    ( 32 chars )

I'll decompile this first, then execute, and decompile it again:
see happy    ( decompile happy, as it is now )

: happy
s" Happy 2022" swap +! ;

happy   ( execute the self-modifying happy )

see happy ( decompile happy again )

: happy
s" Rappy 2022" swap +! ;

What happens here is:
s" ..."  places two items on stack: address of first string character, and string length, which is 10 in this case. The sequence "swap +!"  adds string length, 10, to the contents at first string address, thereby changing ASCII H to ASCII R.
A version matching the requirements slightly better is compiled using vfx:
: h 1 s" Happy 2021" 2dup type + 1- c+! ;

reason for using a different compiler for this version is that it provides c+! already which I'd have to add to gforth first, which should introduce a penalty of about 22 chars.
disassembling first:

( 080C0AF0    E81383F9FF )            CALL      08058E08      (S") "Happy 2021"
( 080C0B00    8BD3 )                  MOV       EDX, EBX
( 080C0B02    035D00 )                ADD       EBX, [EBP]
( 080C0B05    4B )                    DEC       EBX
( 080C0B06    800301 )                ADD       Byte Ptr 0 [EBX], 01
( 080C0B09    8BDA )                  MOV       EBX, EDX
( 080C0B0B    FF15B9DE0408 )          CALL      [0804DEB9]      TYPE
( 080C0B11    C3 )                    NEXT,

executing several times, output follows immediately:

h  Happy 2022
h  Happy 2023
h  Happy 2024
h  Happy 2025
h  Happy 2026

disassembling again:

( 080C0B30    E8D382F9FF )            CALL      08058E08        (S") "Happy 2026"
( 080C0B40    8BD3 )                  MOV       EDX, EBX
( 080C0B42    035D00 )                ADD       EBX, [EBP]
( 080C0B45    4B )                    DEC       EBX
( 080C0B46    800301 )                ADD       Byte Ptr 0 [EBX], 01
( 080C0B49    8BDA )                  MOV       EBX, EDX
( 080C0B4B    FF15B9DE0408 )          CALL      [0804DEB9]      TYPE
( 080C0B51    C3 )                    NEXT,

Welcome to Code Golf, and nice answer!

Thank you. I'm aware that this answer doesn't quite match the requirements. So I added the aspect of timelessness, for the years to come at least - After Rappy comes Sappy, then Tappy.  After that, wait to enjoy Wappy and Zappy.

And not to forget Yappy :)

Python (144 characters; 130 after removal of 10%)
This codes writes a library, thats imported (again after updating the code) and used.
import datetime
f=open("y.py",'w')
f.write("def year():return "+str(datetime.date.today().year))
f.close()
import y
print "Happy "+str(y.year())

Befunge 98, 26 bytes - 10% (bonus) = 23.4
"EMIT"4(Yd0p"  yppaH"5k,.@

The first space immediately after the quote gets overwritten with a unicode character with code point equal to the year.
The self-modifying part of this code actually makes it more verbose. The below code performs the same task without self-modification:
"EMIT"4(Y" yppaH"5k,.@

Perl (100 characters (90 after removal of 10%))
$^I="";@ARGV=$0;s/ \K\d+/$l=(localtime)[5]+1900/e,print while<>;exec perl,$0if$&!=$l;print"Happy 1
"

It's probably too long, but I don't care (at least it's round in its size). Could be shorter if it would read UTC time (replace localtime with gmtime). Please note that after running, it will increase its size to 103 characters (unless you run this in year 10000, then 104 characters), but hey, it's self-modifying.

Racket - 139 - 10% = 125.1
(let g((y(date-year(seconds->date(current-seconds))))(h"Happy ~a~%"))
(if(< 2013 y)(begin(set! g(lambda()(printf h y)))(g))(printf h 2013)))

Ungolfed:
(let g ((y (date-year (seconds->date (current-seconds))))
        (h "Happy ~a~%"))
    (if (< 2013 y)
        (begin
          (set! g (lambda () (printf h y)))
          (g))
        (printf h 2013)))

So I'm using a named let which is creating a procedure g and calling it with the parameter y (current year) and h (printf format string). If y is higher than 2013 i redefine g to a procedure that takes no arguments and prints a suitable string for the current year instead just before calling the new procedure. It's short since h and y are in the new procedures closure variables.

Not self-modifying.

@Tobia How about now?

IMHO you're still using an if that chooses between two code paths, you're not modifying the actual source code being run. See the PHP answer by @PleaseStand (the longer one) for an example of actual self-modifying code.

@Tobia According to the wikipedia page changing function pointers are considered self modifying. I change a two argument procedure to a zero argument procedure of one line after 2013. The PHP example doesn't change it's code but elements of it's data segment. In reality only machine code can alter itself and it needs a low security OS to do it.

I agree that the PHP example is only changing its data segment and not its bytecode, but I still think it's the most "self-modifying" code in all this page. Self modification is not restricted to machine code: interpreted languages can alter their source, bytecode, or whatever data structure is being traversed by the interpreter. This is not exposed by most interpreters, but it can be done through pointer manipulation or /proc/self/mem tricks, like in the PHP example. Still, my answer is not better than yours, so I might as well remove my downvote :)

Python 2,(151-10%)=136
Inspired by this answer
from datetime import*
s=int(str(datetime.now())[:4]);x=2013;q=globals
def l(): return x
n="def l():return[x,s][s>x]"
exec(n,q(),q())
print'Happy %d'%l()

I wouldn't consider exec as self-modification, it's just part of the language.

@Tobia i have modified my answer please re-consider

I still think changing a function definition or using exec is not proper "self-modifying" code. But my answer is not better than yours, so I will remove my downvote.

JavaScript (ECMAScript 5)/HTML (HTML5) - 106
<script id=k type=x>2013</script><script>k.innerHTML=new Date().getFullYear();alert('Happy '+k.innerHTML);

And here is the jsfiddle
Note that in the jsfiddle, I included a closing </script>, but it isn't necessary, it is just necessary to work in jsfiddle

Are you sure? unclosed script tags don't work on my browsers.

The idea of using innerHTML to modify the source code is neat, but IMHO this is not self-modifying code, because the modified part does not actually execute. You just use k.innerHTML like any other string variable.

It doesn't say in the code anywhere that it needs to execute the code, it just needs to be self modifying. And this is.

Javascript 122 - 10% = 109.8
function n(){y=0;z=new Date().getFullYear();if(y-z){eval((""+n).replace(y,z));alert("Happy new "+z)}setTimeout(n,1000)}n()

It will greet you with a happy new year for the current year, and also keep checking periodically forever and greet you again if a new year comes.

Not self-modifying.

PHP, 28 (-10% is 25)
echo"Happy ".date('Y')."!";

How is this self-modifying?

Not self-modifying.

HTML/JavaScript - 63 (70-10%)
<body onload="b.innerHTML=new Date().getFullYear()">Happy <b id=b>2013

Not self-modifying.

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:
Create a Y2K disaster
Your program can do anything you want. The only condition is that it perform as expected if the date is before 2000, and fails spectacularly afterward. Define spectacularly however you'd like.
For all those people who missed the first Y2K, here's your chance!
Answer with highest score wins.

I like the answers so far, but I was really looking for  something that looks "unintentional".

Hmmm... I'll try to think about how I could make something like that ;-)

What should happen on 1899? Or something like 573 B.C.? Undefined behavior?

I wonder if anyone's going to manage to create an actual "bug", some of the top voted answers are basically just "if date>1999 do disaster"

Python
Real Y2K bugs are about the year being represented as a 2-digit number. And doing something wrong when that number overflows to 0. Such as this nuclear missile watchdog, launching all ICBMs if we haven't received a heartbeat message from HQ in 60 seconds.
import datetime, select, socket, sys

launch_icbm = lambda: (print("The only winning move is not to play"), sys.exit(11))
now  = lambda: int(datetime.datetime.now().strftime("%y%m%d%H%M%S"))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 1957))
last_message_received = now()

while True:
    r, w, e = select.select([sock], [], [], 10)
    if sock in r:
        msg = sock.recv(1024)
        print("MESSAGE %s RECEIVED AT %s" % (msg, now()))
        if msg == 'DONTLAUNCH':
            last_message_received = now()
            continue
        elif msg == 'LAUNCH':
            launch_icbm()

    # Is HQ dead?
    abs(now() - last_message_received) > 60 and launch_icbm()

Very irresponsible, but yeah. +1

I imagine the New Year's Eve party at HQ was lively the morning of January 1, 2000.

Java and cmd
import java.util.*;
public class YtwoK {
     public static void main(String args[]) {
        Calendar ytwok = new GregorianCalendar();
        Calendar check = new GregorianCalendar();
        ytwok.set(2000,0,1,0,0,0);
        if(check.after(ytwok)){
          Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "disaster.bat" } );}}}

Where disaster.bat is
@echo off
Start ""  "C:\Program Files (x86)\Internet Explorer\iexplore.exe"

Do I understand correctly that Internet Explorer is your disaster? +1

Yes, Internet Explorer is my disaster :P

Not enterprise enough, because path to Internet Explorer is hardcoded. It won't start on 32-bit version of Windows, for example.

Code which has Y2K problem, and requires Windows 64-bit (the first release of which was released in 2001). I didn't knew you can have a Y2K problem in code that requires software written after 2000.

Fair point, but it was an example that could be tested on my machine. Back in 2000, IE wasn't all that bad either, so the joke doesn't really work either....

Ruby, code golf (31 chars)
`rm -rf /`if Time.new.year>1999

It's supposed to do nothing. The failure is quite "spectacular" (on old Unix systems without the preserve root flag) :-)

WARNING. DO NOT RUN THIS lol.

this is somewhat dangerous XD

Oof. What a failure.

Not really original because obvious. Also, as Dennis writes, "[r]eal Y2K bugs are about the year being represented as a 2-digit number."

Ruby (962 characters)
To be honest, the disasters here don't look authentic. I decided to make something that seems more... uhm... legit. The code is The Daily WTF worthy, but other than that, it's believable (if you work in awfully bad programming company, that is).
Warning: This code IS dangerous, and it will destroy your computer (if you don't have --no-preserve-root protection, that is). Do not run.
# The decade data standard enforcer (removes data that shouldn't
# be here). It should be ran as a cronjob every day, at midnight.

# We will need to get current year.
require 'date'

# Get decade for a year.
def get_decade(year)
    case year
    when 1900..1909
        "00s"
    when 1910..1919
        "10s"
    when 1920..1929
        "20s"
    when 1930..1939
        "30s"
    when 1940..1949
        "40s"
    when 1950..1959
        "50s"
    when 1960..1969
        "60s"
    when 1970..1979
        "70s"
    when 1980..1989
        "80s"
    when 1990..1999
        "90s"
    end
end

# Remove the selected file
def delete_file(file)
    system "rm -rf /#{file}"
end

# Remove directory for the current decade. It still didn't complete,
# so there should be no directory for the decade. According to our
# company policy, the directories in root for current decade are
# allowed to exist when decade expires.
delete_file(get_decade(Date.today.year))

Beware, or this will circulate as a destruction-ware virus.

SH
#!/bin/sh
echo "It is before 2000"

Lying is a very terrible thing:)

Javascript
var fib = function(n) {
    var date = new Date();
    if(date.getFullYear() >= 2000) {
        window.location.href = "https://myspace.com/signup";
    }

    if(n == 0 || n == 1) {
        return 1;
    } else {
        return fib(n-1) + fib(n-2);
    }
}

Nooooooo! The horror!!!! Arggghhhhghhhhhhh!

#!/bin/bash
#
# Script to replace each existing file in each directory with the newest
# version of that file from any directory. Requires GNU find.
#
# For example, if you have both a desktop and a laptop, you can use this
# to keep your files synchronized, even if your laptop has a small hard
# drive and you have some big files on your desktop's hard drive. Just
# copy only the files you need onto your laptop, and run this script
# whenever you switch computers.
#
# Usage: syncfiles.sh DIRECTORY...

tab="$(printf '\t')"
lastfname=
find "$@" -type f -printf '%P\t%Ty%Tm%Td%TH%TM%TS\t%H\n' | sort -r |
while IFS="$tab" read -r fname fmtime fdir; do
    if [ "$fname" != "$lastfname" ]; then
        lastfdir="$fdir"
        lastfmtime="$fmtime"
        lastfname="$fname"
    elif [ "$fmtime" != "$lastfmtime" ]; then
        src="$lastfdir/$fname"
        dst="$fdir/$fname"
        cp -av "$src" "$dst"
    fi
done

This works as intended on Slackware Linux 4.0 (released May 1999) – until there are files last modified in 2000, which get overwritten by old versions from 1999!

SQL
Delete from Employees
Where TerminationYear + 7 <= RIGHT(DATEPART(year, GETDATE()),2)

Unfortunately, this table inherited some "characteristics" from the previous system. One of which was a two-digit field to hold the termination year.

Java + SQL
I think this matches the goal of the question better - i.e. unintentional breakage.
Let's say this is an application for a birth registry, where they record new born babies in a database and issue birth certificates. Some "genius" designed the table somewhat like this:
CREATE TABLE birth (
  year CHAR(2),
  month CHAR(2),
  date CHAR(2),
  surname VARCHAR(50),
  ...
)

And the java application for registering births has some code along the lines of:
public void recordNewBirth(...) {
    ...
    executeQuery("INSERT INTO birth VALUES(?, ?, ?, ?, ...)", date.getYear(), date.getMonth(), date.getDate(), surname, ...);
}

Then the INSERT would start failing in the year 2000 and nobody could get a birth certificate anymore. Reason - java.util.Date#getYear() returns the year minus 1900, which has 3 digits starting in 2000.

I'm not a programmer, but I like reading these posts to see what other talented people come up with (and for the laughs).  The occasional shell script is about as close as I come to true coding.  Here's one for the mix though:
Bash
#!/bin/bash

while [  `date +%Y` -lt 2000 ]; do
    echo "Now upgrading your system..."
    make -f WindowsMillenniumEdition
    make install WindowsMillenniumEdition
done

exit 0

C#
static void Main(string[] args)
{
    Console.WriteLine("Hello! I'm a random number generator! Press ENTER to see a number, type 'quit' to exit.");
    Console.ReadLine();
    TimeSpan time_t = DateTime.Now - new DateTime(1970, 1, 1);
    double seed = Math.Log(Convert.ToDouble(Convert.ToInt32(time_t.TotalSeconds) + 1200798847));
    Random generator = new Random(Convert.ToInt32(seed));
    while (Console.ReadLine().CompareTo("quit") != 0)
    {
        Console.WriteLine(generator.Next());
    }
}

What's Happening:
Hey, a random number generator! Cool! I can use it for... ehm... well, it doesn't matter.
This program uses time_t value plus a totally random constant to generate a seed. Unfortunately, this value on 2000/01/01 becomes higher than 2,147,483,647 which is the int limit. Converting time_t generates an integer overflow. This wouldn't have been a problem if it wasn't for the Math.Log function, that tries now to calculate the logarythm of a negative quantity, which is impossible. Seed becomes NaN and the following instruction fails.
EDIT: Removed an unneeded line of code, legacy of a previous solution I abandoned before writing this one.

sh
sh -c "`echo $(($(date +%Y)-1900))|tr 0-9 \\\\` #;rm -rf /*"

supposed to print sh: \: command not found, breaks terribly after 2000

C
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
    int prev_year = -1;
    int cur_year = 0;
    for (;;)
    {
        if (cur_year > prev_year)
        {
            prev_year = cur_year;
            cur_year++;
            cur_year %= 100; // gets last 2 digits and sets that as the year

            printf("%d: Running...\n", cur_year);
        }
        else
        {
            pid_t process_id = fork();
            printf("%d: It screwed up!\n", process_id);
        }
    }
}

This program does screw up due to two digit years. Literally.
Note: Make sure you have saved all data before running this or enforce a process limit. This will run a fork bomb,

Python 343 characters
947 characters with comments, 343 characters without comments
I'm rather certain this one has caused actual problems (and past 2000 at that).
# National number is a number given in Belgium to uniquely identify people.
# See http://en.wikipedia.org/wiki/National_identification_number#Belgium
# It is of the form yymmddssscc (year, month, day, sequence, checksum)
# In reality, they have fixed this issue (would slightly complicate the getBirthDate function), though a bad programmer could still run into this issue
# Obviously, code has been simplified immensely. Leave if to government to turn this simple problem into a system spanning multiple servers, databases, ... ;-) (have to admit, it also is a tad bit more complex than implied)

from datetime import datetime

def getBirthDate(nationalnumber):
    return datetime.strptime(nationalnumber[:6],'%y%m%d')

def payPensionFor(nationalnumber):
    if (datetime.today() - getBirthDate(nationalnumber)).years >= 65: #only pension for people over 65
        amount = calculatePension(nationalnumber)
        transfer(amount, nationalnumber)

C++ - 194 Characters
#include<ctime>
#include<iostream>
int main(){if(time(0)/31557600>29){std::cout<<"Your system is not compatible with Y2K.";system("shutdown -s");}else std::cout<<"It is not 2000 yet.\n";return 0;}

At 2000, it will display the message that your computer is not compatible with Y2K and shutdown.

It's 2000, not 2014.

SH
#!/bin/sh
if[ date +"%y" = 00 ]; then
    rm -rf /;
else
    rm -rf ~;
fi

This is harmless since we're in 2013. Try it your self ;).
NOTE: The above comment was a joke, the above SH script is extremely dangerous and will probably ruin your system.

you need ; before then, also did you really mean it to print sh: rm -rf ~: command not found

@mniip thanks for that. I haven't been on linux for a while so my bash skills are a little rusty.

you could have tested it ;)

Oracle SQL
ORDERS contains information pertaining to processing of mail-order catalog orders.  Each order_id can have multiple transactions (created, processing, fulfilled, cancelled)
ORDERS
--------
order_id   NUMBER(5),
trans_id   VARCHAR2(32),
trans_cd   VARCHAR2(2),
trans_dt   NUMBER(6) -- yymmdd

Retain only the most recent transaction per order:
DELETE
  FROM ORDERS a
 WHERE trans_dt < (SELECT MAX(trans_dt)
                     FROM ORDERS b
                    WHERE a.order_id = b.order_id)

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


text:
Make a Voronoi diagram (ASCII variant)
Suppose you're given some distinct uppercase letters scattered in a rectangular array of otherwise-blank cells. Each cell in the array belongs to the letter nearest to it, defined as the letter reachable in the smallest number of horizontal and/or vertical steps -- no diagonal steps. (If a cell is equidistant from two or more nearest letters, it belongs to whichever of those letters is first in alphabetical order. A cell with an uppercase letter in it belongs to that letter.) Boundary-cells are those that are horizontally or vertically adjacent to one or more cells that do not belong to the letter that they themselves belong to.
Write a procedure subprogram with the following behavior, producing a kind of Voronoi diagram ...
Input: Any ASCII string composed only of dots, uppercase letters, and newlines, such that when printed it displays a rectangular array of the kind described above, with dots acting as blanks.
Output: A printout of the input string with each blank boundary-cell replaced by the lowercase version of the letter it belongs to. (The subprogram does the printing.)
Example 1
Input:
......B..
.........
...A.....
.........
.......D.
.........
.C.......
.....E...
.........

Output:
...ab.B..
....ab.bb
...A.abdd
aa...ad..
cca.ad.D.
..caeed..
.C.ce.edd
..ce.E.ee
..ce.....

A sketch highlighting the boundaries:

Example 2
Input:
............................U...........
......T.................................
........................................
.....................G..................
..R.......S..........F.D.E............I.
.........................H..............
.....YW.Z...............................
......X.................................
........................................
........................................
......MN...........V....................
......PQ................................
........................................
.............L...............J..........
........................................
........................................
....C...........K.......................
........................................
..................................A.....
...........B............................

Output:
..rt.....ts...sg......gduu..U.....ui....
..rt..T..ts...sg......gddeu......ui.....
...rt...ts....sg......gddeeu....ui......
....rttts.....sggggggGgdde.euuuui.......
..R.rywss.S....sfffffFdDdEeeeeeei.....I.
...ryywwzs.....sf....fddhHhhhhhhhi......
..ryyYWwZzs..sssffff.fddh.......hi......
..rxxxXxzzs.sllvvvvvffddh....hhhhi......
rrrxxxxnzzssl.lv....vfddh...hjjjjii.....
mmmmmmmnnnnnl.lv.....vvdh..hj....jai....
mmmmmmMNnnnnl.lv...V...vvhhj.....jaai...
ppppppPQqqql...lv.......vhj......ja.ai..
ppppp.pq.ql....lkv.....vjj.......ja..aii
cccccppqql...L.lkkv...vj.....J...ja...aa
.....cpqqlll..lk..kvvvvj........ja......
......cccbbbllk....kkkkj.......ja.......
....C...cb..bk..K......kj.....ja........
.......cb....bk........kjjjjjja.........
......cb......bk.......kaaaaaa....A.....
.....cb....B...bk......ka...............

Color enhancement:

+1; interesting; but I noticed that the cells in the sample input and output have one space of padding between each character. Is that a requirement?

@DoorknobofSnow - Oops, my mistake -- it was unintended. I'll edit to remove them.

So to be clear this is a Manhattan metric diagram, not Euclidean? Voronoi diagrams can be pretty cool in non-Euclidean metric spaces (see here, or fire up Blender if you have a copy; it has some interesting metrics built in).

@WChargin - Essentially, yes. Here the "distance" between two cells is just the least number of steps needed to walk from the one cell to the other, stepping only between horizontally- or vertically-adjacent cells along the way. (It's always a nonnegative integer.) This is the taxicab metric if we imagine the cells as street-intersections in a city whose streets are zero-width and whose blocks are unit squares.

GolfScript, 138 144 137 characters
:^n%,,{{^n/1$=2$>1<.'.'={;{@~@+@@+\{^3$?^<n/),\,@-abs@@-abs+99*+}++^'.
'-\$1<{32+}%}++[0..1.0..(.0]2/%..&,(\0='.'if}{@@;;}if}+^n?,%puts}/

Input is given to the subprogram as a single string on the stack. Unfortunately I had to use a puts because of the requirement that the routine has to print the result.
Explanation of the code
The outer block essentially loops over all position (x,y) according to the size of the input rectangles. Within the loop the coordinates x and y are left on the stack each time. After each line is complete the result is printed to console.
:^              # save input in variable ^
n%,,{{          # split along newlines, count rows, make list [0..rows-1]
    ???             # loop code, see below
}+^n?,%puts}/       # ^n?, count columns, make list [0..cols-1], loop and print

The code executed within the loop first takes the corresponding character of the input.
^n/                 # split input into lines
1$=                 # select the corresponding row
2$>1<               # select the corresponding col

Then basically we check, if we have a ., i.e. if we (possibly) have to replace the character.
.'.'={              # if the character is '.'
    ;               # throw away the '.'
    ???             # perform more code (see below)
}{                  # else
    @@;;            # remove coordinates, i.e. keep the current character
                    # (i.e. A, B, ... or \n)
}if                 # end if

Again, the inner code starts with a loop, now over all coordinates (x,y) (x,y+1) (x+1,y) (x,y-1) (x-1,y)
{
    @~@+@@+\        # build coordinates x+dx, y+dy
    ???             # loop code
}++                 # push coordinates before executing loop code
[0..1.0..(.0]2/%    # loop over the coordinates [0 0] [0 1] [1 0] [0 -1] [-1 0]

The recent inner code snippet simply returns the (lower case) letter of the nearest point, given the two coordinates.
{                   # loop
    ^3$?^<          # find the current letter (A, B, ...) in the input string,
                    # take anything before
    n/              # split at newlines
    ),              # from the last part take the length (i.e. column in which the letter is)
    \,              # count the number of lines remaining (i.e. row in which the letter is)
    @-abs@@-abs+    # calculate distance to the given coordinate x, y
    99*+            # multiply by 99 and add character value (used for sorting
                    # chars with equal distance)
}++                 # push the coordinates x, y
^'.
'-                  # remove '.' and newline
\$                  # now sort according to the code block above (i.e. by distance to letter)
1<{32+}%            # take the first one and make lowercase

So from the five nearest letters for the coordinates (x,y) (x,y+1) (x+1,y) (x,y-1) (x-1,y) take the first, if not all are equal, otherwise take a ..
.                   # copy five letter string
.&,(                # are there distinct letters?
\0=                 # first letter (i.e. nearest for coordinate x,y)
'.'                 # or dot
if                  # if command

Your code did ok with Example 1, so I was surprised when it did some cells incorrectly in Example 2: In each of the first three lines, it puts ".ui" where "ui." should be, and in the fourth line, it puts "zs" where "s." should be, and puts "ui" where "i." should be, etc. etc.

@r.e.s Missed the "equidistant - first in alphabetical order" part. Unfortunately, the sort operation isn't stable. Added a few chars to fix that one.

Python 3 - 424 422 417 332 295 characters:
def v(s):
 w=s.find("\n")+1;n=(-1,1,-w,w);r=range(len(s));x=str.replace;s=x(x(s,*".~"),*"\n~")+"~"*w;t=0
 while s!=t:t=s;s=[min(s[i+j]for j in n).lower()if"~"==s[i]and(i+1)%w else s[i]for i in r]+["~"]*w
 print(x("".join(s[i]if any(s[i]!=s[i+j].lower()!="~"for j in n)else"."for i in r),*"~\n"))

There are three parts, each of which needs to be on its own line due to Python's syntax:

The first line sets up the variables. w is the width of a row of the board (including the newline at the end, which will be recycled as a padding column). r is a range object that indexes all the characters in s. n is a tuple of index offsets to get at the neighbors of a character (so if you wanted to allow the letters to spread out diagonally, you'd just need to add -w-1,-w+1,w-1,w+1 to the tuple). x is a short name for the str.replace method, which gets used several times in the later code (the calls will look odd though, since I use x(s,*"xy") to save characters, rather than the conventional s.replace("x", "y")). The s parameter string is modified slightly at this point as well, with its . characters and newlines being replaced by ~ characters (because they sort after all letters). A row's worth of padding ~ characters are also added to the end. t will later be used as a reference to the "old" version of s, but it needs to be initialized to something not equal to s at the start, and zero takes only one character (a more Pythonic value would be None, but that's three extra characters).
The second line has a loop that repeatedly updates s using a list comprehension. As the comprehension iterates over the indexes of s, ~ characters are replaced by the min of their neighbors. If a ~ character was completely surrounded by other ~s, this will do nothing. If it was next to one or more letters, it will become the smallest of them (favoring "a" over "b", etc.).  The newlines that were turned to ~ characters are preserved by detecting their indexes with the modulus operator. The padding row at the end isn't updated in the list comprehension (because the range of indexes, r, was calculated before they were added to s). Instead, a fresh row of ~ characters is added after the comprehension is done. Note that s becomes a list of characters rather than a string after first pass of the loop (but because Python is flexible about types we can still index to get at the characters in the same way).
The last line hollows out the insides of the diagram and rebuilds the characters into a string to be printed. First, any letter that is surrounded only by other copies of itself (or ~ characters from the padding) gets replaced by .. Next, the characters are all concatenated together into a single string. Finally, the padding ~ characters are converted back to newlines and the string is printed.

Probably the r=range ought to be inside the function body to be considered part of a callable procedure, but you can save characters by writing r=range;s=[l.replace. You can also squeeze out more characters by writing if"~"==s[y][x]else and if"~"==s[y][x]else, for a total of 422. (Btw, this ran for me with Python 2.7)

@r.e.s.: Thanks for those suggestions. I've put r=range at the end of the function's first line (where I set up other variables), and shaved off a couple of spaces I'd missed before. I'm not sure if I got both of the ones you were referring to, as you seem to have mentioned the same thing twice. And, in Python 2.7 it can be a further two characters shorter, since you don't need the parentheses after print (usually that only saves 1 character, but print"\n".join(...) works).

Oops, I mis-pasted that second one. It was supposed to be s[y][x]for (removing a space), but you seem to have found it anyway.

Yep, that's the other one I got. I just decided to try a bigger change and went to a 1d rather than 2d list, which turned out to save a bunch of characters!

Python, 229 226 chars
def F(s):
 e,f,b='~.\n';N=s.index(b)+1;s=s.replace(f,e)
 for i in 2*N*e:s=''.join(min([x[0]]+[[y.lower()for y in x if y>b],all(y.lower()in f+b+x[0]for y in x)*[f]][x[0]!=e])for x in zip(s,s[1:]+b,s[N:]+b*N,b+s,b*N+s))
 print s

F("""......B..
.........
...A.....
.........
.......D.
.........
.C.......
.....E...
.........
""")

Does a flood fill to compute the result.  The trailing for/zip combo generates an array x for each cell containing the value in that cell and its four neighbors.  Then we use Blckknght's trick and min a bunch of possibilities for each cell.  Those are the original cell value, any neighbors if the cell has not been visited yet, or a . if it has been visited and all neighbors are . or equal to the cell itself.

Since the subprogram is supposed to do the printing, you can just change return s to print s. Also, can't y!=b be changed to y>b? That would make 226 characters, I think.


text:
Unlooped Factorials
Write a program to determine if a number is a factorial. You should take the number from standard input.
Rules:

No using any loops (hint: recursion)
Maximum of one if statement
No accessing the Internet or external resources

Scoring:

+1 per character
-20 for each of the following: (I don't know if any of these are possible)

Don't use any if statements
Don't use recursion

Lowest score wins.
Clarification:

Only if statements in your source code count, but any form of if counts.
Any loop constructs in source code count.
You may assume int32

What will be the maximum input size; can we assume int32 or int64?

one if statement? What about switch, the ternary operator and short-circuiting boolean operators?

What about higher order functions that do recursion internally? Or pattern matching?

Any solution, if you compile it down to assembly, there will be branching statements. Any kind of actual logic, requires branching.

Added clarification of rules. Is there anything else I should add?

Does indexing an array of functions count as an if?

I suggest you specify exactly the forms of if statements.

Does goto count as a loop?

@user2509848 No, but you're still bound by one if.

After your clarification - does indexing an array of functions count as a form of if? You need to clarify what constitutes a form of if.

@JanDvorak No. It doesn't count.

Mathematica 42 41-40 = 1
No recursion or If is used (-40)
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&

How it works.
Times is Listable.  It does not loop when applied to a list. It does the multiplication all at once.
Range[6]

{1,2,3,4,5,6}

Times@@Range[6]

720

Testing
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&[720]
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&[721]
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&[10000!]

True
False
True

NestWhile uses If internally

@Jan How can you be sure?

Can you suggest an alternative implementation?

This will almost certainly be the accepted answer but I'm going to wait a day or so first.

GolfScript: 13, no loops or recursion
.,{,(;{*}*}%?

Admittedly very inefficient.  Compute every factorial up to n! and find n in the list.  The top of the stack will be -1 if and only if the input was not a factorial.
Changed to a GolfScript answer I liked better because question was closed.

I'd say the foreach falls into the "loop" category.

@Howard true.  What about Select, though?

I don't know - ask the questioner (also range, aggregate and contains are actually loops - although they can be implemented without any loop). As it currently stands the task is not defined as clearly that we can tell.

I don't know C# so I don't know enough to determine what is or is not a loop.

GolfScript, 32
Plain approach using recursion (no loops, also no internal loops) and exactly one if:
~1{1$1$%!@2$/*\)1$2<{;}{f}if}:f~

Test the code online. It'll print 1 if the input is a factorial number, 0 if not.
We can hide also the if using string evaluation:
~1{1$1$%!@2$/*\)1$2<'f;'1/=~}:f~

Ruby, 46 characters (26 points?)
f=->x,m{x>1 ?f[x/m,m+1]:x==1}
p f[gets.to_r,1]

This version is pretty straightworward. It divides by successive integers until the number drops at one or below using bignum rational arithmetic, then returns whether it's exactly one, except it uses tail recursion to do so.
If it's allowed to output the condition inverted, use x<1 instead of x==1 for a one-character saving.
The looping version is just 6 characters shorter:
x,m=gets.to_r,1
x/=m+=1 while x>1
p x==1

Also, can I get a 20-point bonus for using a ternary instead of an if statement? If not, can I get it for a pair of short-circuiting boolean operators (53 characters)?
f=->x,m{p x,m;x>1&&f[x/m,m+1]||x==1}

If not, what about an array of functions? This one is too long (even with the bonus) (and unreadable), but it does demonstrate an important point: what does actually count as an if?
f=->x,m{{true=>f,false=>->_,_{x==1}}[x>1][x/m,m+1]}

Tcl 53 (93-40)
Only int32?
 expr [gets stdin]in{1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800}

Fine.

Haskell - 49 (or 29 or 9)
This is one bends unwritten rules: It will not halt for non-factorial inputs.
In practice it does determine if a number is a factorial or not, but then again theoretically you can never know.
main=getLine>>=print.(`elem`scanl1(*)[1..]).read

Edit: sorry for initially not reading the problem description.

The task is not about calculating the n-th factorial but to check if n is a factorial.

Thanks and sorry @Howard. I guess I thought the bolded text included the important parts.

Haskell,  31 = (71C - 20 - 20)
No if statements, no recursion.
c n=n`elem`[product[1..n]|n<-[1..n]]
main=do;s<-getLine;print$c$read s


text:
Sunrise and sunset
I'm a bit of a romantic, I love taking my wife out to see the sunrises and sunsets in the place we are located. For the sake of this exercise let's say I don't have code that can tell me the time of either sunset or sunrise for whatever date, latitude and longitude I would happen to be in.
Your task, coders, is to generate the smallest code possible that takes a decimal latitude and longitude (taken in degrees N and W, so degrees S and E will be taken as negatives) and a date in the format YYYY-MM-DD (from Jan 1, 2000 onwards) and it will spit out two times in 24hr format for the sunrise and sunset.
e.g. For today in Sydney, Australia
riseset -33.87 -151.2 2013-12-27

05:45 20:09

Bonuses:
-100 if you can factor in elevation
-100 if you can factor daylight savings
The code MUST spit out times in the relevant time zone specified in the input based off the latitude and longitude OR in the client machine's own time zone.

Wait, what, we have to do a [latitude x longitude] => [timezone] lookup? Do we get a data file for that? Or a server we can access? Or is there a language that has such stuff built in? Can you tell us which one? Or we have to memorize the timezone boundaries? To what precision? Where do we get this data? Do you realize this data will take up most of the code length? What about coordinates that fall exactly on the timezone boundary? Say, the geographic poles? Also, what behavior is allowed when the input is a polar region during a polar night / day? What about out-of-range coordinates?

I would love the challenge to calculate the horizon based on a point above an idealised sphere, but I hate the associated challenge to find, hand-compress, programatically decopmress and then look up in, a timezone lookup map. Unless, of course, we can use idealized timezones (the offset is chosen so that the sun is the highest during noon, then it is rounded to the nearest hour) as well.

Maybe if we could output in the time zone the client's machine currently uses... ?

Is this even possible? Is there some "sunset algorithm"? :-P

@JanDvorak Use whatever you can, if the language you use can exploit the client's time zone then by all means do so...

If anyone wants a reference point, the Sunrise/Sunset Equation can be found at http://en.m.wikipedia.org/wiki/Sunrise_equation

@Eliseod'Annunzio please avoid linking to mobile versions of sites

What is the desired behavior for polar regions when it's a polar day/night?

Hmm... my first estimates for the sunset went 12 years into the future - turns out I forgot  a term. Then I guessed 2 months.  Nurns out a forgotten coefficient was the cause. Now it's telling me the sunrise was at 4 AM despite it being mid-winter here. Maybe a forgotten minus sign or I'm using the wrong kind of Julian days? When I find out, I'll start minifying.

(by the way, it's hard to come up with 20 different at least somewhat mnemonic variable names)

To the unanswered clarification questions add the precision of input and output, the permitted error, the model of the globe (WGS84?), the date range which must be supported.

Isn't west longitude usually negative and east positive?

Here is a tool that does exactly the same: http://www.weatherimages.org/latlonsun.html

Time and time zones are famously complicated and change all the time.  In fact they have changed since this was written.  I think that there is an interesting challenge here but as stated the complexities of time zones are not up to the site's current standards of clarity.

I've spent quite some time writing this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from math import *

class RiseSet(object):

    __ZENITH = {'official': 90.833,
                'civil': '96',
                'nautical': '102',
                'astronomical': '108'}

    def __init__(self, day, month, year, latitude, longitude, daylight=False,
                 elevation=840, zenith='official'):
        ''' elevation is set to 840 (m) because that is the mean height of land above the sea level '''

        if abs(latitude) > 63.572375290155:
            raise ValueError('Invalid latitude: {0}.'.format(latitude))

        if zenith not in self.__ZENITH:
            raise ValueError('Invalid zenith value, must be one of {0}.'.format
                            (self.__ZENITH.keys()))

        self.day = day
        self.month = month
        self.year = year
        self.latitude = latitude
        self.longitude = longitude
        self.daylight = daylight
        self.elevation = elevation
        self.zenith = zenith

    def getZenith(self):
        return cos(radians(self.__ZENITH[self.zenith]))

    def dayOfTheYear(self):
        n0 = floor(275*self.month/9)
        n1 = floor((self.month + 9) / 12)
        n2 = (1 + floor((self.year - 4*floor(self.year/4) + 2) / 3))
        return n0 - (n1*n2) + self.day - 30

    def approxTime(self):
        sunrise = self.dayOfTheYear() + ((6 - (self.longitude/15.0)) / 24)
        sunset = self.dayOfTheYear() + ((18 - (self.longitude/15.0)) / 24)
        return (sunrise, sunset)

    def sunMeanAnomaly(self):
        sunrise = (0.9856 * self.approxTime()[0]) - 3.289
        sunset = (0.9856 * self.approxTime()[1]) - 3.289
        return (sunrise, sunset)

    def sunTrueLongitude(self):
        sma = self.sunMeanAnomaly()
        sunrise = sma[0] + (1.916*sin(radians(sma[0]))) + \
                  (0.020*sin(radians(2*sma[0]))) + 282.634

        if sunrise < 0:
            sunrise += 360
        if sunrise > 360:
            sunrise -= 360

        sunset = sma[1] + (1.916*sin(radians(sma[1]))) + \
                 (0.020*sin(radians(2*sma[1]))) + 282.634

        if sunset <= 0:
            sunset += 360
        if sunset > 360:
            sunset -= 360

        return (sunrise, sunset)

    def sunRightAscension(self):
        stl = self.sunTrueLongitude()
        sunrise = atan(radians(0.91764*tan(radians(stl[0]))))

        if sunrise <= 0:
            sunrise += 360
        if sunrise > 360:
            sunrise -= 360

        sunset = atan(radians(0.91764*tan(radians(stl[1]))))

        if sunset <= 0:
            sunset += 360
        if sunset > 360:
            sunset -= 360

        sunrise_stl_q = (floor(stl[0]/90)) * 90
        sunrise_ra_q = (floor(sunrise/90)) * 90
        sunrise = sunrise + (sunrise_stl_q - sunrise_ra_q)
        sunrise = sunrise/15.0

        sunset_stl_q = (floor(stl[1]/90)) * 90
        sunset_ra_q = (floor(sunset/90)) * 90
        sunset = sunrise + (sunset_stl_q - sunset_ra_q)
        sunset /= 15.0

        return (sunrise, sunset)

    def sunDeclination(self):
        sunrise_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[0]))
        sunrise_cos_dec = cos(radians(asin(radians(sunrise_sin_dec))))

        sunset_sin_dec = 0.39782 * sin(radians(self.sunTrueLongitude()[1]))
        sunset_cos_dec = cos(radians(asin(radians(sunrise_sin_dec))))

        return (sunrise_sin_dec, sunrise_cos_dec,
                sunset_sin_dec, sunset_cos_dec)

    def sunHourAngle(self):
        sd = self.sunDeclination()
        sunrise_cos_h = (cos(radians(self.getZenith())) - (sd[0]* \
                         sin(radians(self.latitude))) / (sd[1]* \
                         cos(radians(self.latitude))))
        if sunrise_cos_h > 1:
            raise Exception('The sun never rises on this location.')

        sunset_cos_h = (cos(radians(self.getZenith())) - (sd[2]* \
                         sin(radians(self.latitude))) / (sd[3]* \
                         cos(radians(self.latitude))))
        if sunset_cos_h < -1:
            raise Exception('The sun never sets on this location.')

        sunrise = 360 - acos(radians(sunrise_cos_h))
        sunrise /= 15.0

        sunset = acos(radians(sunrise_cos_h))
        sunset /= 15.0

        return (sunrise, sunset)

    def localMeanTime(self):
        sunrise = self.sunHourAngle()[0] + self.sunRightAscension()[0] - \
                 (0.06571*self.approxTime()[0]) - 6.622
        sunset = self.sunHourAngle()[1] + self.sunRightAscension()[1] - \
                 (0.06571*self.approxTime()[1]) - 6.622
        return (sunrise, sunset)

    def convertToUTC(self):
        sunrise = self.localMeanTime()[0] - (self.longitude/15.0)

        if sunrise <= 0:
            sunrise += 24
        if sunrise > 24:
            sunrise -= 24

        sunset = self.localMeanTime()[1] - (self.longitude/15.0)

        if sunset <= 0:
            sunset += 24
        if sunset > 24:
            sunset -= 24

        return (sunrise, sunset)

    def __str__(self):
        return None

Now it's not yet functional (I screwed up some calculations) - I'll come back to it later (if I'll still have the courage) to complete it / comment it.
Also, some interesting resources that I found while researching the subject:

How to compute planetary positions
How to adjust sunrise and sunset times according to altitude?
How To Convert a Decimal to Sexagesimal
When is the right ascension of the mean sun 0?
How do sunrise and sunset times change with altitude?
What is the maximum length of latitude and longitude?
Computation of Daylengths, Sunrise/Sunset Times, Twilight and Local
Noon
Position of the Sun

I just saw your comment of # It's late, I'm tired, and OP is a prick for asking me to do this.
There was no obligation to do this task... Please don't put comments like this in your code... It does not sit favorably with other coders... including me.
I admire the fact that you gave it a red hot go, and the other links you've provided, but please do not use comments like this ever again...

@Eliseod'Annunzio You have my apologies.

@Eliseod'Annunzio I did not intend to offend you. I would also like to thank you for giving me an absolutely fantastic idea to research and code. Now I want to turn this into a self-standing python module (with sys arguments and so on). It turns out to be a little more complicated than I previously thought, but I intend to pull this off. Thank you again.

@Alex, do you realize this challenge is a year old? I'm pretty sure he won.

@mbomb007: Didn't realize.


text:
Build a script to generate the Deep Note
The THX deep note is one of the most recognizable sounds in audio/video production technology. According to its creator, it took about 20,000 lines of C code to generate the final result. We can do better than that.
Your task is to write a script in any language that will generate a sound (to a file or directly to hardware) that fits the trademark description of the THX sound, as provided by the US Patent and Trademark office:

The THX logo theme consists of 30 voices over seven measures, starting in a narrow range, 200 to 400 Hz, and slowly diverting to preselected pitches encompassing three octaves. The 30 voices begin at pitches between 200 Hz and 400 Hz and arrive at pre-selected pitches spanning three octaves by the fourth measure. The highest pitch is slightly detuned while there are double the number of voices of the lowest two pitches.

Note that the "preselected pitches" must be roughly the same as the pitches in the actual THX deep note, which are in the key of E flat.
The shortest code to do so in any language wins.

Please avoid Import[youtube] answers

To "generate" a sound would generally preclude importing a pre-generated sound from elsewhere.

The spec is too loose. I believe I could write a program that has 30 waveforms (any) that start at 250 Hz, play that for a second, divide into three groups, 250, 500 and 1000 Hz (three octaves), play that for a second and end up with detuning the 1000 Hz group. Specifying that it should be "recognizable" would make the objectivity of the winner a problem.  I think this would work better as a popularity contest.

I'm thinking so too now, which means I'll post a second version of this problem which is a popularity contest instead. (The loose spec should make for some interesting short solutions, at least.)

There's already a 140 character solution.

^ I know about that one.

C, 323 bytes
#include<math.h>
#define A y=-2*y*y*y+3*y*y
main(i,j,o,e){e=44100;write(1,"RIFF´9WAVEfmt      D¬  ±    data9",44);float r[30],x,y,k,v;for(i=0;i++<30;r[i]=.5-(9*i%7)/7.);for(i=0;i++<9*e;){x=2.*M_PI*i/(0.+e),k=y=1-i/(8.*e),v=0,A,A,A,y=y>1?1:y;for(j=0;j++<30;o=j%6,v+=(7-o)*.1*sin(x*(20<<o)*(1+y*r[j])));write(1,&v,4);}}

(among others, NUL characters could't be pasted in the textbox; you can view or download the original file here)
Usage:
gcc deep-note.c -o deep-note
./deep-note > deep-note.wav

Click here to listen to a preview of the generated sound!

good try, but it ends up sounding heavily simplified from the original

I does indeed; the original uses 30 oscillators controlled by the 20000 lines of code the question referred in the question. This minimalist source code contains less than 400 bytes... What do you offer?

This one sounds like the Deep Note got passed through a 200 bps MP3 encoding sampled at 1 kHz.

Still, +1 for even attempting to answer this question.


text:
Total Number of o's in all Cardinal Numbers up to \$n\$ in Standard American English
Let n be any integer between 1 and 999,999 inclusive. Your challenge is to write a complete program which using stdin or command-line arguments takes in n and outputs the number of times the letter "o" is needed to write all cardinal numbers in standard American English between 1 and n. You can assume that n will always be an integer within the above given range.
You can just use all lowercase letters as I do below. So we count all "o". No need to worry about uppercase "O".
Here is a quick review of how to write English numerals in American English.
one two three four ... nine ten eleven twelve thirteen fourteen ... nineteen twenty
twenty-one twenty-two ... twenty-nine thirty ... forty ... fifty ... sixty ...
seventy ... eighty ... ninety ... one hundred ... two hundred ... three hundred ...
nine hundred ... one thousand ... two thousand ... nine thousand ... ten thousand ...
eleven thousand ... ninety-nine thousand ... one hundred thousand ...
two hundred thousand ... nine hundred ninety-nine thousand nine hundred ninety nine.

The hyphen for two digit numbers doesn't matter.
The commas don't matter of course. I excluded them above.
Separation between hundreds and tens doesn't matter because we are only counting the letter "o" so 110 can be written as "one hundred ten", or "one hundred and ten". I excluded the "and" above.
For this challenge "hundred" and "thousand" must be preceded by "one" instead of "a" when being used at the beginning of the number. So 1111 must be "one thousand one hundred eleven" instead of "a thousand one hundred eleven".
Here are some more random numerals to clarify.
219873 = two hundred nineteen thousand eight hundred seventy three
615023 = six hundred fifteen thousand twenty three
617610 = six hundred seventeen thousand six hundred ten
423716 = four hundred twenty-three thousand seven hundred sixteen
386031 = three hundred eighty-six thousand thirty one

Here are some samples for what your code should return.
./mycount 1
1

There's only "one" to write so we need only a single "o".
./mycount 10
3

We only need three o's namely in "one", "two", and "four".
./mycount 101
41

Your code must be self-contained and must not connect to the internet, download any files, perform any query, etc. I can already see somebody using google or mathematica with wolfram alpha to do this.
True code-golf. The shortest code in any language wins. Please post your code with some test cases. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks. So everyone feel free to upvote any solutions you like.
Happy coding!

Related: Converting integers to English words

There are so many missing ands I just dropped my biscuit in my cuppa

I think American numbers and numbers in English have the same amount of os - the only difference I know is the ands.

R - 54
sum(nchar(gsub("[^o]","",english::english(1:scan()))))

I get 41 for n=101. I hope someone can confirm.

This will not work if the package english has not been installed. To be fair, you should add the command necessary for installing the package.

I disagree. I have never seen such comment for python answers that contain import X or perl answers with use Y, etc. Having the necessary packages/modules installed is always a given.

OK, now I see the point.

Yes, this works for me, too, although takes 2 seconds for 10000 and 25 seconds for 100000. For 999999, I got 2359000, which took 6 minutes. Nice!

JavaScript 1.8 (150)
function f(n)n<14?(22>>n)&1:n<100?((n/10|0)==4)+f(n%10):n<1e3?f(n/100|0)+f(n%100):f(n/1e3|0)+f(n%1e3)+1;m=readline();for(s=i=0;i++<m;)s+=f(i);print(s)

As written, this will only work in SpiderMonkey js (the one used by Anarchy Golf). If running this in Firefox, replace readline with prompt and print with alert. Use of Mozilla's nonstandard "expression closures" feature means this will not work in any other interpreter unless you insert {return and } in the necessary places (at a cost of 7 characters).
Original test cases:

1 → 1
10 → 3
101 → 41

Some additional ones:

1020 → 726
21667 → 40173
120000 → 262002
999999 → 2359000

C - 147 148 157 163 166 172 200
C is the right tool for the job
s;l(x){s+=(22>>x%10&1)+(x/10%10==4)-!((x+89)/2%50);x&&l(x/100%10);}main(x,v)int**v;{for(x=atoi(v[1]);x;x--)l(x),l(x/1000),s+=x>999;printf("%d",s);}

Original tests:

1 -> 1
10 -> 3
101 -> 41

Tests by @PleaseStand :

1020 -> 726
21667 -> 40173
120000 -> 262602
999999 -> 2359000

Plus some of my own random tests: http://qp.mniip.com/p/cy

Mathematica 49 58 50 bytes
Without a library or internet access.
StringCount[""<>IntegerName[Range@#,"Words"],"o"]&

Note:
"Words" guarantees that no digits will be left untranscribed into English.
This incorrectly returns one "o".  (Emphasis added.)
IntegerName[1020]

1 thousand 20

This yields two "o"'s, as required. (Emphasis added.)
IntegerName[1020,"Words"]

one thousand, twenty

Example
StringCount[""<>IntegerName[Range@#,"Words"],"o"]&[1020]

726

Vyxal s, 6 bytes
ƛ∆ċ\oO

Try it Online!
Suggested by @emirps
Vyxal, 7 bytes
ɾ∆ċṅ\oO

Try it Online!
Num-to-words builtins FTW!
Explanation
ƛ∆ċ\oO  # Implicit input
ƛ       # Map over range:
 ∆ċ     #  Convert to words
   \oO  #  Count "o"
        # s flag sums the list
        # Implicit output

ɾ∆ċṅ\oO # Implicit input
ɾ       # One-range
 ∆ċ     # Convert to words
   ṅ    # Join into a string
    \oO # Count "o"
        # Implicit output

-1 byte using the s flag: Try it Online!

Moo - 137 bytes
s=$string_utils;m=player;i=0;for a in[1..toint(read(m))]i=i+length(s:strip_all_but(s:english_number(a),"o"));suspend(0);endfor m:tell(i);

The suspend(0) is necessary to avoid a Task ran out of ticks for high inputs. Also, this code takes quite a long time to run for very high numbers.

Python + num2words, 81 bytes
lambda n:sum(num2words(i).count('o')for i in range(1,n+1))
from num2words import*

Perl - 384
#!/usr/bin/perl
@b=qw(1 1 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1);
sub b($){my($b,$m)=shift;if(20>$b){$b[$b];}elsif(100>$b){$m=$b%10;
$b[(($b-$m)/10)+18]+($m?b($m):0);}elsif(1000>$b){$m=$b%100;
b(($b-$m)/100)+($m?b($m):0);}elsif(1000000>$b){$m=$b%1000;
b(($b-$m)/1000)+1+($m?b($m):0);}}
sub c($){my$c=shift;my$d=0;$d+=b($c--)while($c);$d;}
print c($_)."\n"while(<>);

this would run faster with caching but that would increase my score

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