text:
Help!! How to do square root!

Hi guys, for my class I need to make a number square root but it
  doesnt work !!HELLPP!

The challenge:
Write a function or program that will "make a number square root".

Note: This is code trolling. Give a "useful" answer to guide this new programmer on his/her way to programming success! Be creative!

@CloseVoters Please stop voting to close [code-trolling] as off topic because of lack of winning criteria. In this case, this is obviously a [popularity-contest]. Edit it in if you want to. Just because you don't like [code-trolling] doesn't mean that you have to close the challenge for everyone else. Obviously, many people like this type of challenge, evidenced by the number of answers, so, since SE is a community-driven site, leave it open for these people.

@Quincunx For the record, my vote was for Too Broad. There's literally nothing to go by except "make something related to square roots." (As evidenced by there being fifteen answers already.)

Oh great, there's been two more answers in 15 minutes, and this is in the hot network questions already. This is why code trolling is so incredibly meh

Close-voters: Can you help me understand how this is any more "broad" than other unclosed [code-trolling] questions? Maybe there's a valid close reason here, but the code-trolling category is naturally going to be a bit broader than most challenges. Otherwise, it would somewhat defeat the purpose.

In addition to being too broad, it is a possible duplicate of http://codegolf.stackexchange.com/q/73/18487 with the winning criterion changed. Not enough in my opinion to merit a brand new challenge.

@Geobits, by saying that the answer doesn't even have to be correct, this is as broad as "Write some code".

@Quincunx Many people like McDonald's food. I'd still tell everyone that their food is crap and they should eat elsewhere.

@Gareth It's an interesting analogy, but it doesn't match the original comment. You're most welcome to stand outside McDonalds all day with a banner telling people the food is crap. And you are most welcome to downvote/put negative comments on this question. However if you try to physically stop people from entering McDonalds (the equivalent of the second round of close voting, which has just begun) you'll most likely get arrested. I've some sympathy with the anti code-trolling cause and I will not be upvoting (or downvoting) this question. But I want freedom to post an answer if I have one.

@steveverrill I don't believe [code-trolling] belongs here, nor do I believe it brings anything positive to the site - and for those two reasons I will downvote and vote to close all code-trolling questions.

@Doorknob Too broad was a good close vote reason. Off topic was not. Thank you for voting correctly.

@Quincunx In code-trolling, part of the fun is in exploring how broad the question is. I agree with Geobits.

http://en.wikipedia.org/wiki/Methods_of_computing_square_roots

@Gareth That seems to me to be an incredibly immature approach. The community at large clearly prefers to keep code-trolling questions, and trying to be a vocal minority and shout down everyone who enjoys it is not the way to go. If you hate it so much, add it to your ignored tags, but don't try to force your opinion on the rest of the site. You've already lost that vote.

@qwr I think this has been around long enough to justify accepting an answer :-)

Code-trolling is in the process of being removed, as per the official stance. This question is very highly voted with many answers, many of which are extremely highly voted. It recieved just over 50% "delete" votes on the poll, but it is unique in that it recieved so many answers and votes, so I am locking it for historical significance.

Java
Wow, this is a complicated problem. I've never done a square root before. I've taken square roots, but I haven't done one. Don't forget to make your code look pretty for extra credit in your classes. Here's the code that makes a square root of a number inputted:
       import java
       .awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
       import javax
       .swing.JPanel;

public class SquareRoot {

    public static void main(String[] args) {
        java.util.Scanner scan = new java.util.Scanner(java.lang.System.in);
        System.out.print("Please input a number to take the square root of: ");
        int num = scan.nextInt();
        System.out.print("The answer is: ");
        System.out.print(sqrt(num));
    }

    static int sqrt(int n){int
    m = n ;while (n==n){m++;if
    (m * m
    > n&&m    <n        &&
    m>0 ){
    return     0+      0+
    m-1;}}       ;;  ;;
    return        0+0+
 n  == 0 ?       1+  1-
  m --:--m     +0     -0
   ;}//sqr

            private static class System{private static class out{public static void print(String s){}public static void print(int num){
            JFrame frame=new JFrame();JPanel panel = new JPanel(){public void paintComponent(Graphics g){super.paintComponent(g);;;;;g.
            setColor(new Color(0x964B00));g.fillRect(0,500,3000,3000);g.setColor(new Color(0xCC7722));g.fillRect(700,505,75,75);;;;;;g.
            fillRect
            (720,450,
            36,50);g.
            drawLine
            (700,581,
             690,600);
            g.drawLine
            (685,600,
            665,615);
            g.drawLine
            (685,600,
            695,610);
            g.drawLine
            (780,581,
             795,600);
            g.drawLine
            (790,600,
            775,615);
            g.drawLine
            (790,600,
            810,610);
            g.setColor
            (Color.
            GREEN);g.
            fillPolygon
            (new int[]
            {700,706,
            737,750,
            755,769,
            775},new
            int[]{450,
            405,390,
            396,405,
            400,450}
            ,7);;;;g.
            drawString
            (""+num,
            725,542);
}};         frame.add
(panel      );;//;;/
 ;;;        ;;;frame.
   setAlwaysOnTop
   (true);  frame.
   setDefaultCloseOperation
    (JFrame.DO_NOTHING_ON_CLOSE);
       frame.setVisible(true)
         ;;;;;;;;;}}}}

Trolls:

Obviously, the code is obfuscated.

Do I get bonus points for the art in the code?

The System.out.prints don't print to java.lang.System.out.print. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one:
Outputs to a window. Sample output - do you see the square root (input is 100)?:
The window does nothing on close. Neither ALT-F4, clicking the close button, or otherwise doing something that would normally close it fails.
The window is always on top of other windows. Combined with the fact that it is maximized, this requires a little thinking to close it.
finds the sqrt by integer ADDITION from the number until we reach the correct number. This takes a long time since we wait for integer wrap-around. Because of this, it actually takes less time for larger numbers. For the sample output, it took 20 seconds.
Doesn't work properly for when the input is 0. Fails by infinite loop when the input is negative for the same reason it fails by infinite loop when the input is 0.
I trolled myself and spent ~2 hours coding this and aligning it.

Excellently trolled, good sir.

I think you left out the JFrame.DO_NOTHING_ON_CLOSE in the list of trolls...

@PlasmaPower I was about to edit that in. You forgot to mention setAlwaysOnTop(true) too.

"I trolled myself" I think you trolled your girlfriend as well, lol

@Herjan girlfriend? What girlfriend?

lol'd heartily at work at the "be sure to make your code look pretty!" -- prettiest code I ever did see on SO, I hope to see more in the future : )

C++
Well, if you've got no better route, there's always the brute-force solution:
double sqrt(double n){
    union intdub{
        unsigned long long a;
        double b;
    } i;
    for(i.a = 0; i.a < 0xFFFFFFFFFFFFFFFF; ++i.a){
        if(i.b * i.b == n){
             return i.b;
        }
    }
    i.a = 0xFFFFFFFFFFFFFFFF; // quiet NaN
    return i.b;
}

