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!


Posted 2014-04-20T22:55:02.080

Reputation: 8 929

Question was closed 2014-05-10T03:19:30.297

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

12@Quincunx For the record, my vote was for Too Broad. There's literally nothing to go by except "make something related to square roots." (As evidenced by there being fifteen answers already.) – Doorknob – 2014-04-21T11:57:25.673

1Oh great, there's been two more answers in 15 minutes, and this is in the hot network questions already. This is why code trolling is so incredibly meh – Doorknob – 2014-04-21T12:14:54.870

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

In addition to being too broad, it is a possible duplicate of with the winning criterion changed. Not enough in my opinion to merit a brand new challenge.

– Rainbolt – 2014-04-21T13:36:07.237

6@Geobits, by saying that the answer doesn't even have to be correct, this is as broad as "Write some code". – Peter Taylor – 2014-04-21T13:54:53.967

@Quincunx Many people like McDonald's food. I'd still tell everyone that their food is crap and they should eat elsewhere. – Gareth – 2014-04-21T15:17:07.397

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

3@steveverrill I don't believe [code-trolling] belongs here, nor do I believe it brings anything positive to the site - and for those two reasons I will downvote and vote to close all code-trolling questions. – Gareth – 2014-04-21T16:23:34.817

@Doorknob Too broad was a good close vote reason. Off topic was not. Thank you for voting correctly. – Justin – 2014-04-21T16:39:02.837

2@Quincunx In code-trolling, part of the fun is in exploring how broad the question is. I agree with Geobits. – 11684 – 2014-04-24T19:24:23.060


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

– Chris Hayes – 2014-04-30T02:01:18.343

@qwr I think this has been around long enough to justify accepting an answer :-) – Justin – 2014-05-07T18:45:37.310

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

– Doorknob – 2014-05-11T23:07:14.463




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
import java.awt.Graphics;
import javax.swing.JFrame;
       import javax

public class SquareRoot {

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

    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

            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.
            (new int[]
}};         frame.add
(panel      );;//;;/
 ;;;        ;;;frame.
   (true);  frame.


  • Obviously, the code is obfuscated.
    • Do I get bonus points for the art in the code?
  • The System.out.prints don't print to java.lang.System.out.print. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one:
  • Outputs to a window. Sample output - do you see the square root (input is 100)?:enter image description here
  • 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.


Posted 2014-04-20T22:55:02.080

Reputation: 19 757

11Excellently trolled, good sir. – Code Whisperer – 2014-04-22T19:44:59.210

1I think you left out the JFrame.DO_NOTHING_ON_CLOSE in the list of trolls... – PlasmaPower – 2014-04-23T02:08:58.160

2@PlasmaPower I was about to edit that in. You forgot to mention setAlwaysOnTop(true) too. – Justin – 2014-04-23T02:15:17.110

4"I trolled myself" I think you trolled your girlfriend as well, lol – Herjan – 2014-04-23T19:01:05.587

15@Herjan girlfriend? What girlfriend? – Justin – 2014-04-23T19:05:15.150

1lol'd heartily at work at the "be sure to make your code look pretty!" -- prettiest code I ever did see on SO, I hope to see more in the future : ) – HC_ – 2014-04-24T16:53:05.310



Well, if you've got no better route, there's always the brute-force solution:

