title: Help!! How to do square root!

text:
# Question
Title: 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!

# Answer
> 120 votes
# 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`)?:
* 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
> 71 votes
# 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
> 64 votes
# 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
> 45 votes
In Python 3 you can do the following:

```
def square_root(n):
return float(n)**0.5

```

# Answer
> 42 votes
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.

# Answer
> 39 votes
## 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
> 33 votes
# 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
> 30 votes
# 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.

# Answer
> 29 votes
# 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
> 28 votes
# 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
> 25 votes
# 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

```

# Answer
> 20 votes
# 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.

# Answer
> 20 votes
# 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.

# Answer
> 16 votes
## 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
> 11 votes
# 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
> 10 votes
## 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
> 10 votes
## 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.

# Answer
> 9 votes
# 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
> 9 votes
## 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** **y<sup>2</sup> = 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

# Answer
> 8 votes
# 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!

# Answer
> 8 votes
# 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
> 7 votes
## 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 e<sup>e</sup>, and so on. In this way, what you might on a binary machine call a bit-shift to the left performs x =\> e<sup>x</sup>, 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
> 6 votes
# 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
> 6 votes
## 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:

# Answer
> 6 votes
### 100% pure (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
> 4 votes
# 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.

# Answer
> 3 votes
# 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

# Answer
> 3 votes
## 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
> 3 votes
## 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
> 3 votes
# 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;}

```

# Answer
> 2 votes
## 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.

# Answer
> 2 votes
**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))

```

# Answer
> 2 votes
## 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

```

# Answer
> 2 votes
## 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`.

# Answer
> 2 votes
# 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();
    }
}

```

# Answer
> 1 votes
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.

# Answer
> 0 votes
# Python

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

```

# Answer
> 0 votes
# 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])

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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 `n`th 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.

# Answer
> 0 votes
# 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.

---
Tags: popularity-contest, code-trolling
---


title: An improved version of GolfScript

text:
# Question
Title: An improved version of GolfScript
I am planning to write an improved GolfScript for even shorter programs that can do more things. This is not a challenge; it is a request for feedback and tips on what I should do. (see tags)

I'm not sure if this should be Community Wiki. If you think so, just flag for a moderator to convert it :)

This language will be very similar to GolfScript. It is still written in Ruby. However, it has a few differences:

* Using ``` as a string delimiter, because it's an uncommon character, so less escaping will be needed. (Another character can replace its function, like `#` (more on that later)). `\`` to escape a backtick, `\\` to escape a backslash, and there are no other escape sequences. If you need a newline, just stick an actual literal newline in the string.
* Using Ruby's `Rational`s for arbitrary precision floating point, one of GolfScript's major flaws.
* The ability to convert types to other types. For example, you can convert a block to a string.
* Regular expressions. Probably created with `"..."`. Operators will be overloaded for them as well. For example, `"\W"~{`Invalid: non-word character`}{`OK`}if`. Will automatically execute when pushed from a variable, like blocks.
* File and Date objects, to do more stuff that was impossible in GolfScript. These will not have literals, but will have functions for initializing them, such as ``file.txt`fl` (name of the file-making-function may change).
* Hashes maybe, but I'm not sure on that one. Should I?
* Helper functions to do even more. For example, ``http://example.com`net` for network access (again, `net` operator may be renamed). `rb` to execute a string as Ruby code. There will be many more of these; suggestions welcome.
* No comments, so that `#` can be used for something else. If you want a comment, ``comment here`;` will work fine. (Maybe `#` can replace ```'s function)
* It will be completely rewritten in a way that it will be much easier to add functions. Basically, the code will be more readable. (Have you seen the GolfScript source? `:/`)
* It will be on Github so it can be collaboratively worked on. I'll license it under MIT or something.
* No final newline, so cheaty quines work :P

And I'm setting these apart because I think they're the most drastic and helpful changes (except maybe adding floating point):

* It will have many Ruby functions built-in. For example, `shuffle` (which may be abbreviated to `sf`) (previously took 9 characters), `tr` (previously 14 chars), `sample` (`sm`, previously `.,rand=`), `flatten` (`fl`, previously ???), etc.
* It will be mushed, like Rebmu. For example, now you can do `~:a0<{0a-}aIF` (using a letter variable name) instead of `~:$0<{0$-}$if` (overwriting the sort function). (example from here). Note that this way, it is case-insensitive, and numbers are not allowed in variable names. This is okay in my opinion since it's a golfing language :P
* It will have debugging. I will add the ability to supply a flag specifying array delimiters, element delimiters, etc., number output (rational, float, or int?), stepping through instructions one at a time, tokenizing and outputting each token instead of running the program, etc.

So, my question is: **what is there to improve?** What do you think I should add?

Any other ideas for this, before I start coding it?

# Answer
## Flexible I/O

Golfscript cannot at present be used for interactive programs. I propose some functions for explicit input be added (i.e. `readline`, `getchar` and friends). The interpreter should see if the program uses these before running it.

If the program does not call any input functions, the interpreter should act like Golfscript normally does.

I wouldn't expect the interpreter to detect input functions in eval'ed code generated at runtime, but if it somehow can do that, kudos.
> 17 votes

# Answer
## Shorter built-ins

Single-character aliases for all of the built-in commands which don't have them. I would use `base` a lot more if it were just `B`.
> 11 votes

# Answer
## Combined div-mod

This is a bit more niche than some of the suggestions, but when working on number-theoretic programs I frequently find myself wanting an operation which pops two integers `a` and `b` from the stack and pushes `a/b` and `a%b`. (At present this is `1$1$/@@%`).
> 9 votes

# Answer
### Numbers

Change the lexer such that leading 0 is not part of a number:

```
# current behaviour
01     # -> 1

# new
01     # -> 0 1

```

Also negative numbers should be written with `_` instead:

```
# current behaviour
1 2-3   # -> -1 3

# new
1 2_3     # -> 1 2 -3

```
> 8 votes

# Answer
## Access to the whole stack

GolfScript is a stack-based language, but access to all but the top three items on the stack is limited to `<integer>$` to copy the nth item. It would be useful to have something like PostScript's `roll` command so that it's easier to work with more than three "live" variables.

Ideally there would be one-arg and two-arg versions, but if there aren't enough names around then the one-arg should get preference for a one-character one.

The one-arg one just takes the number of items to roll. E.g. `1 roll` does nothing; `2 roll` is equivalent to `\`; `3 roll` is equivalent to `@`; `4 roll` and for higher numbers doesn't have an existing equivalent; the closest that's possible is something like

```
]-4/()\+\+[]*-1%~