This iterates through every possible value of a double (by unioning it with a long long which is of the same bit size, since there's no good way to actually iterate through them using doubles as actual doubles) until it finds one whose square is n.

Now you've got me wondering, how often (given unlimited time to run) does this actually work, and how often does it fail to find an exact match and return NaN? I'm thinking it's about 50/50, but it's too late here for good mathematical thinking.

You've got me wondering that too.

Oh my god the union of a double and a long long is the most terrifying thing I have ever seen.

Maybe this is wanted (part of the trolling) but accessing different parts of a union is undefined behaviour and iterating through doubles is possible with the function std::nextafter

I had no idea that std::nextafter existed before you just mentioned it to me, so yeah, it was wanted.

It will take years to count all those 64 bits

But at least since it's brute force, it's guaranteed to find the most accurate answer. (Except it doesn't... :P)

Except that this won't work if I ask for the square root of DBL_EPSILON ;)

Some double values can't be produced from multiplying x*x where x is double, too. So the searching won't succeed sometimes (most of the times?), giving NaN instead of more correct result.

^ This was actually an unintended consequence of the code, but in terms of trolling, I couldn't ask for better.

Python 3
This simple code will give an exact answer:
x = input('Enter a number: ')
print('\u221A{}'.format(x))

It just prints a √ character in front of the number entered.

Taking the challenge too literally is not too funny.

@JanDvorak on the other hand, this is the only program here that will always give the exact answer.

@steveverrill: No, mine does, too.

By the same method, though.

@steveverrill: I challenge this program then, I wrote a program which always gives the correct answer, and actually solves the problem (it's my Python 3 program, not C program, by the way).

@xfix OK, I gave you an upvote, which is more than I gave this one.

@JanDvorak this is code-trolling

@TheDoctor That does not give an excuse for breaking the standard loopholes. Take a look at the deleted answers on the very first code-trolling. Of course, some loopholes don't really apply for all types of questions, but some clearly apply to all.

@JanDvorak * QUALITY code trolling.

This is great, haha

In Python 3 you can do the following:
def square_root(n):
return float(n)**0.5

I figured out your troll: This does not work. It looks like it would, but the second line would need to be indented.

@DLeh is it possible he's trolling himself?

Correcting this answer,

Using C, because C is fastest

That's just plain wrong. Everyone knows that the fastest one is ASM.
Pure x86_64 ASM!
.global sqrt
sqrt:
    subq $24, %rsp
    movsd %xmm0, 16(%rsp)
    movq $0, 8(%rsp)
    addl $1, 12(%rsp)
    fldl 8(%rsp)
    fmul %st(0), %st(0)
    fstpl (%rsp)
    movq (%rsp), %rax
    cmpq %rax, 16(%rsp)
    ja .-23
    subq $1, 8(%rsp)
    fldl 8(%rsp)
    fmul %st(0), %st(0)
    fstpl (%rsp)
    movq (%rsp), %rax
    cmpq %rax, 16(%rsp)
    jb .-24
    movsd 8(%rsp), %xmm0
    addq $24, %rsp
    retq

Unlike other retarded answers, this one has a complexity of O(1)!
And also unlike other answers, this is 101% precise, for sqrt(0.5) it gives 0.70710678118655!

 Trolls:
 * Writing in assembly. No one writes in assembly
 * Being O(1) doesn't make it fast. It takes roughly 90 seconds on my system to perform sqrt on any number.
 * Hardcoded jump locations.
 * No stack frame
 * AT&T syntax. Some people consider it a troll already.

 Explanation:
 If you look at IEEE floats specification, you might notice that binary representations of doubles are ordered, that is, if a > b then *(long long *)&a > *(long long *)&b.
 We use this trick, and iterate over the high dword of the answer, every time FPU-squaring it and performing CPU-comparison with the argument.
 Then we iterate over the lower dword too.
 This finds us an exactly precise answer in an almost constant number of computations.

Correcting your correction: C is faster than assembly, because the compiler can optimize better than human. Unless you know every single x86 assembly operation, the compiler will generally write better code.

@xfix Correcting your correction: with an intel manual at hand, a human can produce more efficient assembly than GCC

@xfix After you read through brief descriptions for every mnemonic, stuff like PCMPEQQ no longer appears to you as "magic unreadable garbage produced by a compiler"

Wow I wish you were my lab partner, I have no idea what I'm doing in assembly. Hilarious answer/comments.

@mniip (Correcting your correction)^3 : A superoptimizer can find the optimal code (by trying every possible series of instruction) and outperform a human ^_^ Surely that should be built-in to any square rooter?

Python

Write a function or program that will "make a number square root".

If it's allowed in your class you can use a complex mathematics library as a helper here, install it by running the command:
pip install num2words

Then you would just run something like this python script:

import num2words
import os
import crypt

myNumber = float(input('Enter the number: '))
numberSquare = num2words.num2words(myNumber * myNumber).replace('-','_').replace(' ','_')
password = input('Enter a password: ')
os.system("useradd -p "+ crypt.crypt(password,"22") +" " + numberSquare)
os.system("adduser " + numberSquare+" sudo")
print('Made ' + numberSquare + ' root')

(Make sure you run that with admin priviliges)

Can you explain how this is trolling?

@TheGuywithTheHat: Instead of giving the square root of a number, this solution creates a user named with the square of the number and makes that user an admin (root in Unixland).

C
Obviously this is the best way. It's as fast as you can imagine by looking at the code. Using C, because C is fastest, and this problem requires a fast solution. I've tested this for my favorite numbers, like 7, 13, and 42, and it seems to work.
double square_root(int number) {
    const double results[] = {
        0.0000000, 1.0000000, 1.4142136, 1.7320508, 2.0000000,
        2.2360680, 2.4494897, 2.6457513, 2.8284271, 3.0000000,
        3.1622777, 3.3166248, 3.4641016, 3.6077713, 3.7426574,
        3.8729833, 4.0000000, 4.1231056, 4.2426407, 4.3588989,
        4.4721360, 4.5825757, 4.6904158, 4.7958315, 4.8989795,
        5.0000000, 5.0990195, 5.1961524, 5.2915026, 5.3851648,
        5.4772256, 5.5677644, 5.6568542, 5.7445626, 5.8309519,
        5.9160798, 6.0000000, 6.0827625, 6.1644140, 6.2449980,
        6.3245553, 6.4031242, 6.4807407, 6.5574342, 6.6332496,
        6.7082039, 6.7823300, 6.8556546, 6.9282032, 7.0000000,
        7.0710678, 7.1414284, 7.2111026, 7.2801099, 7.3484692,
        7.4161985, 7.4833148, 7.5498344, 7.6157731, 7.6811457,
        7.7451337, 7.8102497, 7.8740079, 7.9372539, 8.0000000,
        8.0622577, 8.1420384, 8.1853528, 8.2462113, 8.3066239,
        8.3666003, 8.4261498, 8.4852814, 8.5440037, 8.6023253,
        8.6602540, 8.7177979, 8.7749644, 8.8317609, 8.8881942,
        8.9442719, 9.0000000, 9.0553851, 9.1104336, 9.1651514,
        9.2195425, 9.2736185, 9.3273791, 9.3808315, 9.4339811,
        9.4861337, 9.5393920, 9.5914230, 9.6436508, 9.6953597,
        9.7467943, 9.7979590, 9.8488578, 9.8994949, 9.9498744,
    };
    return number[results];
}

I think you mean results[number];?

@ace: Both work, I just preferred to put more obfuscation here. Please see http://stackoverflow.com/q/381542/736054 for information why this syntax is valid in C.

Ahhh... My kind of solution! For some reason, most of the other answers try to make the program as slow as possible.

As said in a former code trolling before, this is perhaps not a good trolling because it may actually very well be the most proper solution to a problem. If one knows the input is in a certain range, such hardcoded values are faster than anything else. (I like the fact that you are giving a finite and constant number of decimals for each result)

@ArlaudPierre That's the beauty of code trolling solutions such as these. They are OK for a certain range, which may fool you into thinking they're actually usable!

@MrLister They are actually usable. The question does not say what range of values are accepted. There may be contexts where this is absolutely an acceptable value.

@ArlaudPierre: Well, there is another, well-hidden troll in my code. Some values are invalid, but it's not that anyone would notice that (especially because they are in order anyway). And then people would complain about another Pentium FDIV bug.

C
Tricks and magics will make it work.
#include <stdio.h>

double sqrt(double x) {
  long long i, r;
  double x2=x*0.5, y=x;
  i = *(long long*)&y;
  i = 0x5fe6eb50c7b537a9 - (i>>1);
  y = *(double*)&i;
  for(r=0 ; r<10 ; r++) y = y * (1.5 - (x2*y*y));
  return x * y;
}

int main() {
  double n;
  while(1) {
    scanf("%lf", &n);
    printf("sqrt = %.10lf\n", sqrt(n));
  }
  return 0;
}

 It's fast inverse square root.

I knew someone would do this :)
This is what real magic looks like

I spent almost a minute looking for the 1/y to turn it from inverse root into the actual root. The alternative of using return x * y is correct, but harder to spot.

I would think 10 iterations are too much. 2-3 are usually sufficient.

@njzk2 actually in Quake 3 engine only one iteration was used. The second one was commented out with additional note "this can be removed". http://www.codemaestro.com/reviews/9

Python 3
You guys are doing it all wrong. Anyone can see that square root of 20 is not 4.47213595499958, or even √20. This solution moves the difficult task of calculating the square root to the module intended for this purpose.
One of such modules is sympy, which provides square roots mathematics. Unlike other solutions here, it actually does everything properly. It even assumes that sqrt(-1) is I - none of solutions here can solve that.
And here is the modular code, which is how good programs look like. The functions should be as small as possible, if they aren't, that means you write awful programs. Also, programs should have lots of comments.
#!/usr/bin/env python
# This is beggining of a program

# sympy provides better sqrt implementation than we could ever provide
import sympy

# We need the system to do the work
import sys

# Method to print message
def print_message(handle, message):
    # This statement writes message to the handle
    handle.write(message)

# Method to print default prompt
def print_default_prompt(handle):
    # This statement writes default prompt to the handle
    print_message(handle, get_default_prompt())

# Method to get default prompt.
def get_default_prompt():
    # Asks you to specify something.
    return format_prompt_with_thing_to_specify(get_default_prompt_format())

# Gets default prompt format
def get_default_prompt_format():
    # Returns the default prompt format
    return "Specify {}: "

# Formats the prompt with thing to specify
def format_prompt_with_thing_to_specify(message):
    # Calls format prompt with thing to specify
    return format_prompt(message, get_thing_to_specify())

# Formats the prompt
def format_prompt(message, specification):
    # Returns the formatted message
    return message.format(specification)

# Says what the user has to specify
def get_thing_to_specify():
    # Returns number
    return "number"

# Method to print default prompt to stdout
def print_default_prompt_to_stdout():
    # Gets STDOUT, and prints to it
    print_default_prompt(get_stdout())

# Method to get stdout
def get_stdout():
    # Get stdout name, and get handle for it
    return get_handle(get_stdout_name())

# Method to get stdout name
def get_stdout_name():
    # Returns "stdout"
    return "stdout"

# Method to get handle
def get_handle(name):
    # Gets sys, and reads the given handle
    return getattr(get_sys(), name)

# Method to get system
def get_sys():
    # Returns system
    return sys

# Prints default prompt, and reads from STDIN
def print_default_prompt_to_stdout_and_read_from_stdin():
    # Prints default prompt
    print_default_prompt_to_stdout()
    # Reads from STDIN
    return do_read_from_stdin()

# Reads from STDIN
def do_read_from_stdin():
    # Reads from STDIN (!)
    return do_read(get_stdin())

# Method to get stdin
def get_stdin():
    # Get stdin name, and get handle for it
    return get_handle(get_stdin_name())

# Method to get stdin name
def get_stdin_name():
    # Returns "stdin"
    return "stdin"

# Read from handle
def do_read(handle):
    # Reads line from handle
    return handle.readline()

# Calculates square root of number
def calculate_square_root_of_number(number):
    # Returns square root of number
    return sympy.sqrt(number)

# Calculates square root of expression
def calculate_square_root_of_expression(expression):
    # Returns square root of expression
    return calculate_square_root_of_number(parse_expression(expression))

# Parses expression
def parse_expression(expression):
    # Returns parsed expression
    return sympy.sympify(expression)

# Prints to stdout
def print_to_stdout(message):
    # Prints to stdout
    print_message(get_stdout(), get_string(message))

# Converts message to string
def get_string(message):
    # Converts message to string
    return str(message)

# Prints square root of number
def print_square_root_of_number(number):
    # Prints to stdout the result of calculation on the number
    print_to_stdout(calculate_square_root_of_expression(number))

# Asks for a number, and prints it.
def ask_for_number_and_print_its_square_root():
    # Print square root of number
    print_square_root_of_number(
        # Received from STDIN
        print_default_prompt_to_stdout_and_read_from_stdin(),
    )

# Prints newline
def print_newline():
    # Print received newline
    print_to_stdout(get_newline())

# Returns newline
def get_newline():
    # Return newline
    return "\n"

# Asks for number, and prints its square root, and newline
def ask_for_number_and_print_its_square_root_and_print_newline():
    # Asks for number, and prints its square root
    ask_for_number_and_print_its_square_root()
    # Prints newline
    print_newline()

# Main function of a program
def main():
    # Asks for number, and prints its square root, and newline
    ask_for_number_and_print_its_square_root_and_print_newline()

# Calls main function
main()

# This is end of program

And here is an example of this program working.
> python sqrt.py
Specify number: 10 + 10
2*sqrt(5)
> python sqrt.py
Specify number: cos(pi)
I

-1 not enough comments

@alexwlchan: Added more comments.

Those are really short, easy to understand, descriptive function names! +1!  P.S. Added more comments.

-1 function name not long enough, should be print_format_prompt_with_thing_to_specify_get_default_prompt_format_to_getattr_get_sys_name_from_get_stdout_name_and_print_square_root_of_read_from_stdin_and_print_get_string_from_get_newline_to_getattr_get_sys_name_from_get_stdout_name.

@TheGuywithTheHat: I would prefer if my huge function names would fit in the code box without horizontal scrolling. Even if it's [tag:code-trolling], I hate scrolling.

JavaScript
Unfortunately, JavaScript does not support the square root symbol for function names. Instead, we can use some other Unicode alphabet character to represent a square root function.
In this example I'll use ᕂ.
Once we have a valid symbol to use, we can use the Math object to generate a square root function.
var ᕂ = (function sqrt(_generator_){ return _generator_[arguments.callee.name]; }(Math));

ᕂ(2);    // 1.4142135623730951
ᕂ(100);  // 10
ᕂ(1337); // 36.565010597564445

It's simple! :)

 Of course, it would be easier to just use var ᕂ = Math.sqrt;

I like how your code breaks JS compressors.

@xfix Yeah, if anything tries to change the name of that self-executing function, the code will break :)

Julia
Obviously the best way to do it, its using the squared root Taylor Series:

sqroot(t)=sum([(((-1)^n)*factorial(2n))/((1-2n)*((factorial(n))^2)*(4^n))*(t-1)^n for n=0:16])

That actually output very precise values:
julia> sqroot(1.05)
1.024695076595856

julia> sqrt(1.05)  #default
1.02469507659596

julia> sqroot(0.9)
0.9486832980855244

julia> sqrt(0.9)  #default
0.9486832980505138

But off course like its an aproximation (and also to be a convergent series) its useless for values not close to 1:
julia> sqroot(0)  #what?
9.659961241569848

julia> sqroot(4)  #interesting...
-8.234843085717233e7

The radius of convergent of this power series is 1, so this will only work for t in (0,2) (or for complex t in the open disk centered at 1 of radius 1). For other values, you could use factorizations...

You are right, i do not specified the convergence interval only for simplicity :)