double sqrt(double n){
    union intdub{
        unsigned long long a;
        double b;
    } i;
    for(i.a = 0; i.a < 0xFFFFFFFFFFFFFFFF; ++i.a){
        if(i.b * i.b == n){
             return i.b;
    i.a = 0xFFFFFFFFFFFFFFFF; // quiet NaN
    return i.b;

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

Joe Z.

Posted 2014-04-20T22:55:02.080

Reputation: 30 589

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

1You've got me wondering that too. – Joe Z. – 2014-04-21T13:36:33.327

29Oh my god the union of a double and a long long is the most terrifying thing I have ever seen. – Patrick Collins – 2014-04-22T10:50:09.263


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

– Nobody – 2014-04-23T12:56:33.937

6I had no idea that std::nextafter existed before you just mentioned it to me, so yeah, it was wanted. – Joe Z. – 2014-04-23T13:45:31.583

It will take years to count all those 64 bits – phuclv – 2014-04-27T01:27:52.280

1But at least since it's brute force, it's guaranteed to find the most accurate answer. (Except it doesn't... :P) – Joe Z. – 2014-04-27T19:22:24.030

Except that this won't work if I ask for the square root of DBL_EPSILON ;) – Cole Johnson – 2014-04-27T20:19:31.250

3Some double values can't be produced from multiplying x*x where x is double, too. So the searching won't succeed sometimes (most of the times?), giving NaN instead of more correct result. – Display Name – 2014-04-28T13:15:09.790

2^ This was actually an unintended consequence of the code, but in terms of trolling, I couldn't ask for better. – Joe Z. – 2014-04-28T13:53:47.167


Python 3

This simple code will give an exact answer:

x = input('Enter a number: ')

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


Posted 2014-04-20T22:55:02.080

Reputation: 6 319

19Taking the challenge too literally is not too funny. – John Dvorak – 2014-04-21T08:43:38.623

24@JanDvorak on the other hand, this is the only program here that will always give the exact answer. – Level River St – 2014-04-21T09:55:03.143

1@steveverrill: No, mine does, too. – NaCl – 2014-04-21T11:44:24.750

By the same method, though. – Joe Z. – 2014-04-21T13:37:45.177

1@steveverrill: I challenge this program then, I wrote a program which always gives the correct answer, and actually solves the problem (it's my Python 3 program, not C program, by the way). – Konrad Borowski – 2014-04-21T18:26:21.853

@xfix OK, I gave you an upvote, which is more than I gave this one. – Level River St – 2014-04-21T18:53:01.280

16@JanDvorak this is code-trolling – TheDoctor – 2014-04-22T01:03:28.533

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

@JanDvorak * QUALITY code trolling. – Code Whisperer – 2014-04-22T19:45:32.993

This is great, haha – Joe Harper – 2014-04-24T10:33:56.350


In Python 3 you can do the following:

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


Posted 2014-04-20T22:55:02.080

Reputation: 551

38I figured out your troll: This does not work. It looks like it would, but the second line would need to be indented. – Justin – 2014-04-21T21:10:59.047

7@DLeh is it possible he's trolling himself? – krs013 – 2014-04-25T07:50:16.783


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
    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

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!

* 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.


Posted 2014-04-20T22:55:02.080

Reputation: 9 396

5Correcting your correction: C is faster than assembly, because the compiler can optimize better than human. Unless you know every single x86 assembly operation, the compiler will generally write better code. – Konrad Borowski – 2014-04-21T16:31:23.993

30@xfix Correcting your correction: with an intel manual at hand, a human can produce more efficient assembly than GCC – mniip – 2014-04-21T16:33:34.713

6@xfix After you read through brief descriptions for every mnemonic, stuff like PCMPEQQ no longer appears to you as "magic unreadable garbage produced by a compiler" – mniip – 2014-04-21T18:16:57.503

1Wow I wish you were my lab partner, I have no idea what I'm doing in assembly. Hilarious answer/comments. – HC_ – 2014-04-24T16:58:51.473

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



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)


Posted 2014-04-20T22:55:02.080

Reputation: 511

Can you explain how this is trolling? – The Guy with The Hat – 2014-04-27T16:46:17.787

6@TheGuywithTheHat: Instead of giving the square root of a number, this solution creates a user named with the square of the number and makes that user an admin (root in Unixland). – 3Doubloons – 2014-04-27T16:49:15.113



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];

Konrad Borowski

Posted 2014-04-20T22:55:02.080

Reputation: 11 185

3I think you mean results[number];? – user12205 – 2014-04-21T13:52:51.600


@ace: Both work, I just preferred to put more obfuscation here. Please see for information why this syntax is valid in C.

– Konrad Borowski – 2014-04-21T15:50:05.150

Ahhh... My kind of solution! For some reason, most of the other answers try to make the program as slow as possible. – Mr Lister – 2014-04-22T07:33:37.300

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

8@ArlaudPierre That's the beauty of code trolling solutions such as these. They are OK for a certain range, which may fool you into thinking they're actually usable! – Mr Lister – 2014-04-22T12:21:50.377

2@MrLister They are actually usable. The question does not say what range of values are accepted. There may be contexts where this is absolutely an acceptable value. – Pierre Arlaud – 2014-04-22T12:24:01.917

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



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.


Posted 2014-04-20T22:55:02.080

Reputation: 2 142

7I knew someone would do this :) This is what real magic looks like – qwr – 2014-04-21T04:34:36.617

8I spent almost a minute looking for the 1/y to turn it from inverse root into the actual root. The alternative of using return x * y is correct, but harder to spot. – Level River St – 2014-04-21T14:55:21.977

1I would think 10 iterations are too much. 2-3 are usually sufficient. – njzk2 – 2014-04-22T14:11:20.047


@njzk2 actually in Quake 3 engine only one iteration was used. The second one was commented out with additional note "this can be removed".

– Dunno – 2014-04-27T21:24:02.007


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

# 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

# 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
    # 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

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

# Prints newline
def print_newline():
    # Print received 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
    # Prints newline

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

# Calls main function

# This is end of program

And here is an example of this program working.

> python 
Specify number: 10 + 10
> python 
Specify number: cos(pi)

Konrad Borowski

Posted 2014-04-20T22:55:02.080

Reputation: 11 185

12-1 not enough comments – alexwlchan – 2014-04-22T22:00:09.383

5@alexwlchan: Added more comments. – Konrad Borowski – 2014-04-23T10:44:42.580

2Those are really short, easy to understand, descriptive function names! +1! P.S. Added more comments. – A.M.K – 2014-04-27T03:07:47.307

2-1 function name not long enough, should be print_format_prompt_with_thing_to_specify_get_default_prompt_format_to_getattr_get_sys_name_from_get_stdout_name_and_print_square_root_of_read_from_stdin_and_print_get_string_from_get_newline_to_getattr_get_sys_name_from_get_stdout_name. – The Guy with The Hat – 2014-04-27T17:02:18.780

1@TheGuywithTheHat: I would prefer if my huge function names would fit in the code box without horizontal scrolling. Even if it's [tag:code-trolling], I hate scrolling. – Konrad Borowski – 2014-04-27T17:03:30.043



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_[]; }(Math));

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

