Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}

60 characters exactly!

Thanks so much for your wisdom!

share

locked by ChrisF May 13 '13 at 19:46

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as not constructive by gnat, MichaelT, GlenH7, ChrisF May 13 '13 at 19:46

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

22  
Why was brainf**k censored? Can't we be adults and not tell everyone what they can and cannot read? In this context brainf**k is not an obscenity. –  ChaosPandion Nov 6 '10 at 21:28
2  
I suspect this question will be closed. Try improve it to be more constructive. See: blog.stackoverflow.com/2010/09/good-subjective-bad-subjective –  bigown Nov 6 '10 at 23:41
8  
@bigown: This is a good subjective one and is constructive. It's no different than asking for famous quotes. In fact, it's better, because it's asking for famous code/equation "quotes." :-) –  Macneil Nov 7 '10 at 0:30
3  
@bigown: honestly, I can't really see how this question could be any more constructive. Not to doubt you or so, but very genuily asked, could you suggest an improvement to @BeachRunnerJoe? I actually very much enjoyed the answers and learned a lot from them. I'd love to see this question reopen. –  Joris Meys Nov 7 '10 at 20:31

35 Answers 35

The classic C string copy routine is known by fewer and fewer people theses days:

while (*d++ = *s++);
share
3  
yes, very famous...to the veterans! –  BeachRunnerJoe Nov 6 '10 at 19:27
13  
While I understand it has "historical" value it's terrible terrible code, so the fact that it's falling in disuse is a good thing =) –  Andreas Bonini Nov 6 '10 at 19:34
9  
A C veteran would recognize the pattern immediately. It's idiomatic C. –  Barry Brown Nov 6 '10 at 19:47
6  
Always thought this was incredibly cool. –  Maulrus Nov 7 '10 at 1:00
5  
I must say, I agree with @Kop. In just a few chars, it shows signifficant flaws of its standard lib and its semantics. One of the most absurd things is strings being 0-terminated instead of length-prefixed (which is safer and makes determining the length of a string O(1)). The second thing is that C doesn't have actual boolean values (which fixes the if (alarm = red) launchNukes();-trap). Dijkstra would consider this code more than harmful. I do agree it is imperative for a C programmer to at least understand this code, but I think it's more important for him to know how to do it better. –  back2dos Nov 7 '10 at 13:12

not one line, but I present The World's Last C Bug:

    status = GetRadarInfo();
    if (status = 1)
      LaunchNukes();
share
2  
That's one of those "Oh sh*t!" errors. –  the Tin Man Nov 11 '10 at 1:49
3  
it's LaunchNukes(); –  hasenj Nov 12 '10 at 21:24
1  
if that has been written as: if(GetRadarInfo()=1){...}, we wouldn't get this bug because it doesn't compile. So don't always introduce intermediate variable. –  tactoth Jan 27 '11 at 2:45

I see Conway's Game of Life in APL floating around a lot:

An extra bonus is that this will make sure you're handling unicode correctly.

share
2  
ha! that's the first thing I thought of when I saw your code, nice! –  BeachRunnerJoe Nov 6 '10 at 19:24
4  
Explanation: youtube.com/watch?v=a9xAKttWgP4 –  J.F. Sebastian Nov 7 '10 at 21:28
15  
And I thought Perl looked like line noise. –  the Tin Man Nov 8 '10 at 20:17
1  
@Greg, just wait, APL uses more than the roman and greek alphabets because there weren't enough letters and symbols already; backspace (more properly called "overstrike") is also used because some characters need to be typed on top of other characters. One such was a divide symbol on top of a square, which represented matrix inversion (if unary operator, or multiplication by the inverted matrix if it was used as a binary operator). –  Tangurena Nov 10 '10 at 21:32

A modified version of a famous Perl one-liner:

/^.?$|^(..+?)\1+$/

This regular expression matches strings whose length is prime.

The original version is:

/^1?$|^(11+?)\1+$/

which matches strings consisting of a prime number of 1s.

share

Quicksort:

qsort []     = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

If the list is empty, the sorted result is the empty list.

If the list starts with the element x, and the rest of the list is xs, then the sorted result is list consisting of the sorted list consisting of all elements in xs less than x concatenated with the element x concatenated with the sorted list of all elements in xs larger than x.