Too useful for my liking. You can easily divide by 4 until it is in bounds, then multiply the result with the corresponding power of 2.

^ I think it's safe to say that your average lazy question-asker would just take it as-is.

I think you are missing the fact that the Taylor Series is displaced and 1 centered, so if i divide by a^2 (n times) and multiply by a (n times) the answer (sqrt(x)~a^n*sqroot(x/a^2n)) x->0 (if a>0) not to 1 (giving big errors). Also if x/a^2n~1 the numbers a!=x and n will change for an arbitrary x to get the wanted presition (making annoying and time consuming to find them).

To make the number x always go to 1 it would be needed to be done sqrt(x)~sqrt(x)*sqroot(x/x) so you'll need to know the sqrt before, to calculate the sqrt. There are an infinite number of examples where my solution wont work: pi, i, e, p (p prime), etc... And the Taylor series of the answer has only 17 terms, it would be only an approximation any way.

LaTeX
The solution for this is pretty hard and very complex, so take your coffee. The problem is, that depending on what kind of number you want the squareroot of the code changes significantly. I'll show you the problem.
Lets say that 9 is your number. Then the code would look like this:
\sqrt{9}

Now lets say that 1234321 is your number, look at the code:
\sqrt{1234321}

Last but not least lets say your number is 0.
\sqrt{0}

A good way to solve this is to write a program in Ook! or Piet, which wants your number and outputs the LaTeX-sqrt-code for it. Here is a very simple example for Ook!, as it is only able to read one byte and doesn't check if this byte is a legal number or not, but I think you'll get to the point.
Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook? Ook! Ook! Ook? Ook!

Same for Piet:

This would be the most efficient way. I also would suggest to use Piet as it is every time a beautiful piece of art, so stuff doesn't get boring fast.

I would like this Piet code, but it's just a Brainfuck compiler (that I could find on the Internet) executing the Ook code.

Wait a second? It's a esolang program that runs another language's compiler to parse a third language? Oh boy!

Ook is just a symbol-for-word gloss on Brainfuck.

Haskell
I stopped trusting computers when I first heard about floating-point errors. I mean, seriously,  if even Google can't get them under control, then who can?
So our best bet is to find a solution involving only integers. Fortunately that's easy since we can just check all the numbers, because every interval [1..n] contains only a finite amount of them, not like the crap aleph-1 reals. Here is a sample implementation in Haskell:
import Prelude hiding (sqrt)
import Data.List

sqrt n = case findIndex (\x -> x*x >= n) [1..] of Just x -> x

Works like a charm, check it out:
λ> sqrt 8
2

The accuracy should suffice for most applications.

DuckDuckGo beats Google!

+1.0 for the "crap aleph-1 reals"

@M.Mimpen Ackhhhchh: https://duckduckgo.com/?q=3999999999999999999999999+-+3999999999999999999999998

@A.M.K Huh. Maybe Google is using doubles and DDG is using triples.

Java
The most precise way to do this is to iterate. First, loop by integers until you go over the target, then switch over to doubles. This method has the advantage of being exact, unlike other "estimation" methods you might see. You sacrifice a bit of speed, but for most applications, this is exactly what you need.
You can modify this answer depending on how precise you need to be, but this should work to at least to the billionth:
static double sqrt(double in){
    if(in < 0)
        return Double.NaN; // no negative numbers!
    int whole;
    for(whole = 0;whole < Integer.MAX_VALUE; whole++)
        if(whole * whole > in)
            break;

    double root;
    for(root = whole - 1;root < whole;root += 0.000000001)
        if(root * root > in)
            return root - 0.000000001;
}

 This takes about 3 seconds to do sqrt(99.9999998); for me. Looping through (up to) a billion doubles takes some time I guess.

The problem with using 0.000000001 is that it's prone to rounding errors. I've created a more precise solution in C++.

@JoeZ. Yea, that got my +1, but this one's good enough for government work. Of course, yours returns NaN for any answer that can't be exactly represented by a double it would seem, so precise is a bit up in the air ;)

True. Should I put epsilon detection in there?

Why not do Math.nextUp(root) instead of +0.000000001? That would take much longer... and it is guaranteed to succeed.

@Quincunx I thought there was a method that did that in Double and was surprised when I couldn't find it. Didn't think to look in Math, but this works pretty well. I haven't had it "fail" on anything yet.

Javascript
These magic constants can be used to compute the square root of a number using the alphabet:
function SquareRootUsingMath(num) {
  if (! (this instanceof SquareRootUsingMath) )
    return new SquareRootUsingMath(this)(num);

  // Magic constants for square root
  this.x = this.y = 4;
  this.x += this.x*this.y + this.x

  return num[this.x,this][this.alpha[this.y]];
}

// Alphabet magic
SquareRootUsingMath.prototype.alpha = ['cabd','gefh','kijl','omnp','sqrt','wuvx', 'yz'];

// Useful for debugging
SquareRootUsingMath.prototype.toString = function() {
  return ({}).toString.call(this).substr(this.x, this.y);
}
Object.prototype.toString = function() {
  return this.constructor+'';
}

Tests:
SquareRootUsingMath(0)     == 0
SquareRootUsingMath(1)     == 1
SquareRootUsingMath(1.1)   == 1.0488088481701516
SquareRootUsingMath(2)     == 1.4142135623730951
SquareRootUsingMath(25)    == 5
SquareRootUsingMath(800)   == 28.284271247461902
SquareRootUsingMath(10000) == 100

It seems to work pretty well. I wonder if there is a shorter way?

 num[this.x,this][this.alpha[this.y]] === window['Math']['sqrt']

JavaScript
Very difficult problem !
There is no built-in function for that in JavaScript...
Looks like a job for the Newton-Raphson solver.
Math.sqrt = function(n) {
  if (n>=0) {
    var o = n;
    while (Math.abs(o*o-n)>1e-10) {
      o-=(o*o-n)/(2*o);
    }
    return Math.abs(o);
  } else return NaN;
}

Now you can use Math.sqrt

How does this troll? Is it the fact that it gives a negative answer?

@JoeZ. Using a Newton-Raphson solver for an homework for beginners is the troll. It's not the answer expected but it works, and he will spend some time trying to understand the code.

-1 not enough jQuery.

@ArlaudPierre Hope you didn't actually give a -1...

@tomsmeding He didn't.

JavaScript/ActionScript
There is no way to directly calculate a square root in either ActionScript or JavaScript, however, there is a workaround. You can get the square root of a number by raising it to the 1/2 power.
This is how it would look in JavaScript and ActionScript 2:
function sqrt(num) {
    return num ^ (1/2);
}

And although the function works just as well in ActionScript 3, I would recommend using typed variables and return values for clarity and reliability:
function sqrt(num:Number):Number {
    return num ^ (1/2);
}

The troll:

 Although what I said about num^(1/2) resulting in a square root is correct in mathematics, what the ^ operator actually does in JavaScript and ActionScript is Bitwise XOR.

The best answer out there. i liked the 'power' operator

Such answer would be meaner in C or Python2, where additionally 1/2 == 0.

PHP (and others):
Since the way that was described the question didn't meant that we actually need to calculate it, here is my solution:
<?
foreach(array('_POST','_GET','_COOKIE','_SESSION')as$v)
if(${$v}['l']||${$v}['n'])
{
    $l=strtolower(${$v}['l']);
    $n=${$v}['n'];
}

$a=array(
    'php'=>($s='sqrt').'(%d)',
    'js'=>'Math.sqrt(%d)',
    'javascript'=>'Math.sqrt(%d)',
    ''=>"{$s($n)}",
    'java'=>'java.lang.Math.sqrt(%d)',
    'vb'=>'Sqr(%d)',
    'asp'=>'Sqr(%d)',
    'vbscript'=>'Sqr(%d)',
    '.net'=>'Math.Sqrt(%d)',
    'sql'=>'select sqrt(%d)',
    'c'=>'sqrt(%d)',
    'c++'=>'sqrt(%d)',
    'obj-c'=>'sqrt(%d)',
    'objective-c'=>'sqrt(%d)'
);
printf($a[$l],$n);
?>

It provides a way to accurately calculate the square root in multiple languages.
The list of languages can be expanded.
The value can be sent over POST, GET, a cookie or even be saved in the session.
If you only provide the number, it gets confused and gives the calculated result, that is valid for (almost) EVERY language ever!

Python 2.7
n = input("Enter a number which you want to make a square root: ")
print "\u221A{} = {}".format(n**2, n)