It's simple! :)

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


Posted 2014-04-20T22:55:02.080

Reputation: 4 912

16I like how your code breaks JS compressors. – Konrad Borowski – 2014-04-22T06:15:29.500

2@xfix Yeah, if anything tries to change the name of that self-executing function, the code will break :) – nderscore – 2014-04-22T14:34:12.247



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

enter image description here

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)

julia> sqrt(1.05)  #default

julia> sqroot(0.9)

julia> sqrt(0.9)  #default

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?

julia> sqroot(4)  #interesting...


Posted 2014-04-20T22:55:02.080

Reputation: 632

2The radius of convergent of this power series is 1, so this will only work for t in (0,2) (or for complex t in the open disk centered at 1 of radius 1). For other values, you could use factorizations... – gniourf_gniourf – 2014-04-21T08:02:40.183

You are right, i do not specified the convergence interval only for simplicity :) – CCP – 2014-04-21T22:13:38.623

2Too useful for my liking. You can easily divide by 4 until it is in bounds, then multiply the result with the corresponding power of 2. – user19713 – 2014-04-22T06:47:13.990

1^ I think it's safe to say that your average lazy question-asker would just take it as-is. – Joe Z. – 2014-04-22T13:56:43.493

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

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



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:


Now lets say that 1234321 is your number, look at the code:


Last but not least lets say your number is 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!

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.


Posted 2014-04-20T22:55:02.080

Reputation: 528

3I would like this Piet code, but it's just a Brainfuck compiler (that I could find on the Internet) executing the Ook code. – Konrad Borowski – 2014-04-21T17:27:47.400

11Wait a second? It's a esolang program that runs another language's compiler to parse a third language? Oh boy! – Kroltan – 2014-04-22T09:22:49.183

Ook is just a symbol-for-word gloss on Brainfuck. – Ross Presser – 2014-04-28T19:52:45.127



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

The accuracy should suffice for most applications.


Posted 2014-04-20T22:55:02.080

Reputation: 7 621

11DuckDuckGo beats Google! – M. Mimpen – 2014-04-22T11:33:07.957

2+1.0 for the "crap aleph-1 reals" – wchargin – 2014-04-26T00:47:01.737


@M.Mimpen Ackhhhchh:

– A.M.K – 2014-04-27T03:14:12.360

1@A.M.K Huh. Maybe Google is using doubles and DDG is using triples. – wchargin – 2014-04-27T22:56:26.353



The most precise way to do this is to iterate. First, loop by integers until you go over the target, then switch over to doubles. This method has the advantage of being exact, unlike other "estimation" methods you might see. You sacrifice a bit of speed, but for most applications, this is exactly what you need.

You can modify this answer depending on how precise you need to be, but this should work to at least to the billionth:

static double sqrt(double in){
    if(in < 0)
        return Double.NaN; // no negative numbers!
    int whole;
    for(whole = 0;whole < Integer.MAX_VALUE; whole++)
        if(whole * whole > in)

    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.


Posted 2014-04-20T22:55:02.080

Reputation: 19 061


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

– Joe Z. – 2014-04-21T02:40:22.070

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

True. Should I put epsilon detection in there? – Joe Z. – 2014-04-21T02:49:43.050

3Why not do Math.nextUp(root) instead of +0.000000001? That would take much longer... and it is guaranteed to succeed. – Justin – 2014-04-21T06:44:32.610

1@Quincunx I thought there was a method that did that in Double and was surprised when I couldn't find it. Didn't think to look in Math, but this works pretty well. I haven't had it "fail" on anything yet. – Geobits – 2014-04-21T11:38:31.167



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 ({}), this.y);
Object.prototype.toString = function() {
  return this.constructor+'';


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']


Posted 2014-04-20T22:55:02.080

Reputation: 256



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) {
    return Math.abs(o);
  } else return NaN;

