[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
Closed 9 years ago.
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
> 
> 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!
  
[Answer]
# 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.print`s 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`)?:![enter image description here](https://i.stack.imgur.com/kVSdR.png)
* 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.
[Answer]
# 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 `union`ing 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`.
[Answer]
# 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.
> 
> 
> 
[Answer]
In Python 3 you can do the following:
```
def square_root(n):
return float(n)**0.5
```
[Answer]
Correcting [this answer](https://codegolf.stackexchange.com/a/26110/7162),
> 
> 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.
> 
> 
> 
[Answer]
## 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)
[Answer]
# 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];
}
```
[Answer]
# 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](http://en.wikipedia.org/wiki/Fast_inverse_square_root).
> 
> 
> 
[Answer]
# 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
```
[Answer]
# 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;`
> 
> 
> 
[Answer]
# Julia
Obviously the best way to do it, its using the squared root Taylor Series:
![enter image description here](https://i.stack.imgur.com/787IB.png)
```
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   
```
[Answer]
# 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`:
![Does the same as the simple program written in Ook!](https://i.stack.imgur.com/sGtZu.gif)
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.
[Answer]
# 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](https://www.google.at/search?q=399999999999999+-+399999999999998&oq=399999999999999+-+399999999999998&aqs=chrome..69i57j0.143j0j4&sourceid=chrome&es_sm=93&ie=UTF-8), 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.
[Answer]
## Java
The most precise way to do this is to iterate. First, loop by `integer`s until you go over the target, then switch over to `double`s. 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.
> 
> 
> 
[Answer]
# 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']`
> 
> 
> 
[Answer]
## 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`
[Answer]
## 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators).
> 
> 
> 
[Answer]
## 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](http://en.wikipedia.org/wiki/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](https://www.youtube.com/watch?v=uw1S4LtlZe8)
[Answer]
# 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!
[Answer]
# 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
* `for`loop 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)
[Answer]
# 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!
![enter image description here](https://i.stack.imgur.com/YoGVg.png)
[Answer]
## 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;
}
```
[Answer]
# 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;
}
```
[Answer]
## 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](http://adrianiainlam.github.io/squareroot.html) (requires Java), or enjoy some screenshots below:
![enter image description here](https://i.stack.imgur.com/9w3zE.png) ![enter image description here](https://i.stack.imgur.com/djH78.png)
[Answer]
### 100% pure [bash](/questions/tagged/bash "show questions tagged '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!!
[Answer]
# Java
Thanks, to [ggmx's for code on generating n digits of pi in java](https://stackoverflow.com/a/17899007/3024116). 
```
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.](http://www.askamathematician.com/2009/11/since-pi-is-infinite-can-i-draw-any-random-number-sequence-and-be-certain-that-it-exists-somewhere-in-the-digits-of-pi/)
[Answer]
# 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 = "&radic;" +a ;
document.write(a);  
});
</script>
```
Here is a [fiddle](http://jsfiddle.net/c42e8/1/)
[Answer]
## 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.
[Answer]
## Python
This solution:
1. is non deterministic and yields approximate answers
2. is O(N) and quite slow, even for low N
3. 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)))
```
[Answer]
# 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;}
```
]