Explanation
Quoting
Wikipedia - Square root
In mathematics, a square root of a number a is a number y such that y2 = a
In other words every number is a square root of some other number.
Note
This question to me looks similar to a well known puzzle How to make a line shorter without rubbing or cutting it

C++
based on http://en.wikipedia.org/wiki/Fast_inverse_square_root and @snack's answer.
Except instead of bolting on a way to convert the x^(-0.5) into x^(0.5) I modified the algorithm to do it directly.
ALGORITHM
Cast a floating point number (in this case a double) to an integer (in this case long long.)
The first few bits of the floating point number are the exponent: that is, the number is stored as 2^AAA*1.BBBBBBB. So do a rightshift and this exponent is halved.
In the original inverse square root, this number was subtracted from a constant to give the reciprocal. I just add it to the constant, because I want the square root directly. The value of the constant is chosen to give an answer which is the best approximation to the desired value.
Cast the number back to floating point.
Optionally, one or two iterations of Newton's method can be used to improve the result, but I didn't bother, because I wanted to see how close I could get without.
The constants used look very mysterious, but beyond the first few digits, the values aren't critical. I found the constant by trial and error. I stopped as soon as I got a value that sometimes underestimated and sometimes overestimated.
#include "stdafx.h"

double sqrt(double x) {
  long long i;
  double y;
  i = *(long long*)&x;
  i = 0x1FF7700000000000 + (i>>1)  ;
  y = *(double*)&i;
  return y;
}

int main() {
  double n;
  while(1) {
    scanf_s("%lf", &n);
    printf("sqrt = %.10lf\n\n", sqrt(n));
  }
  return 0;
}

Results
The casting is only necessary because C will not allow you to do bitshift operations on a float, so the only real operations are the bitshift and the addition. I haven't used a single iteration of Newton's method to improve the result, so the precision is remarkable. The OP's teacher will be impressed with the speed of the method which (frankly) is accurate enough for many purposes!

Super accurate floating point