Now you can use Math.sqrt

Michael M.

Posted 2014-04-20T22:55:02.080

Reputation: 12 173

How does this troll? Is it the fact that it gives a negative answer? – Joe Z. – 2014-04-21T13:28:30.220

1@JoeZ. Using a Newton-Raphson solver for an homework for beginners is the troll. It's not the answer expected but it works, and he will spend some time trying to understand the code. – Michael M. – 2014-04-21T14:01:43.833

28-1 not enough jQuery. – Pierre Arlaud – 2014-04-22T09:54:09.590

5@ArlaudPierre Hope you didn't actually give a -1... – tomsmeding – 2014-04-22T12:03:49.920

@tomsmeding He didn't.

– Justin – 2014-04-26T18:12:51.333



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.


Posted 2014-04-20T22:55:02.080

Reputation: 1 180

1The best answer out there. i liked the 'power' operator – Silviu Burcea – 2014-04-24T07:23:36.087

Such answer would be meaner in C or Python2, where additionally 1/2 == 0. – aland – 2014-04-28T11:07:59.740


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:


    'sql'=>'select sqrt(%d)',

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!

Ismael Miguel

Posted 2014-04-20T22:55:02.080

Reputation: 6 797


Python 2.7

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



Wikipedia - Square root

In mathematics, a square root of a number a is a number y such that y2 = a

In other words every number is a square root of some other number.


This question to me looks similar to a well known puzzle How to make a line shorter without rubbing or cutting it


Posted 2014-04-20T22:55:02.080

Reputation: 2 841



based on 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.


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;


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

Level River St

Posted 2014-04-20T22:55:02.080

Reputation: 22 049

Super accurate floating point – Cole Johnson – 2014-04-22T02:52:19.593

2@ColeJohnson Well you can't have a precise output, that's a constraint of the computer world (we can't have infinite memory). So I'd say this is about as accurate as it gets. – Pierre Arlaud – 2014-04-22T09:56:15.293

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



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;


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


Posted 2014-04-20T22:55:02.080

Reputation: 181

#define the number ... nice! I liked your reasoning about the condition for showing the usage message, in particular. – CompuChip – 2014-04-22T12:28:23.493

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



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;


Posted 2014-04-20T22:55:02.080

Reputation: 245

7Is this a real language? – Joe Z. – 2014-04-21T13:14:58.177

What kind of computer are you using? – Cole Johnson – 2014-04-22T02:50:48.153

@ClickRick Any chance you can provide a link for the E programming syntax and command scheme? – WallyWest – 2014-04-23T00:01:14.000

6Sorry, but even in base e, n >> 1 is not the same as log(n). – jwg – 2014-04-23T22:51:01.400

Is this it? – Cole Johnson – 2014-04-27T20:24:48.963

@jwg I assume it's not bit shifts then, but "e"-shifts. Where the language is defined such that n >> 1 === ln(n) and n << 1 === exp(n). That is, if such a language even exists. – Cole Johnson – 2014-04-27T20:26:34.160

2The language is easy enough to infer. The existence of supporting hardware is the part you should be questioning. – ClickRick – 2014-04-27T20:32:37.910



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"); = n + "px"; = "0px";

    // Rotating the div by 45 degrees = "rotate(45deg)"; = "rotate(45deg)"; = "rotate(45deg)"; = "rotate(45deg)"; = "rotate(45deg)";

    // Adding the div to the page so the browser will compute it's bounding box

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

    // Removing it from the page

    // 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;


Posted 2014-04-20T22:55:02.080

Reputation: 1 301




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

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

enter image description here enter image description here


Posted 2014-04-20T22:55:02.080

Reputation: 8 752


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 -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}
    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};
    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!!

F. Hauri

Posted 2014-04-20T22:55:02.080

Reputation: 2 654



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,
        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(;
                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;


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 :)

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.

Sahar Rabinoviz

Posted 2014-04-20T22:55:02.080

Reputation: 281

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

@Exelian made a fix according to your comment, provided a link to backup both your comment and the reason why my solution is still sufficient. – Sahar Rabinoviz – 2014-04-30T17:13:04.713