(or in other words - divide in two piles, all less than x and all larger than x, sort them both and create a list with the less-than pile, the element x, and the larger-than pile).

Beats the understandability of the C version quite easily.

share
1  
This is Standard ML? Or Haskell? –  Barry Brown Nov 6 '10 at 21:02
3  
Haskell. I like the mindset of the language. –  user1249 Nov 7 '10 at 1:00
1  
Is there a version of this that uses a random pivot instead of the head of the list? That would make it closer to C.A.R. Hoare's original. –  Macneil Nov 11 '10 at 2:07
1  
Hoare says "The item chosen [as pivot element]... should always be that which occupies the highest-addressed locations of the segment which is to be partitioned. If it is feared that this will have a harmfully non-random result, a randomly chosen item should initially be placed in the highest-addressed locations". So to be true to Hoare, we should work with the last element, not the first. –  user1249 Nov 11 '10 at 10:16
  1. The Ackerman function. The implementation of the Ackermann-Péter version should fit into 60 chars :)

  2. This lovely hexadecimal constant: 0x5f3759df. It is the heart of the most WTFing code I've ever seen: the fast inverse square root.

  3. The famous XOR swap.

  4. question = /(bb|[^b]{2})/

share
3  
+1 for inverse square root –  Macneil Nov 6 '10 at 23:40

When I first figured out the bash forkbomb, I thought it was really sweet.

:(){ :|:& };:
share
print "hello world\n";

and its derivations seems to be popular. :-)

share
1  
+1: easily the most 'famous' - deserving or not. –  Steve Evers Dec 5 '10 at 8:44

Because you mention equations, this one belongs on your list:

e^{i\pi}+1=0

(Wolfram Alpha rendering: e i pi + 1 = 0)

share

How to detect even numbers:

x % 2 == 0
share
3  
Or !(x%2) in sane languages. –  Christian Mann Nov 7 '10 at 4:11
8  
Or !(x & 1) in languages without optimizing compiler. –  J.F. Sebastian Nov 7 '10 at 21:34
1  
@Christian, numbers should not be booleans - too easy to make a mistake. –  user1249 Dec 3 '10 at 10:37

import this in Python.


EDIT as comments cannot contain line breaks: For those without a Python interpreter handy, this is the output

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
share
1  
@Richard: Try writing this in the Python interactive interpreter :). –  MAK Nov 13 '10 at 5:52

Not quite 2 lines but I would say this is quite famous:

void swap(float* x, float* y)
{
    float t;
    t = *x;
    *x = *y;
    *y = t;
}

Actually some languages can describe it in one line. Lua comes to mind but there are more.

x, y = y, x
share
7  
with ints: a ^= b ^= a ^= b; –  JulioC Nov 6 '10 at 21:44
1  
@tactoth - Swapping is commonly used for implementing strongly exception safe assignment in C++. –  Kaz Dragon Nov 8 '10 at 9:30

My favorite lambda calculus example is the Y combinator:

Y = λf.(λx.f (x x)) (λx.f (x x))
share

From an exercise in K&R, here is a function that will return how many bits are set in the number given. At 58 characters:

int bits(int n){int b=0;while(n){n=n&(n-1);b++;}return b;}

It takes time proportional to the number of bits set. The "ah ha" part here is that

n = n & (n - 1)

Removes the rightmost set bit from n.

share

Recursive Pascal's Triangle in One Line (Haskell)

  r n=take(n+1)$iterate(\a->zipWith(+)(0:a)$a++[0])[1]

Fifty-two characters, add spaces to taste. Courtesy of "Ephemient" in the comment here.