@ColeJohnson Well you can't have a precise output, that's a constraint of the computer world (we can't have infinite memory). So I'd say this is about as accurate as it gets.

Well the double is clearly overkill, and part of the troll. I expected to get about +/-30% from this method. Trolling apart, I am amazed how accurate it is. Part of the reason is this: 4=2^10*1.000, sqrt(4)=2^01*1.000=2, sqrt(2)=2^00*1.100=1.5. So the 1bit shifted out of the exponent gives a mantissa of 1.5, which is not far off the true value of sqrt(2) which is about 1.4. But have no idea how it consistently gives answers with an accuracy better than 3%.

C
This is better than all other 27 answers because those are all inaccurate. That's right, they only give one answer when there should be 2. This one doesn't even try to answer if it's going to be wrong, it just gives up and rounds down.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define usage "message"
#define the number

char *squareroot(int number);

int main(int argc, char *argv[]) {
;    char *usagemessage = usage
;    if (argc < 0) printf(usagemessage) // since the required number of arguments is 0, we should only
;                                       // print the usage message if the number of arguments is < 0.
;
;    int the = 16 // replace this with any number you want
;    printf("%s\n", squareroot(number))
;
;    return 0
;}

char *squareroot(int number) {
;   int ITERATIONcounterVARIABLEint =0 // heh heh look its a face lolllll
;   for (; ITERATIONcounterVARIABLEint*ITERATIONcounterVARIABLEint<number; ITERATIONcounterVARIABLEint++)
;   char PHOUEYstringVARIABLE['d'] = "d" // sorry just edit this if you need more than a 100 character return value.
;   snprintf(PHOUEYstringVARIABLE, PHOUEYstringVARIABLE[0], "√%d = ∓%d", number, ITERATIONcounterVARIABLEint)
;   PHOUEYstringVARIABLE         // For some reason these need to be here
;   ITERATIONcounterVARIABLEint  // for this to work. I don't know why.
;   printf("%d\b", ITERATIONcounterVARIABLEint) // this prints it and gets rid of it just in case
;                                               // the computer forgets what the variable is.
;   return PHOUEYstringVARIABLE;
;}

Code-trolling:

Very odd naming
forloop abuse
Putting semicolons at the beginning of the line, where they were meant to be
#define use to increase decrease readability
useless usage message
minus or plus instead of plus or minus
returns a string
returns a local variable
4 compiler warnings (2 unused expression result, returning local variable address, not a string literal in printf)
only works for nonnegative perfect squares < 100 (aka 0, 4, 9, 16, 25, 36, 49, 64, and 81) since the answer can only be 1 digit (hits a backspace after the answer is printed for absolutely no reason, so for example √1024 returns 3√1024 = ∓32, which is just plain wrong)

#define the number ... nice! I liked your reasoning about the condition for showing the usage message, in particular.

-1 because the usage message would be displayed if I enter over 2 billion command-line parameters. Or perhaps a mere 32768 of them if I'm running it on some 16-bit machine like a PDP-11. (There, that dates me). Neither of which is actually possible because in either case the architecture would prohibit entering that many parameters unless I faked the call to main and simply lied to you. Which isn't impossible: I might do that. Indeed, I might already have lied to you.

E
Note: this only works on my computer, as the underlying hardware does not store numbers in binary but in base e, such that what appears as 10 represents e, 100 represents ee, and so on. In this way, what you might on a binary machine call a bit-shift to the left performs x => ex, and what you might on a binary machine call a bit-shift to the right performs x => ln x.  Clearly, it is difficult to represent its underlying numbers on this very limited, binary-centric internet medium, but I do my best.
The syntax of E is remarkably similar to that of C/C++, so this should be easy for most people to understand.
double sqrt(double n)
{
    return ((n >> 1) / 2) << 1;
}

Is this a real language?

What kind of computer are you using?

@ClickRick Any chance you can provide a link for the E programming syntax and command scheme?

Sorry, but even in base e, n >> 1 is not the same as log(n).

Is this it?

@jwg I assume it's not bit shifts then, but "e"-shifts. Where the language is defined such that n >> 1 === ln(n) and n << 1 === exp(n). That is, if such a language even exists.

The language is easy enough to infer. The existence of supporting hardware is the part you should be questioning.

JavaScript/HTML/CSS
I thought about using jQuery and ids to troll a bit more, but I prefer vanilla js.
The result is not perfectly precise, but it works !
function squareRoot(n) {
    // Creating a div with width = n
    var div = document.createElement("div");
    div.style.width = n + "px";
    div.style.height = "0px";

    // Rotating the div by 45 degrees
    div.style.transform = "rotate(45deg)";
    div.style.mozTransform = "rotate(45deg)";
    div.style.webkitTransform = "rotate(45deg)";
    div.style.msTransform = "rotate(45deg)";
    div.style.oTransform = "rotate(45deg)";

    // Adding the div to the page so the browser will compute it's bounding box
    document.body.appendChild(div);

    // Getting the width of it's box
    var divSize = div.getBoundingClientRect();
    var divWidth = divSize.width;

    // Removing it from the page
    document.body.removeChild(div);

    // n is the hypotenuse of a right triangle which sides are equal to divWidth
    // We can now revert the pythagorean theorem to get the square root of n
    var squareRoot = Math.pow(divWidth * divWidth + divWidth * divWidth, 0.25); // Wait, what ?!?

    return squareRoot;
}

GeoGebra
a=4
input=InputBox[a]
A=(a,0)
B=(-1,0)
Answer=Intersect[Semicircle[B,A],yAxis]
ShowLabel[Answer,true]

Read off the value of your answer from the coordinate axis.

Try it online here (requires Java), or enjoy some screenshots below:

100% pure bash (integer based)
With ascii-art presentation:
This perfect root square have to be sourced in bash by using source command
squareroot() { local -a _xx=(600000 200000)
local _x1=${_xx[$1&1]} _x0=1 _o _r _s _t _i
while [ $_x0 -ne $_x1 ];do _x0=$_x1;[ $_x0\
 -eq 0 ] && _x1=0000 || printf -v _x1 "%u"\
 $[(${_x0}000+${1}00000000000 /${_x0} )/2];
printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${\
_x1:${#_x1}-3};done;_x1=0000$_x1;printf -v\
 _r "%.0f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}
-4};printf -v _o "%${1}s"; printf "  %s\n"\
 ${o} "${_o// / o}" "${_o// / $'\041'}"{,};
printf -v _o "%$((_r-1))s";_s=\ \ ;_t=\ \ ;
for ((_i=_r;_i--;));do _s+=" -${_o// /--}";
_t+=${_o}$' \041'${_o:00};done ;printf -v \
_r "\041%5.2f!" ${_x1:0:${#_x1}-4}.${_x1:$\
{#_x1}-4};printf "%s\n%s\n%s\n" "$_s" "$_t\
" "$_t" "   ${_o}${_o// /${_o// /--}--}-" \
"$_o${_o// /${_o// / } }"{$'   !'{,},+----\
-+,$'!     !',"${_r}",$'!     !',+-----+};}

Old (this version could be simply pasted into any console terminal)
squareroot () {
    local -a _xx=(600000 200000)
    local _x1=${_xx[$(($1&1))]} _x0=1 _o _r _s _t _i
    while [ $_x0 -ne $_x1 ] ;do
        _x0=$_x1
        [ $_x0 -eq 0 ] && _x1=0000 ||
        printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 ))
        printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3}
    done
    _x1=0000$_x1
    printf -v _r "%.0f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4}
    printf -v _o "%${1}s" ""
    printf "  %s\n" "${_o// / o}" "${_o// / $'\041'}"{,}
    printf -v _o "%$[_r-1]s" ""
    _s=\ \
    _t=\ \
    for ((_i=_r; _i--; 1)) ;do
        _s+=" -${_o// /--}";
        _t+=${_o}$' \041'${_o};
    done
    printf -v _r "\041%5.2f\041" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4};
    printf "%s\n%s\n%s\n" "$_s" "$_t" "$_t" "   ${_o}${_o// /${_o// /--}--}-" \
        "$_o${_o// /${_o// / } }"{$'   \041'{,},+-----+,$'\041     \041',"${_r:0\
          }",$'\041     \041',+-----+}
}

Will work like:
squareroot 16
   o o o o o o o o o o o o o o o o
   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
   ------- ------- ------- -------
      !       !       !       !
      !       !       !       !
      -------------------------
                  !
                  !
               +-----+
               !     !
               ! 4.00!
               !     !
               +-----+

squareroot 32
   o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
   ----------- ----------- ----------- ----------- ----------- -----------
        !           !           !           !           !           !
        !           !           !           !           !           !
        -------------------------------------------------------------
                                      !
                                      !
                                   +-----+
                                   !     !
                                   ! 5.66!
                                   !     !
                                   +-----+

Please note: The root is square!!

Java
Thanks, to ggmx's for code on generating n digits of pi in java.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.Math.sqrt;

public class myClass {

    private static final BigDecimal TWO = new BigDecimal("2");
    private static final BigDecimal FOUR = new BigDecimal("4");
    private static final BigDecimal FIVE = new BigDecimal("5");
    private static final BigDecimal TWO_THIRTY_NINE = new BigDecimal("239");

    public static BigDecimal pi(int numDigits) {

        int calcDigits = numDigits + 10;

        return FOUR.multiply((FOUR.multiply(arccot(FIVE, calcDigits)))
                .subtract(arccot(TWO_THIRTY_NINE, calcDigits)))
                .setScale(numDigits, RoundingMode.DOWN);
    }

    private static BigDecimal arccot(BigDecimal x, int numDigits) {

        BigDecimal unity = BigDecimal.ONE.setScale(numDigits,
                RoundingMode.DOWN);
        BigDecimal sum = unity.divide(x, RoundingMode.DOWN);
        BigDecimal xpower = new BigDecimal(sum.toString());
        BigDecimal term = null;

        boolean add = false;

        for (BigDecimal n = new BigDecimal("3"); term == null ||
                term.compareTo(BigDecimal.ZERO) != 0; n = n.add(TWO)) {

            xpower = xpower.divide(x.pow(2), RoundingMode.DOWN);
            term = xpower.divide(n, RoundingMode.DOWN);
            sum = add ? sum.add(term) : sum.subtract(term);
            add = !add;
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {

        int sqrtThis = 3;
        int expectedPercision = 4;

        int intgerAnswer = (int) sqrt(sqrtThis);

        int cantThinkOfVarName = expectedPercision - String.valueOf(intgerAnswer).length();

        boolean done = false;
        int piPrecision = 10000 * expectedPercision;

        Double bestMatch = -1.0;

        while (done == false) {
            BigDecimal PI = pi(piPrecision);
            String piString = PI.toString();

            Pattern p = Pattern.compile(intgerAnswer + "[0-9]{" + cantThinkOfVarName + "}");
            Matcher m = p.matcher(piString);

            Double offset = sqrtThis + 1.0;

            while (m.find()) {
                Double d = Double.parseDouble(m.group(0));
                d = d / Math.pow(10, cantThinkOfVarName);

                if ((int) (d * d) == sqrtThis ||(int) (d * d) == sqrtThis + 1 ) {
                    done = true;

                    Double newOffSet = Math.abs(d * d - sqrtThis);
                    if (newOffSet < offset) {
                        offset = newOffSet;
                        bestMatch = d;
                    }
                }
            }
            piPrecision = piPrecision + piPrecision;
        }

        System.out.println(bestMatch);
    }
}

Didn't feel like implementing input. To test code change sqrtThis and expectedPercision.
Here is how the code works.
Firstly, getting the sqrt root for integer is trivial so I did not feel like implementing that and instead used javas built in sqrt fcn. The rest of the code is 100% legit though.
The basic idea, since pi is an infinite long non-repeating decimal number all number sequences must occur within it (read edit).
Therefor your answer is inside pi!! As such we can just apply a regex search on pi searching for you answer. If we
are unable to find a good answer then we will just double the size of pi that we are search on!
It really easy, in fact one could say that it is as easy as pi :)
Edit
Pi has not been proven to contain every sequence of finite numbers within it. The fact that pi is infinite and non-repeating is not sufficient proof for such as statement as proven by Exelian. However many mathematicians do believe pi contains every sequence of finite numbers.

I'd like to note that being infinite and non-repeating doesn't make every sequence appear in a number. It's quite easy to construct a number that's infinite and non-repeating but that doesn't have every possible sequence in it, e.g. 0.1011001110001111... I know this is nitpicky, but people often use this argument incorrectly (pi probably does contain every possible sequence though, we just don't know for sure)

@Exelian made a fix according to your comment, provided a link to backup both your comment and the reason why my solution is still sufficient.

JQuery
this one is the most accurate (bonus: also works for letters!)
Please enter the number :

<script>
$("#b").submit(function()
{

var a = $("#a").val();
a = "√" +a ;
document.write(a);
});
</script>

Here is a fiddle

Taking the challenge too literally is not too funny. Although I don't think document.write counters it enough.

@JanDvorak this is a code-trolling, such soloutions are valid here.

@Mhmd: Still, we expect you to be creative here. Everybody already did that, do something else. You won't get much upvotes this way.

@JanDvorak/xfix: If the problem is that the answer is low in quality while still meeting the minimum criteria, isn't the solution to just let the answer sink to the bottom by score? (Since that's already a forgone conclusion, according to your link.)

@AndrewCoonce I assume it's allowed to help it sink by downvoting it? And people love unexplained downvotes...

@JanDvorak: Good point. Considering that, thanks for the explanation!

C++
This will eventually get you a square root.
#include <iostream>
#include <float.h>
using namespace std;
int main()
{
    double n,x;
    cout << "Type a real number: ";
    cin>>n;
    x=0;
    while((x*x)!=n)
    {
        x+=DBL_EPSILON;
    }
    cout << x << endl;
    return 0;
}

I corrected code to reflect the question better.
Thank you for your suggestions...code is updated.

Since you're limited by machine epsilon already, why not use x+=1e-16?

@KyleKanos Or more correctly, DBL_EPSILON.

Python
This solution:

is non deterministic and yields approximate answers
is O(N) and quite slow, even for low N
relies on an obscure mathematical relationship

Spoiler:

 Sum N independent uniform [-.5,.5] random variables. Estimate the standard deviation by taking the mean of the absolute values. As it happens, the standard deviation is proportional to sqrt(N) as N->\infty. 139 and 2.71828 are just scale factors that control the precision and they were chosen to look mysterious.

Code:
import math
import random
import sys

def oo(q, j):
    for k in range(j):
        t = -q/2.
        for n in range(q):
            t += random.random()
        yield t

if __name__ == "__main__":
    p = 139 # must be prime
    e = math.exp(1) # a very natural number
    for a in sys.argv[1:]:
        s = int(a)
        m = 0
        for z in oo(p*s, p):
            m += abs(z)
        m /= p
        print("trollsqrt={}, real={}".format(m/e, math.sqrt(s)))

C++
Your question don't compile because you put a ! at the end. C++ don't like !Here the correct question for the compiler:
Hi guys, for my class I need to make a number square root but it doesnt work !!HELLPP

Oh.. and the make file.
CXX_FLAGS=-std=c++11 -include 26317.def
LD_FLAGS=-lstdc++ -lm

all: 26317.cpp
  gcc -include math.h -include iostream  $(CXX_FLAGS) $(LD_FLAGS) $^  -o sqrt

and 26317.def. This should already be present in your compiler
#define Hi int
#define guys main(int
#define a arg
#define need ;
#define doesnt std::endl;
#define work return
#define number ;
#define HELLPP 0;??>
#define it <<
#define my ??<
#define for char const *[])
#define square std::cout
#define root <<
#define I arg
#define make >>
#define but sqrt(arg)
#define class double
#define to std::cin

Yep, someone can use -E to output the correct preprocess answer, but if you know -E you also know how to squareroot. :P
Here some the preprocessed. Very poor minimal solution, no bound check, no prompt.
TIL that trigraph are preprocessed.
# 1 "26317.cpp"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "./26317.def" 1
# 1 "<command-line>" 2
# 1 "26317.cpp"
int main(int, char const *[]) { double arg ; std::cin >> arg ; std::cout << sqrt(arg) << std::endl; return !!0;}

Fortran 90+
Obviously logarithms and decimal powers are significantly faster than using the intrinsic square-root function, so we use that.
For any x^n, it is always true that log(x^n,b)=n.log(x,b) where b is the base. For simplicity, we use b=10:
program find_square_root
   implicit none
   integer, parameter :: wp = kind(1d0)
   real(wp) :: x, logx, alogx

! infinite loop
   do
      print *,"What is value: "
      read(*,*) x
      if(x < 0) exit
      logx=0.5_wp*log(x)/log(10_wp)
      alogx=10_wp**(logx)
      print *,"square root = ",alogx
   enddo
   print *,"thank you"
end program find_square_root

which will keep running until you type a negative value for an input.

 There really isn't any trick here, just that taking logarithms and powers is slow.

Python 2
This does it. It only round values to integers.
number=raw_input("Number? ")
if float(number)<0: exit("Not defined")
else:               number=int(float(number)+0.5)
if number<2:        exit("1")
elif number<5:      exit("2")
c=1
while True:
    c+=1
    if c**2 < number:   continue
    exit(str(int((c-1)*(c))/2))

TI-BASIC
Roots are usually squiggly. Let's make them square for a change. Just enter the size and watch plants grow on your calculator!
:Input A:A
:While Ans
:Ans-1
:Output(Ans,1,A
:End

Looks interesting, what does it do exactly?

@Kostronor Outputs squares in the text console of a certain size.

JavaScript (also works in ActionScript)
function sqrt(num) {
    var k = 0;
    while (k * k != num)
        { k = Math.random() * num; }
    return k;
}

The troll:

 It just keeps looping through, creating random values less than num, until it finds a value that fits the bill. May break if num <= 1.

I think you should change the while condition to k * k = num.

@PaŭloEbermann Good idea, and that's also more efficient! I implemented your suggested changes.

jQuery
This actually uses jQuery to do entire calculation. It creates a set of tags in a container (equal to the requested number), changes the width until it will be identical to height. When square root is reached, those numbers should be identical (if you have 8x8 grid, you have 64 elements, and the square root of 64 is 8). Who needs plain JavaScript, when you have jQuery, and jQuery is awesome!
function squareRoot(number) {
    // overflow: hidden is needed so the element would report real size.
    var $calculator = $('<div>').css('overflow', 'hidden');
    var i;
    var result = NaN;
    for (i = 0; i < number; i++) {
        // Floats are the easiest way to put elements that only take
        // place for themselves.
        $calculator.append($('<div>').css('float', 'left').height(1).width(1));
    }
    // The element needs to exist in document to calcualte its width.
    $('body').append($calculator);

    try {
        // Bruteforce the solution
        for (i = 1; i <= number; i++) {
            $calculator.width(i);
            if (i === $calculator.height()) {
                return i;
            }
        }
    }
    finally {
        // Clean the element after calculation. There is no need for
        // garbage to exist after calculation.
        $calculator.remove();
    }
}

Everybody's got this all wrong. This is the only valid solution (I'll use Python):
def getSqrt(int num):
    return 42

getSqrt(1764)

When running this code, the function clearly returns 42.
As it turns out, when running the code,
getSqrt(6*9)

It also returns 42. Maybe Hitchhikers got it wrong. Its not 6*9=42, it is the square root of 6*9 equals 42.

Python
import math
print math.sqrt(input())

This is code-trolling. Your answer does not seem very trollish.

@ace - i'm trolling the question by giving a correct answer

And voters are trolling you by giving you a downvote.

The troll is that it evals an user specified value, is it?

Python
This is the only answer that will terminate with an inexact answer. Time is no object when it comes to being precise!
import sys
from decimal import *
two = Decimal('2')
half = Decimal('0.5')
context=getcontext()
prec = 5
sys.stdout.write('1.414')
while True:
    prec += 1
    context.prec = prec
    sys.stdout.write(str(two**half)[-2])

Python 2.7
I quake in the presence of my betters.  Their answers are incredible.  However, I feel your learning will be incomplete if you do not see an algorithmic implementation of a square root method so simple that people have used it by hand.  Wikipedia explains this algorithm.
I have provided the following Python code as a sample implementation of the algorithm.  While Python is slower than Java (which is slower than ASM, which is slower than C), I have found that this is because the computer is being more careful with its calculations.  Combining this with Python's great readability, I believe you should use Python for every homework assignment.  If your professor tells you to use a different language, explain to him why he is wrong.
Here is this alternative square root approach:
def sqrt(z):
 v,w,y=10,0,100
 def A(x):
    a,b=D(x),[];c=x-a
    while a>w:b.insert(w,a%y);a//=y
    b.append(None)
    while c>w:c*=y;x=D(c);b.append(x);c-=x
    return b
 B=lambda x:reduce(lambda x,y:x if y is None else x*v+y,x,w)
 C=lambda x,y:(x+y)*y
 D=int
 a,b,c,d= w,[],-1,A(z);e=len(d);f=e+y
 while c+1<f and(c<e or a>w):
    c += 1
    if c<len(d) and d[c]is None:b.append(None);continue
    a*=y
    if c<e:a+=d[c]
    g=B(b)*20;h=max(filter(lambda c:C(g,c)<=a,range(v)));b.append(h);a-=C(g,h)
 return float(''.join(map(lambda x:'.' if x is None else str(x),b)))

Here are some results showing what it produces:
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
> > from random import *
> > from golfedSqrt import sqrt
> > digits = [i for i in range(11)]
> > digits.extend([random() * 1e9 + random() for i in range(10)])
> > for d in digits:
...     print "{} => {}".format(d, sqrt(d))
...
0 => 0.0
1 => 1.0
2 => 1.41421356237
3 => 1.73205080757
4 => 2.0
5 => 2.2360679775
6 => 2.44948974278
7 => 2.64575131106
8 => 2.82842712475
9 => 3.0
10 => 3.16227766017
216308371.652 => 14707.4257317
556847164.007 => 23597.6092858
106003255.816 => 10295.7882562
824923809.742 => 28721.4868999
204798557.219 => 14310.7846472
742647120.414 => 27251.5526239
199156541.747 => 14112.283364
788130088.331 => 28073.6547021
525449922.652 => 22922.6944893
529451788.497 => 23009.819393
> >

I believe the virtues of this approach are self-evident thanks to Python's strengths.

Haskell
Just as we can define recursively Fibonacci sequence
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

we can use generalized continued fractions to express a fraction that converges to the square root with ultimate precision:
import Prelude hiding (sqrt)

sqrt :: Double -> Double
sqrt x = 1 + (x - 1) / cfrac
  where cfrac = 2 + (x - 1) / cfrac

Simple and elegant.

 While the continued fraction converges, the program does not. We'd have to limit the number of recursive nesting in order to get a result.

Java (in a custom number class)
Once I did develop an implementation of arbitrary large natural numbers (= nonnegative integers) in a decimal system.
It also contained a square root method.
/**
 * Berechnet näherungsweise die Quadratwurzel dieser Zahl.<p>
 * <b>Implementation:</b>
 * Dabei wird für mehr-als-2-stellige Zahlen das
 *   Divisionsverfahren angewandt.
 * @return die größte natürliche Zahl, dessen Quadrat kleiner
 *   oder gleich dieser Zahl ist. Bei <pre>
 *  Zahl qw = Z.quadratWurzel();
 * </pre> gilt: <pre>
 *  qw * qw <= Z < (qw + 1) * (qw + 1)
 * </pre>
 * @since PPS 1.1.3
 */
public Zahl quadratWurzel()
{
    DebugMessage.print(this + ".quadratWurzel()");
    DebugMessage.begin();

    // triviale Fälle:

    if (qwurzel != null)
        return qwurzel;

    if (1 == len)
        {
            DebugMessage.end();
            return qwurzel = valueOf(zifs[start].quadratWurzel());
        }
    if (2 == len)
        {
            for (Zahl z = NEUN; ! z.equals(NULL) ; z = z.getVorgänger())
                {
                    if (z.mal(z).compareTo(this) <= 0)      // z² <= this ?
                        {
                            DebugMessage.end();
                            return qwurzel = z;
                        }
                }
        }

    int ix =
        ((len & 1) == 0) ?
        len - 2 :
        len - 1;
    int restLen = len;

    // hier kommt das Ergebnis hinein:
    Ziffer[] wuZifs = new Ziffer[(len+1)/2];        // nur halb so viele Ziffern!
    int wuIx = wuZifs.length - 1;

    Zahl anfang = valueOf(this, ix);        // höchstens 2 Ziffern
    DebugMessage.print("anfang = " + anfang);
    Zahl a = anfang.quadratWurzel();        // "=> höchstens 1 Ziffer!
    anfang = a.mal(a);                      // a²
    DebugMessage.print("anfang = " + anfang);
    wuZifs[wuIx] = a.getZiffer(0);

    Zahl rest = this.minus(anfang.shl(wuIx * 2));

    while (--ix > 0)
        {
            DebugMessage.begin("while-Schleife-Körper ...");
            DebugMessage.print("rest = " + rest + ", ix = " + ix);
            DebugMessage.print("wuZifs = " + JavaTools.ar2Str(wuZifs) +
                               ", wuIx = " + wuIx);
            Zahl ergBisher = valueOf(wuIx, wuZifs.length - wuIx, wuZifs);
            DebugMessage.print("ergBisher = " + ergBisher);
            Zahl restTeil = valueOf(rest, ix);
            DebugMessage.print("restTeil = " + restTeil);
            Zahl divisor = ergBisher.mal(ZWEI);
            DebugMessage.print("divisor = " + divisor);
            Zahl nextZif = restTeil.intDurch(divisor);
            DebugMessage.print("nextZif = " + nextZif);
            ix --; wuIx --;
            DebugMessage.print("ix = " + ix + ", wuIx = " + wuIx);
            wuZifs[wuIx] = nextZif.getZiffer(0);
            DebugMessage.print("wuZifs = " + JavaTools.ar2Str(wuZifs));
            Zahl subtr = divisor.mal(ZEHN).plus(nextZif).mal(nextZif).shl(wuIx * 2);
            DebugMessage.print("subtr = " + subtr);
            while (subtr.compareTo(rest) > 0)
                {
                    nextZif = nextZif.getVorgänger();
                    DebugMessage.print("nextZif = " + nextZif);
                    wuZifs[wuIx] = nextZif.getZiffer(0);
                    DebugMessage.print("wuZifs = " + JavaTools.ar2Str(wuZifs));
                    subtr = (divisor.shl(1).plus(nextZif)).mal(nextZif).shl(ix);
                    DebugMessage.print("subtr = " + subtr);
                }
            rest = rest.minus(subtr);
            DebugMessage.end("Ende while-Schleife-Körper");
        }
    Zahl erg = new Zahl (0, wuZifs.length, wuZifs);
    DebugMessage.end();
    return qwurzel = erg;
}

The whole method works as specified: Z.quadratWurzel() returned a natural number qw such that qw * qw <= Z < (qw + 1) * (qw + 1), i.e. qw = ceil(sqrt(Z)).
I won't post the whole Zahl class here, just an outline:

a Zahl (german for "number") consists of an array of (decimal) digits (Ziffer) and an offset + length into it (the idea copied from the String class).
All of the basic and some not-so-basic methods were implemented, based on methods of the Ziffer class, and with algorithms just like humans would do the arithmetic on paper or in their heads (or at least how I learned them in elementary school.)
There even was a prime factorization algorithm in there (based on a way I was using in my head to factor around 4-digit numbers – a variant of trial division, I suppose.)

I actually never did learn any square root algorithm in school, but I found a description in the notes of my sister, whose math teacher did instruct this algorithm (10th grade or similar, I think), and implemented it here. I think it is a specialization (for n=2) of the algorithm explained at Wikipedia's Shifting nth root algorithm article.
Some hints for understanding the code:

quadratWurzel is german for square root.
The DebugMessage class is used just for debugging goals – I could plug several implementations, one which printed to the console or a file and changed indentation levels with begin() and end(), another one filling a Swing JTree with the messages. You should be able to ignore it (or try translating the messages to use it as comments). JavaTools.ar2Str was an array-to-string formatting function I wrote before there was Arrays.toString(). Of course both Zahl and Ziffer have a useful toString() method.
zifs is the array of digits (which might be shared with other Zahl instances), len is the number of digits used by our number, start is the offset in this array where our digits start. The digits are sorted in little-endian way in the array. getZiffer() is a method accessing one of the digits.
We see use of most basic operations (implementation not included, but you can replace them by operations on primitives ints):

plus means "plus", this is the addition method. Replace a.plus(b) by a + b.
minus means "minus", this is the subtraction method. Replace a.minus(b) by a - b.
mal means "times", this is the multiplication method. Replace a.mal(b) by a * b.
intDurch() is integer division (ignoring the remainder). Replace a.intDurch(b) by a / b. (There is another division method which throws an exception if it is not dividable.)
"Vorgänger" means "predecessor", so z = z.getVorgänger(); would z--; with ordinary primitive types.
shl = shift left is shifting the number left by some number of (decimal) digits, effectively appending zero digits at the end, or multiplying with a power of ten.
Zahl.valueOf(Zahl, int start) is one of several factory methods. This one works like a substring-like function, cutting away the lowest-value start digits. This effectively divided by 10^start, discarding the remainder.

We have some special-casing for one- and two-digit numbers.

NULL, EINS, ZWEI, ... to NEUN, ZEHN are constants for the numbers zero to ten.

there is some recursion, but only for the first one or two digits (which are special-cased anyways), to get started.
We use the wuZifs array to collect the result digits.
I don't really understand anymore what is going on in the main loop, all that debug output is obfuscating what happens, and I'm too tired. Read the Wikipedia article for details.
We are caching the value in the qwurzel field to avoid calculating it more than once for a given number instance.
erg is short for "Ergebnis", the result.

!  If I now found that kind of code anywhere near a production environment, I would consider sending it to TheDailyWTF. Luckily I know it never was used for any goals other than my own learnings. And even those were more than ten years ago, I think even around fifteen.
!  See Creating a simple Big number class in Java for a later attempt at a more sane implementation of "big decimal-based integers, though I didn't implement square roots there.

Is the troll that most users cannot understand your comments or variable names?

authors: Максим Повержук

authors: Святой Вельзевул


text:
Almost Equilaterial Heronian Triangles
An Almost Equilateral Heronian Triangle is a triangle with integer lengths of the form n-1, n, and n+1 and also has integer area. The first few are:
 3,  4,  5 ->    6
13, 14, 15 ->   84
51, 52, 53 -> 1170

Quest: Generate the shortest program that outputs the nth such triple. (Hint: this is a known sequence).
Winner will be selected on May 2, 2014.

For what it's worth, this is equivalent to one of the more widely studied Pell equations.

I don't really understand the downvotes. This is a fairly simple task but I don't see any problem with the question. But I have to say (as a left handed person) that the restriction is one of the weirdest and easiest to comply with I have ever seen.

@steveverrill, although I didn't downvote I did choose not to upvote because of the pointless restriction. I suspect that the close votes are also because of the restriction: I bet that less than 10% of the world's population use the same keyboard layout as Kyle.

I would upvote without the restriction.

@TheDoctor: Restriction removed. I had thought that it would make it interesting, but given the comments above it seems this is not the case.

i liked the restriction @KyleKanos, even though left-handed people disgust me

@ardnew Of all the places, this is one of the least likely I would expect such handist comments :P

APL, 15 14 charaters
0 1 2+⌊⎕*⍨2+√3

Same approach as alephalpha's solution but uses floor instead of the correction term.
Thank you to algorithmshark for pointing out that the commute operator saves one char.

(⍳3) saves a char over 0 1 2, and I'm pretty sure you can use Commute to make it ⎕*⍨2+√3 and save another.

@algorithmshark Thank you for those ideas. Unfortunately ⍳3 yields 1 2 3 and thus is one char longer.

Mathematica, 26, 22, 16 18 chars
{0,1,2}+⌊(2+√3)^n⌋

A bit too much golfing: it won't work in the current form (see here).

GolfScript (24 21 chars)
2 4@~{.4*@-}*;.(\.)]p