```

(and that doesn't even handle non-integers at certain positions on the stack, or active `[`, and almost certainly breaks inside loops too).

The two-arg one also takes an amount to roll; `a b roll2` is equivalent to `{a roll}b*`.
> 8 votes

# Answer
# CJam

I have implemented "an improved GolfScript" and it is called CJam - http://sf.net/p/cjam
Now at the second release (version 0.6) it already has many if not most of the features discussed here. I'll try to list them:

* still written in Ruby - nope, java
* using ``` as a string delimiter - no, but it uses double-quoted strings with minimal escaping (`\` escapes only `\` and `"`)
* floating point - supported, but only standard "double", not arbitrary precision
* convert types to other types - yes
* regular expressions - not yet, but planned; will use regular strings with special operators
* File and Date objects - no, but can get the current date/time
* hashes - assuming those are like python dicts or java maps, then they're not supported (may consider in the future)
* helper functions to do even more - yes, a lot
* ``http://example.com`net` \- `"example.com"g`
* execute a string as Ruby code - nope
* no comments - exactly, `#` used for something else, `"comments like this";`
* easier to add functions - I think so, but I'm also biased :)
* on Github - even better (in my opinion, please don't shoot) - on SourceForge, using hg
* licensed under MIT - yes
* no final newline - right
* shuffle - `mr`
* tr - `er`
* sample - not done, `_,mr=`
* flatten - not done, but probably easier to achieve
* mushed - nope, but identifiers don't need to be separated
* debugging - only stack traces, and `ed` operator for showing the stack
* flexible I/O - yes, but **only** explicit input
* shorter built-ins - yes, `b` = base, `z` = zip
* separate leading 0 - no, but can use predefined variables
* disambiguate `-` \- yes, but not with `_`; `1 2-3` -\> `1 2 -3`; `1 2m3` -\> `-1 3`
* roll/rotate the stack - nope
* array set - `t`
* divmod - `md`
* change the lexer (for identifiers) - yes, more below
* cartesian product - not exactly the same, but yes, `m*`
* unicode operators - no
* single-character identifiers - predefined operators have 1 or 2 characters and variables are single-character uppercase letters; they can all be concatenated without confusing the lexer/parser
* operators on blocks - no
* stable sort - yes
* turn symbols back into code blocks - no, but may add later
* current date/time - `et`
* command line args - `ea`
* clearly separating built-ins - yes, but capitals are variables; built-ins are or start with lowercase and special characters
* min and max - yes, currently only for 2 values: `e<`, `e>`
* absolute value - `z` (GolfScript has `abs`, not lacking)
* sum and product of an array - `:+`, `:*`
* Manhattan distance - nope
* chr - `c` (converts to a character, not a string)
* spill a string onto the stack - CJam strings are made of characters, not numbers; to spill the characters it's still `{}/`
* a version of `:` that consumes what is stored - nope
* operators for `>=`, `<=` \- nope, use `<!`, `>!`
* base64 and zlib - nope
* shortcuts for 1$, 2$, 3$, 4$, 5$ - nope
* copy the top two stack items - planned; for now use `1$1$`
* local variables - nope
* HQ9+ features - no, thank you

CJam has a lot more features, check out https://sourceforge.net/p/cjam/wiki/Operators/
> 8 votes

# Answer
## Change the lexer

GolfScript's lexer treats a Ruby identifier (anything which matches the regex `[_a-zA-Z][_a-zA-Z0-9]*`) as a single token. If it instead treated `[a-zA-Z]+` as a token that would free up `_` to be a built-in and would allow an alpha variable to be followed by a literal integer without separating whitespace.
> 6 votes

# Answer
## Unicode aliases

Multiple-character commands could have unicode aliases. This would save on the score when the score is counted in characters and not in bytes.
> 5 votes

# Answer
### Stable sort

The `$` builtin on blocks should perform a stable sort.
> 5 votes

# Answer
### Array set operator

```
["A" "B" "C" "D" "E" "F"] -1 4 S    # -> ["A" "B" "C" "D" -1 "F"]

```

Any built-in we can make available for that?
> 5 votes

# Answer
# Single-character identifiers

It's not like a code golf solution is going to have too many variables. And it would save on spaces.
> 5 votes

# Answer
### % as builtin for product

```
[1 2][1 2 3]%  # -> [[[1 1][1 2][1 3]][[2 1][2 2][2 3]]]

```
> 4 votes

# Answer
## Regex support

The lack of regex support has always struck me as odd in a language designed for golfing. It would be great to have

* `<string> <string> <string> y` (aka `tr`, using Perl's one-char alias for it)
* `<string> <string> <string> s` (substitute)
* `<string> <string> <block> s` (substitute with callback)
* `<string> <string> m` (match)
> 3 votes

# Answer
### Builtins for current date/time

It is currently very quirky to get date/time using Ruby evals.

```
D     # -> [2013 12 31]
T     # -> [23 59 59]

```
> 3 votes

# Answer
### Make |, & and ^ built-ins do something useful on blocks

E.g. `<array/string> <block> |` can be used as index function

```
[0 -10 -20 30 40 -50 60] {0<} |   # -> [1 2 5]

```

Any ideas for `<array/string> <block> &` or `<array/string> <block> ^`?
> 3 votes

# Answer
## A way to turn symbols back into code blocks

Currently, we can bind code blocks to symbols with `:`, but there's no way to reverse the process: executing a symbol bound to a code block just executes the block.

I can see a couple of ways to implement this:

1. add new syntax, e.g. `#foo` to push the value of `foo` to the stack, even if it's a code block, or
2. add an operator to expand *every* symbol in a code block, so that (using `_` as the new operator), e.g. `{2*}:dbl; {dbl dbl}_` would produce `{2* 2*}`.

I can see advantages to both methods. The latter could substitute for the former, at the cost of two extra chars (`{foo}_` instead of `#foo`), but I can see some potential applications for the former syntax where those two chars would be prohibitive (e.g. using `array #func %` instead of `array {func} %`).

Meanwhile, the former syntax could be used to replace the latter *if* there was a convenient way to somehow iterate over the tokens in a code block (which could be useful on its own, anyway).

---

In either case, I'd propose that expanding symbols that are bound to native built-ins (i.e. implemented in Ruby code) should return some kind of stub that could be called to obtain the functionality of the built-in, while being either impossible or just unlikely to be overridden. For example `#$` (or `{$}_`) could return e.g. `{builtin_dollar}`, where `builtin_dollar` would contain the actual implementation of the `$` built-in (and `#builtin_dollar` or `{builtin_dollar}_` should just return `{builtin_dollar}` itself).

This would **allow built-ins to be redefined without losing access to their functionality** (see my earlier suggestion), so that if I, say, for some reason wanted to swap the meanings of `$` and `@`, I could just do `#$ #@ :$; :@;` (or `{$}_ {@}_ :$; :@;`).
> 2 votes

# Answer
### Variable preset with command line args

Unfortunately, there isn't any char left unassigned, but maybe we can use `A` for that?
> 1 votes

# Answer
# Native Ruby functions that I should implement

This is Community Wiki; feel free to edit and add the functions you think I should implement!

Format: "`nativeFunctionName` (`nameInMyLanguage`)"

* `shuffle` (`sf`)
* `tr` (`tr`)
* `sample` (`sm`)
> 0 votes

# Answer
# Take features from APL and HQ9+ too!

* Shortcuts, like in APL. EDIT: just saw the answer "unicode aliases". That's what I meant :)
* Other golf-oriented shortcuts, like in H9+, HQ9+, CHIQRSX9+
> 0 votes

# Answer
# Clearly separating built-ins

e.g. capitals : built-ins ; making B for base feasable
> 0 votes

# Answer
## Local variables / closures

One thing I *really* miss in GolfScript is the ability to **temporarily change the value of a symbol**.

In particular, there's currently no way to temporarily override the meaning of a "primitive" built-in: once you, say, redefine `$`, you're never going to sort anything in that program again. (Well, not without writing your own sort implementation, at least.) It would be really nice to be able to say, for example, that *in this code block* `$` means something else, but still keep the normal meaning elsewhere.

Related to the above, it would be nice to **bind symbols in a code block to their current value**. Sure, I can write, say, `{$-1%}:rsort` and be able to use `rsort` to sort and reverse an array, but that works *only* as long as the definition of `$` (or `-1` or `%`) doesn't change, since my `rsort` function is still calling the global symbol `$`. It would be nice to be able to say "let `rsort` do what `$-1%` currently does, even if those symbols are later redefined."

In particular, the **standard library** could use this kind of binding. It's kind of surprising to realize that, say, changing `n` changes the behavior of `puts`, or that redefining `!` completely messes up `xor`. (Then again, some caution should be exercised here, since, in particular, the ability to change the behavior of `puts` turns out to be turns out to be the only way to avoid printing a final newline in the current version of GS.)

**Edit:** Being able to turn symbols back into code blocks would go a long way towards implementing this functionality. In particular, the `{foo}_` syntax suggested in that answer would effectively perform one level of static binding by expanding all symbols in a code block. Combine that with a fixpoint combinator for deep static binding, and Bob's your uncle...
> 0 votes

# Answer
# More built-in functions

Make all the single-letter variables a-z and A-Z perform some generic, useful function. Some built-ins that are lacking:

* min and max: all or some of top 2 stack values, top n stack values, over an array
* absolute value
* sum and product of an array. why do `{+}*` when you can do `S`? You have 52 functions to work with here!
* Manhattan distance (i.e. `x1 y1 x2 y2 --> abs(x2-x1)+abs(y2-y1)`. Now it'd have to be `@-A@@-A+` if `A` is a built-in absolute value. Granted this only came up caues of my most recent post but I always figured that'd be a good way to expand golfscript: write down what functions would be handy to have, collect them, and add them as built-ins.
* Convert an integer to a one-character string (equivalent of python's `chr`).
* Spill a string onto the stack (currently `{}/`)
* A version of `:` that consumes what is stored. This would have to not get 'stuck' to identifiers to be useful.
* Operators for `>=`, `<=`
* As someone suggested, a way to put a variable containing a block onto the stack without executing it. So you could reduce ifs of the form `1{\}{|}if` to something like `1?\?|if`
* Built-in base64 conversion and zlib support to make embedding data take less characters
* Beyond base64, make a custom base93 encoding (using all printable characters that aren't the string delimiter).
* Shortcuts for `1$`, `2$`, `3$`, `4$`, `5$`
* An operator to copy the top two stack items as they are, i.e. `\.@.@\`
> 0 votes

# Answer
It'd be nice if the value written or computed in the last line of a function was automatically returned
> -4 votes

---
Tags: code-golf, tips, golfscript
---