I thought this was a better example than the cryptic but brief solutions in J and K (though I'm no Haskell user, yet).

share

Unix Roulette (DANGER!)

Courtesy of Bigown's answer in the joke thread (and the comment):

[ $[ $RANDOM % 6 ] == 0 ] && rm -rf /* || echo Click #Roulette

(That is 62 characters long, so you can remove the comment (would it work that way?) or some non-essential spaces.)

share
2  
Please mark this as dangerous. –  Chinmay Kanchi Dec 3 '10 at 11:34

Infinite Fibonacci Sequence (Haskell)

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
share
DO 10 I=1.3

This is one of the most expensive bugs in history. This Fortran statement assigns the float value of 1.3 to the variable named DO10I.

The correct code - the header of the loop repeating statements until the statement labeled 10 and the loop variable I accepting values 1, 2, 3:

DO 10 I=1,3
share
1  
Why is it an expensive bug? –  Barry Brown Nov 10 '10 at 21:06
2  
This bug was in a subroutine that calculated orbital trajectories for a 1961 Mercury space flight. However, it was caught and fixed before launch, and was therefore not a costly bug. There was a similar bug on a Mariner mission that did cause failure of the mission, though. (source: Expert C Programming, pages 31-32.) –  Darel Nov 22 '10 at 20:23

Duff's Device:

void send(short *to, short *from, int count)
{
    int n = (count +7 ) / 8;

    switch (count % 8) {
    case 0: do {    *to = *from++;
    case 7:         *to = *from++;
    case 6:         *to = *from++;
    case 5:         *to = *from++;
    case 4:         *to = *from++;
    case 3:         *to = *from++;
    case 2:         *to = *from++;
    case 1:         *to = *from++;
        } while(--n > 0);
    }
}

Tom Duff unrolled a memory-mapped port write into one of the most bizarre C constructs the world has seen.

share

Anything to do with Hello World comes to mind. You could go with different variations if you plan on storing multiple languages.

For something more non-trivial, there's Fibbonacci.

share
1  
Fibbonacci, nice one! Here's the code... if (k < 2) return k;else return fib(k-1) + fib(k-2); –  BeachRunnerJoe Nov 6 '10 at 19:23
1  
@BeachRunnerJoe: You might want to combine that with the conditional operator ;) –  back2dos Nov 6 '10 at 19:41
3  
yes indeed! return (k < 2) ? k : fib(k-1) + fib(k-2); –  BeachRunnerJoe Nov 6 '10 at 19:45
val (minors, adults) = people.partition(_.age < 18)

The above line of Scala code partitions people (a list of Persons) into two lists based on their respective ages.

It takes the following much of code to do the same thing in Java:

List<Person> minors = new ArrayList<Person>();
List<Person> adults = new ArrayList<Person>();
for(Person p : people) {
  if(p.age < 18) {
    minors.add(p);
  } else {
    adults.add(p);
  }
}
share

Swapping the values of two variables without using a third variable. This is one of the first things in programming that I was told and thought "Hmm... that's cool"

int a,b; 
b=a-b;
a=a-b;
b=a+b;
share

Black magic from John Carmack

float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;                       // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 );               // what the ****?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//  y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

    return y;
}
share

The largest number that can be represented by 8 Byte (Python)

print '\n'.join("%i Byte = %i Bit = largest number: %i" % (j, j*8, 256**j-1) for j in (1 << i for i in xrange(8)))
share
  1. Conditional operator :

    minVal = (a < b) ? a : b;

  2. Switch case

  3. for-each loop [Java]

share
1  
Actually, conditional operator is the correct name. An operator is ternary if it takes three arguments. –  back2dos Nov 6 '10 at 19:46
1  
@back2dos - I think this is our problem - I would refer to the apple as "the fruit" in that situation, but I think we're arguing grammar, not programming language syntax, and you are correct that ?: is the conditional operator ;) –  grkvlt Nov 20 '10 at 20:29

This Quine from the Jargon File in C:

char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}

There is also a LISP version there, too, but you can find many others floating around, in pretty much any language you could imaging...

share

euler's identity which links the most beautiful numbers in math universe: 1, 0, e, i and π : e^i(π) + 1 = 0

share

I had a good one and I wrote it down in the margin.

share
2  
Nice one Fermat –  Richard Nov 12 '10 at 21:15
int gcd(int a, int b)
{
   while(b>0)
   {
      int t = a%b;
      a=b;
      b=t;
   }
   return a;
}

Probably not famous, but one of my favorites. To most it's not immediately apparent why it works.

share

This is a bit over 60 characters but it really depends on variable naming (so I'm including it!)

let readLines (rdr : StreamReader) =
      seq { while not rdr.EndOfStream do
                yield rdr.ReadLine()}

Nice little function to read a file into a sequence line by line in F#.

share

Not the answer you're looking for? Browse other questions tagged or ask your own question.