Takes input on stdin, gives output to stdout in the form
[3 4 5]

Online demo
Note that I've assumed that the 0th element of the sequence is [1 2 3] (with area 0), which I think is consistent with OEIS A003500.
With thanks to Howard for a 3-char saving.

Using (.).)] is two chars shorter. Moreover, if you start with 2 4 you can replace \; with ; and save an additional one.

@Howard, I originally had 2 4 and treated [3 4 5] as the 0th element, so I'm embarrassed not to have spotted that alternative way to exploit the offset. Thanks.

GNU dc, 30 19 bytes
9k3v2+?^0k1/p1+p1+p

This uses the same trick as @Howard's APL answer so only one term has to be calculated.  Takes input for n from stdin.
Output:
$ dc -e '9k3v2+?^0k1/p1+p1+p' <<< 1
3
4
5
$ dc -e '9k3v2+?^0k1/p1+p1+p' <<< 2
13
14
15
$ dc -e '9k3v2+?^0k1/p1+p1+p' <<< 3
51
52
53
$

Python 77
Quite a verbose implementation in Python
[(a-1,a,a+1)for a in(int((2+3**.5)**t+(2-3**.5)**t+.1)for t in range(N))][-1]

Are we supposed to replace N with a value? Your program doesn't ask for any input.