this one is the most accurate (bonus: also works for letters!)

Please enter the number : 

var a = $("#a").val();
a = "&radic;" +a ;

Here is a fiddle


Posted 2014-04-20T22:55:02.080

Reputation: 2 019

3Taking the challenge too literally is not too funny. Although I don't think document.write counters it enough. – John Dvorak – 2014-04-21T08:41:45.127

2@JanDvorak this is a code-trolling, such soloutions are valid here. – Mhmd – 2014-04-21T08:52:08.450

3@Mhmd: Still, we expect you to be creative here. Everybody already did that, do something else. You won't get much upvotes this way. – Konrad Borowski – 2014-04-21T09:07:42.603

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

@AndrewCoonce I assume it's allowed to help it sink by downvoting it? And people love unexplained downvotes... – John Dvorak – 2014-04-21T18:36:00.923

1@JanDvorak: Good point. Considering that, thanks for the explanation! – Andrew Coonce – 2014-04-21T19:10:03.600



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: ";
    cout << x << endl;
    return 0;

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


Posted 2014-04-20T22:55:02.080

Reputation: 1 235

Since you're limited by machine epsilon already, why not use x+=1e-16? – Kyle Kanos – 2014-04-21T13:32:19.923

1@KyleKanos Or more correctly, DBL_EPSILON. – Cole Johnson – 2014-04-22T02:50:22.213



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


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.


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)))

Emanuel Landeholm

Posted 2014-04-20T22:55:02.080

Reputation: 181



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;}


Posted 2014-04-20T22:55:02.080

Reputation: 1 147


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
      print *,"What is value: "
      read(*,*) x
      if(x < 0) exit
      print *,"square root = ",alogx
   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.

Kyle Kanos

Posted 2014-04-20T22:55:02.080

Reputation: 4 270


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")
while True:
    if c**2 < number:   continue

Hannes Karppila

Posted 2014-04-20T22:55:02.080

Reputation: 3 090



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


Posted 2014-04-20T22:55:02.080

Reputation: 12 038

1Looks interesting, what does it do exactly? – reggaemuffin – 2014-04-25T00:21:39.003

@Kostronor Outputs squares in the text console of a certain size. – Timtech – 2014-04-25T10:48:31.340


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.


Posted 2014-04-20T22:55:02.080

Reputation: 1 180

I think you should change the while condition to k * k = num. – Paŭlo Ebermann – 2014-04-26T17:57:46.950

@PaŭloEbermann Good idea, and that's also more efficient! I implemented your suggested changes. – IQAndreas – 2014-04-26T23:19:41.017



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.

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

Konrad Borowski

Posted 2014-04-20T22:55:02.080

Reputation: 11 185


Everybody's got this all wrong. This is the only valid solution (I'll use Python):

def getSqrt(int num):
    return 42


When running this code, the function clearly returns 42.

As it turns out, when running the code,


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


Posted 2014-04-20T22:55:02.080

Reputation: 383



import math
print math.sqrt(input())


Posted 2014-04-20T22:55:02.080

Reputation: 7 793

6This is code-trolling. Your answer does not seem very trollish. – user12205 – 2014-04-22T07:18:42.557

2@ace - i'm trolling the question by giving a correct answer – TheDoctor – 2014-04-22T14:07:57.180

10And voters are trolling you by giving you a downvote. – user12205 – 2014-04-22T15:11:44.160

The troll is that it evals an user specified value, is it? – Konrad Borowski – 2014-04-26T15:29:20.737



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')
prec = 5
while True:
    prec += 1
    context.prec = prec


Posted 2014-04-20T22:55:02.080

Reputation: 5 984



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.

Petr Pudlák

Posted 2014-04-20T22:55:02.080

Reputation: 4 272


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()");

    // triviale Fälle:

    if (qwurzel != null)
        return qwurzel;

    if (1 == len)
            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 ?
                            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);
    return qwurzel = erg;

The whole method works as specified: Z.quadratWurzel() returned a natural number qw such that qw * qw <= Z < (qw + 1) * (qw + 1), i.e. qw = ceil(sqrt(Z)).

I won't post the whole Zahl class here, just an outline:

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

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

Some hints for understanding the code:

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

Paŭlo Ebermann

Posted 2014-04-20T22:55:02.080

Reputation: 1 010

Is the troll that most users cannot understand your comments or variable names? – erdekhayser – 2014-04-29T02:04:13.240


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):
 def A(x):
    while a>w:b.insert(w,a%y);a//=y
    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
 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
    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
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.


Posted 2014-04-20T22:55:02.080

Reputation: 619