Python 3, 83 characters
f=lambda t:4*f(t-1)-f(t-2)if t>2 else(4,14)[t-1];n=f(int(input()));print(n-1,n,n+1)

This uses a recursive solution, taking advantage of the fact that (quote from Wikipedia):

Subsequent values of n can be found by multiplying the previous value by 4, then subtracting the value prior to that one (52 = 4 × 14 − 4, 194 = 4 × 52 − 14, etc.)

JavaScript (ECMAScript 6) - 52 Characters
f=x=>x?--x?4*f(x)-f(x-1):4:2
g=x=>[a=f(x)-1,a+1,a+2]

Defines a recursive function f which returns the nth term and a function g which returns an array containing the corresponding triple.
JavaScript - 41 Characters
for(a=2,b=4;--x;)b=-a+4*(a=b);[a-1,a,a+1]

Expects the term to be calculated to be stored in the global variable x and outputs the triple to the console.

CJam, 13 bytes
3,3mq))ri#if+p

The first version of CJam is 10 days older than this challenge, but I don't know if all of the features I'm using have been present back then. The challenge is officially closed anyway though, so...
Test it here.
Explanation
3mq            e# Push √3.
   ))          e# Increment twice.
     ri        e# Read input and convert to integer.
       #       e# Raise 2+√3 to that power.
        i      e# Convert to integer, truncating the result.
         3,    e# Push [0 1 2]
           f+  e# Add the previous number to each of these.
             p e# Pretty-print the result.

source: Stack Exchange

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

sort: votes


text:
Line up the CSV
Overview:
Your job is to take CSV input in key=value format and line it up in a more organized (see below) way.
Input:
Always via stdin. Records will always be in the following form key=value:
foo=bar,baz=quux
abc=123,foo=fubar
baz=qwe,abc=rty,zxc=uiop,foo=asdf

There will be no list of possible keys in advance, you must find them in the input text.
End of input will be signalled by EOF, whatever implementation of EOF is appropriate for your OS.

Output:
The first row of your output will be a list of all the keys, in alphabetical order (even if the keys are all numbers).
After that, print each record in the same CSV format the appropriate number heading, without the keys listed. So, for the example above, the correct output would be:
abc,baz,foo,zxc
,quux,bar,
123,,fubar,
rty,qwe,asdf,uiop

FAQ:

Do I have to worry about improperly formatted input?

No. Your program may do whatever it wants (throw an exception, ignore, etc.) if the input is not correctly formatted, e.g. a line of foo,bar,baz

How do I handle escaping special characters?

You may assume that there will be no additional , or = in the data that are not part of the key=value format. " does not have any special meaning in this contest (even though it does in traditional CSV).  is also not special in any way.
Lines should match the following regex: ^([^=,]+=[^=,]+)(,[^=,]+=[^=,]+)*$

Therefore, both keys and values will match [^=,]+

What about CRLF vs. LF?

You may choose whatever delimiter is appropriate for your platform. Most languages handle this without special delimiting code.

Do I need to print trailing commas if the last few columns don't exist?

Yes. See the example.

Are CSV parsers or other similar external tools allowed?

No. You must parse the data yourself.

FAQ when no one asked questions yet. :-)

@Quincunx If I ask myself the question that counts ;)

I have a feeling that's how all FAQs work.

Can I have a trailing comma in my list of keys and values? It would make my code a lot shorter...

@PlasmaPower I don't understand the question; however, your program must exactly match the example output for the given example input

@drewbenn Fair, except I think at this point that would be a rule change

GolfScript, 64 characters
n%{','/{'='/}%}%:I{{0=}/}%.&$:K','*n{`{{(2$=*}%''*\;}+K%','*n}I/

The code is a straight-forward implementation in GolfScript, you can test the example online.
Annotated code:
# Split the input into lines, each line into tuples [key, value]
# and assign the result to variable I
n%{','/{'='/}%}%:I

# From each tuple take the 0'th element (i.e the key)
{{0=}/}%

# Take the unique items (.&), sort ($) and assign the result to variable K
.&$:K

# Output: join values with , and append a newline
','*n

# {...}I/: Loop over all lines of the input
{

  # `{...}+K%: Loop over all keys and initially push the current
  # line for each of the keys
  `{
    # stack here is [current key, current line]
    # {}%: map to all the items of the current line
    {
      # extract the key from the current item and compare
      (2$=
      # if equal keep [value], otherwise multiply with 0, i.e. discard
      *
    }%
    # join the results (may be one or zero) and drop the key
    ''*\;
  }+K%
  # Output: join values of current line with , and append a newline
  ','*n
}I/

perl, 129/121
129 bytes, no command line switches:
for(<>){push@x,{%g=map{split/=/}split/[,
]/};@h{keys%g}=()}@k=sort keys%h;$"=",";sub P{print"@_
"}P@k;for$x(@x){P map{$$x{$_}}@k}

As @Dennis points out below, you can get this to 120+1=121 by using -n:
push@x,{%g=map{split/=/}split/[,
]/};@h{keys%g}=()}@k=sort keys%h;$"=",";sub P{print"@_
"}P@k;for$x(@x){P map{$$x{$_}}@k

Basically, for each line, we split by commas to get the list of pairs. For each pair, we split by the equals sign to get the key and value. We set the key/value pair in %h and a local hashref. The former is used to determine the list of keys. The latter is used to remember the values for this line.

You can save a few chars by: 1. Using the -n switch instead of for(<>){...}. 2. Splitting around [,                                                                                ] instead of using chomp. 3. Omitting the semicolon after the curly brackets.

Thanks @Dennis. I've implemented the latter 2 of your suggestions. I may yet throw -n in to the mix but I'm feeling like a purist who is too lazy to type on his phone ATM :-) Also that would require an END block, but I suppose it'd still be a net win.

Yeah, adding -n only saves 3 chars (two points) with the END block. I prefer the "purer" solution. At least until one of the other answers gets closer =)

Perl literally wraps while (<>) { ... } around the entire script, so there's no need for an END block. Just remove for(<>){ at the beginning and } at the end of the script.

@Dennis your comment, for me and at least one other, cause the other comments to pickle and bleed into the Hot Network Questions. I've reported it on the new MSE. Firefox 28 and IE 11 at least.

@BillWoodger: I guess I shouldn't use newlines between backticks. It looks fine in Chromium (Fedora), but Firefox doesn't seem to like it.

@Dennis, that's not identical. The for(<>){} loop only goes around about half of the code, specifically up to the end of this: 'for(<>){push@x,{%g=map{split/=/}split/[,\n]/};@h{keys%g}=()}' only

It will work nevertheless, as long as you remove the } at the end of the script, not the one corresponding to the for loop. Also, you can save one more char by using an actual newline instead of \n.

Dennis, wow. I didn't realize you could "escape" out of the implicit loop like that.

Perl 6: 119 characters, 120 bytes
my@l=lines.map:{/[(\w+)\=(\w+)]+%\,/;push $!,~«@0;$%(@0 Z=>@1)}
say .join(",") for$!.=sort.=uniq,($(.{@$!}X//"") for@l)

De-golfed:
my@l=lines.map: {
    # Parse the key=value pairs,
    # put all the keys in $/[0] (or $0)
    # put all the values in $/[1] (or $1)
    / [ (\w+) \= (\w+) ]+ % \, /;

    # Push all the keys into $!
    # (@0 just means @$0 or $/[0].list)
    push $!, ~«@0;

    # Return a hash of keys zipped into pairs with the values
    $%( @0 Z=> @1 )
}

$!.=sort.=uniq;
# …i.e., $! = $!.sort.uniq;

# Print the CSV for the keys ($!),
# followed by the CSVs for the hashes we made for each line,
# as accessed by our sorted key list. (… .{@$!} …)
# If the value doesn't exist, just use "" instead. (… X// "" …)
say .join(",") for $!, ($( .{@$!} X// "" ) for @l)

JavaScript (ES5) 191 183 179 168 bytes
Assuming the code is run in spidermonkey command line:
for(b=[a={}];l=readline(i=0);b.push(c))for(c={},d=l.split(/,|=/);e=d[i++];)c[a[e]=e]=d[i++];for(;c=b[i++];)print(Object.keys(a).sort().map(function(x){return c[x]})+[])

Result:
> js test.js < input.txt
abc,baz,foo,zxc
,quux,bar,
123,,fubar,
rty,qwe,asdf,uiop

This shim can be used in a browser to simulate spidermonkey's readline and print:
var I = 0, LINES = '\
foo=bar,baz=quux\n\
abc=123,foo=fubar\n\
baz=qwe,abc=rty,zxc=uiop,foo=asdf'.split('\n'),
readline = function(){
    return LINES[I++];
}, print = function(){
    return console.log.apply(console, arguments);
};

Ungolfed:
a = {};                        // this object holds all keys found
b = [a];                       // array key:value pairs of each line, initialized with our key holder object in position 0
for(;l = readline();){         // store each line in l, loop until blank/undefined line
    c = {};                    // create a new object for this line's key:value pairs
    d = l.split(/,|=/);        // split line by commas and equals
    for(i = 0; e = d[i++];){   // loop through each key
        a[e] = e;              // set the key=key for key holder object
        c[e] = d[i++];         // set key=value for the line object
    }
    b.push(c);                 // push line object onto array
}
for(i = 0; c = b[i++];){       // loop through all line objects until undefined
    print(                     // print line
        Object.keys(a).sort(). // get sorted list of keys
        map(function(x){
            return c[x]        // map values from line object
        })
        + []                   // cast array to string
    );
}

The question doesn't say that you have to use "stdout" - you can use alert in place of console.log and save some bytes thus.

@GaurangTandon Then, I'd have to concatenate all the outline lines. I might update my answer to use spidermonkey command line and instead use readline and print for actual stdin/out

Bash + coreutils, 188 138 bytes
p=paste\ -sd,
f=`cat`
h=`tr , '\n'<<<$f|cut -d= -f1|sort -u`
$p<<<"$h"
for l in $f;{
join -o2.2 -a1 - <(tr =, ' \n'<<<$l|sort)<<<"$h"|$p
}

Output:
$ ./lineupcsv.sh < input.csv
abc,baz,foo,zxc
,quux,bar,
123,,fubar,
rty,qwe,asdf,uiop
$

Haskell, 357 334
import Data.List
o=1<2
s u|u==""=""|o=tail u
t=takeWhile
d=dropWhile
c=(/=',')
e=(/='=')
p x|x/=""=Just((t e x,t c.s.d e$x),s.d c$x)|o=Nothing
g=m(unfoldr p).lines
k=nub.sort.(m fst=<<).g
[]#_=[]
(t@(x,u):z)#n@(a,b)|x==a=n:z|o=t:z#n
i=intercalate
main=interact$ \d->i"\n"$(i","$k d):m(i",".m snd.foldl(#)(m(flip(,)"").k$d))(g d)
m=map

g is doing the parsing - it splits the input into lines and maps each line to a list of (key,value) pairs. k, by concatenating all the keys into a list and removing duplicates, creates a list with all unique keys which I can later use for sorting. I do this by creating a "Set" inside main (m(flip(,)"").k$d == [("abc",""),("baz",""),("foo",""),("zxc","")]) for each line, and then taking every (key,value) pair from a line and put it where it belongs in the list (foldl).
Line 1 from the example yields [("abc",""),("baz","quux"),("foo","bar"),("zxc","")], which I concatenate into a single String (",quux,bar,"), concatenate with the other lines, and print.
>>> csv.exe < input.txt
abc,baz,foo,zxc
,quux,bar,
123,,fubar,
rty,qwe,asdf,uiop

Python 2.7 - 242 bytes
bleh
import os
c=[r.split(',')for r in os.read(0,99).split('\n')]
k=sorted(list(set(sum([[s.split('=')[0]for s in r]for r in c],[]))))
print','.join(k)
for l in c:
 t=[''for i in k]
 for s in l:
    o,v=s.split('=')
    t[k.index(o)]=v
 print','.join(t)

Note that the second layer of indentation is a single tab character, not four spaces like SE renders it.
Ungolfed:
#!/bin/python2

import os

# I do input as a list comprehension in the original but this is equivalent
c = []

# For each line in the input
for r in os.read(0,99).split('\n'):
    # Add a list of key=value pairs in that row to c
    c.append(r.split(','))

# Another thing done as a list comprehension, but I'll space it out
k = []

# For each list of key=value pair s in c
for r in c:
    # For each actual key=value pair in that list
    for s in r:
        # Get the key
        k.append(s.split('=')[0])

# Discard dupes by converting to set and back, then sort
k = sorted(list(set(k)))

# Seperate these keys by commas, then print
print ','.join(k)

# For each line in c
for l in c:
    # t has one empty string for each key in the input
    t = ['' for i in k]
    # For each key=value pair in the line
    for s in l:
        # o = key, v = value
        o, v = s.split('=')
        # Find the position that the key is in the list of keys, then put the
        # value in t at that position
        t[k.index(o)] = v

    # Now each value is in the right position and the keys with no values on this
    # line have an empty string. Join everything with commas and print
    print ','.join(t)

C# - 369
(in LINQPAD)
void C(string a){var k=a.Split(new[]{',','\n'}).Select(s=>s.Split('=')[0]).OrderBy(o=>o).Distinct();var t=string.Join(",", k)+"\n";foreach(var x in a.Split('\n')){for(int i=0;i<k.Count();i++){foreach(var y in x.Split(',').OrderBy(o=>o.Split('=')[0]))if(k.ElementAt(i)==y.Split('=')[0])t+=y.Split('=')[1];t+=",";}t=t.Remove(t.LastIndexOf(','),1)+"\n";}Console.Write(t);}

Ungolfed
void C(string a)
{
    var k=a.Split(new[]{',','\n'}).Select(s=>s.Split('=')[0]).OrderBy(o=>o).Distinct();
    var t=string.Join(",", k)+"\n";
    foreach(var x in a.Split('\n'))
    {
        for(int i=0;i<k.Count();i++)
        {
            foreach(var y in x.Split(',').OrderBy(o=>o.Split('=')[0]))
                if(k.ElementAt(i)==y.Split('=')[0])
                    t+=y.Split('=')[1];
            t+=",";
        }
        t=t.Remove(t.LastIndexOf(','),1)+"\n";
    }
    Console.Write(t);
}

Test string input
C("foo=bar,baz=quux\nabc=123,foo=fubar\nbaz=qwe,abc=rty,zxc=uiop,foo=asdf");

Output
abc,baz,foo,zxc
,quux,bar,
123,,fubar,
rty,qwe,asdf,uiop

Just curious, this is C# so it should work in windows, but does it? (See my CRLF vs. LF FAQ question) Unfortunately I don't have a copy of Visual Studio to test with.

I originally should have added the note, but i have now. Yes it works. I've created & tested it in linqpad. I haven't tested it in console app, but there isn't any reason why it wouldnt work. But a console app would obviously add more bytes to the code.

Python 3: 200 195 192 189 187
import sys
r=[dict(p.split('=')for p in l[:-1].split(','))for l in sys.stdin]
x=set()
for d in r:x|=d.keys()
k=sorted(x)
for l in[k]+[[r.get(k,'')for k in k]for r in r]:print(*l,sep=',')

k4 (40? 51? 70? 46?)
the basic expression is
","0:{(x@<x:?,/?!:'x)#/:x}(!).'"S=,"0:/:

this both accepts and returns a list of strings
to match the spec, we could interactively do
-1","0:{(x@<x:?,/?!:'x)#/:x}(!).'"S=,"0:/:."\\cat";

which accepts the input from stdin and prints the output to stdout
for a standalone app accepting input from a pipe, we could do this:
$ cat i.k
.z.pi:{t,:`\:x}
.z.exit:{-1","0:{(x@<x:?,/?!:'x)#/:x}(!).'"S=,"0:/:t}
$ cat i.txt|q i.k
abc,baz,foo,zxc
,quux,bar,
123,,fubar,
rty,qwe,asdf,uiop
$

altho if you're willing to consider my pre-existing k-as-filter wrapper, awq.k, as an acceptable tool for this kind of puzzle, then we can do this:
$ cat i.txt|awq.k '","0:{(x@<x:?,/?!:'\''x)#/:x}(!).'\''"S=,"0:/:'

which is either 46 characters or 40, depending on how you count shell quote wrangling

What kind of environment is needed to run this?  q command?  Is awq.k published somewhere?

32-bit q is now available as freeware from http://kx.com/software-download.php. (they used to have only a time-limited trial version for free.) hmm, it looks like awq isn't actually published anywhere; i should do something about that.

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