42
votes
\$\begingroup\$

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!

\$\endgroup\$
15
  • 63
    \$\begingroup\$ @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. \$\endgroup\$
    – Justin
    Apr 21, 2014 at 8:01
  • 12
    \$\begingroup\$ @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.) \$\endgroup\$
    – Doorknob
    Apr 21, 2014 at 11:57
  • 7
    \$\begingroup\$ Close-voters: Can you help me understand how this is any more "broad" than other unclosed [code-trolling] questions? Maybe there's a valid close reason here, but the code-trolling category is naturally going to be a bit broader than most challenges. Otherwise, it would somewhat defeat the purpose. \$\endgroup\$
    – Geobits
    Apr 21, 2014 at 13:18
  • 6
    \$\begingroup\$ @Geobits, by saying that the answer doesn't even have to be correct, this is as broad as "Write some code". \$\endgroup\$ Apr 21, 2014 at 13:54
  • 11
    \$\begingroup\$ @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. \$\endgroup\$ Apr 21, 2014 at 15:44

41 Answers 41

121
votes
\$\begingroup\$

Java

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

       import java
       .awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
       import javax
       .swing.JPanel;

public class SquareRoot {

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

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

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

Trolls:

  • Obviously, the code is obfuscated.
    • Do I get bonus points for the art in the code?
  • The System.out.prints don't print to java.lang.System.out.print. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one:
  • Outputs to a window. Sample output - do you see the square root (input is 100)?: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.
\$\endgroup\$
6
  • 11
    \$\begingroup\$ Excellently trolled, good sir. \$\endgroup\$ Apr 22, 2014 at 19:44
  • 1
    \$\begingroup\$ I think you left out the JFrame.DO_NOTHING_ON_CLOSE in the list of trolls... \$\endgroup\$ Apr 23, 2014 at 2:08
  • 2
    \$\begingroup\$ @PlasmaPower I was about to edit that in. You forgot to mention setAlwaysOnTop(true) too. \$\endgroup\$
    – Justin
    Apr 23, 2014 at 2:15
  • 4
    \$\begingroup\$ "I trolled myself" I think you trolled your girlfriend as well, lol \$\endgroup\$
    – Herjan
    Apr 23, 2014 at 19:01
  • 15
    \$\begingroup\$ @Herjan girlfriend? What girlfriend? \$\endgroup\$
    – Justin
    Apr 23, 2014 at 19:05
71
votes
\$\begingroup\$

C++

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

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

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

\$\endgroup\$
10
  • 12
    \$\begingroup\$ Now you've got me wondering, how often (given unlimited time to run) does this actually work, and how often does it fail to find an exact match and return NaN? I'm thinking it's about 50/50, but it's too late here for good mathematical thinking. \$\endgroup\$
    – hobbs
    Apr 21, 2014 at 7:21
  • 29
    \$\begingroup\$ Oh my god the union of a double and a long long is the most terrifying thing I have ever seen. \$\endgroup\$ Apr 22, 2014 at 10:50
  • 10
    \$\begingroup\$ 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 \$\endgroup\$ Apr 23, 2014 at 12:56
  • 6
    \$\begingroup\$ I had no idea that std::nextafter existed before you just mentioned it to me, so yeah, it was wanted. \$\endgroup\$
    – Joe Z.
    Apr 23, 2014 at 13:45
  • 3
    \$\begingroup\$ Some double values can't be produced from multiplying x*x where x is double, too. So the searching won't succeed sometimes (most of the times?), giving NaN instead of more correct result. \$\endgroup\$ Apr 28, 2014 at 13:15
64
votes
\$\begingroup\$

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.

\$\endgroup\$
10
  • 19
    \$\begingroup\$ Taking the challenge too literally is not too funny. \$\endgroup\$ Apr 21, 2014 at 8:43
  • 24
    \$\begingroup\$ @JanDvorak on the other hand, this is the only program here that will always give the exact answer. \$\endgroup\$ Apr 21, 2014 at 9:55
  • 1
    \$\begingroup\$ @steveverrill: No, mine does, too. \$\endgroup\$
    – NaCl
    Apr 21, 2014 at 11:44
  • 1
    \$\begingroup\$ @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). \$\endgroup\$ Apr 21, 2014 at 18:26
  • 16
    \$\begingroup\$ @JanDvorak this is code-trolling \$\endgroup\$
    – TheDoctor
    Apr 22, 2014 at 1:03
45
votes
\$\begingroup\$

In Python 3 you can do the following:

def square_root(n):
return float(n)**0.5
\$\endgroup\$
2
  • 38
    \$\begingroup\$ I figured out your troll: This does not work. It looks like it would, but the second line would need to be indented. \$\endgroup\$
    – Justin
    Apr 21, 2014 at 21:10
  • 7
    \$\begingroup\$ @DLeh is it possible he's trolling himself? \$\endgroup\$
    – krs013
    Apr 25, 2014 at 7:50
42
votes
\$\begingroup\$

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.

\$\endgroup\$
5
  • 5
    \$\begingroup\$ Correcting your correction: C is faster than assembly, because the compiler can optimize better than human. Unless you know every single x86 assembly operation, the compiler will generally write better code. \$\endgroup\$ Apr 21, 2014 at 16:31
  • 30
    \$\begingroup\$ @xfix Correcting your correction: with an intel manual at hand, a human can produce more efficient assembly than GCC \$\endgroup\$
    – mniip
    Apr 21, 2014 at 16:33
  • 6
    \$\begingroup\$ @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" \$\endgroup\$
    – mniip
    Apr 21, 2014 at 18:16
  • 1
    \$\begingroup\$ Wow I wish you were my lab partner, I have no idea what I'm doing in assembly. Hilarious answer/comments. \$\endgroup\$
    – HC_
    Apr 24, 2014 at 16:58
  • \$\begingroup\$ @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? \$\endgroup\$
    – Navin
    Apr 30, 2014 at 4:47
39
votes
\$\begingroup\$

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)

\$\endgroup\$
2
  • \$\begingroup\$ Can you explain how this is trolling? \$\endgroup\$ Apr 27, 2014 at 16:46
  • 6
    \$\begingroup\$ @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). \$\endgroup\$
    – 3Doubloons
    Apr 27, 2014 at 16:49
33
votes
\$\begingroup\$

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];
}
\$\endgroup\$
7
  • 3
    \$\begingroup\$ I think you mean results[number];? \$\endgroup\$
    – user12205
    Apr 21, 2014 at 13:52
  • 31
    \$\begingroup\$ @ace: Both work, I just preferred to put more obfuscation here. Please see stackoverflow.com/q/381542/736054 for information why this syntax is valid in C. \$\endgroup\$ Apr 21, 2014 at 15:50
  • 8
    \$\begingroup\$ @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! \$\endgroup\$
    – Mr Lister
    Apr 22, 2014 at 12:21
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ Apr 22, 2014 at 12:24
  • 9
    \$\begingroup\$ @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. \$\endgroup\$ Apr 22, 2014 at 12:46
30
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 7
    \$\begingroup\$ I knew someone would do this :) This is what real magic looks like \$\endgroup\$
    – qwr
    Apr 21, 2014 at 4:34
  • 8
    \$\begingroup\$ I spent almost a minute looking for the 1/y to turn it from inverse root into the actual root. The alternative of using return x * y is correct, but harder to spot. \$\endgroup\$ Apr 21, 2014 at 14:55
  • 1
    \$\begingroup\$ I would think 10 iterations are too much. 2-3 are usually sufficient. \$\endgroup\$
    – njzk2
    Apr 22, 2014 at 14:11
  • 1
    \$\begingroup\$ @njzk2 actually in Quake 3 engine only one iteration was used. The second one was commented out with additional note "this can be removed". codemaestro.com/reviews/9 \$\endgroup\$
    – Dunno
    Apr 27, 2014 at 21:24
29
votes
\$\begingroup\$

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
\$\endgroup\$
5
  • 12
    \$\begingroup\$ -1 not enough comments \$\endgroup\$
    – alexwlchan
    Apr 22, 2014 at 22:00
  • 5
    \$\begingroup\$ @alexwlchan: Added more comments. \$\endgroup\$ Apr 23, 2014 at 10:44
  • 2
    \$\begingroup\$ Those are really short, easy to understand, descriptive function names! +1! P.S. Added more comments. \$\endgroup\$
    – A.M.K
    Apr 27, 2014 at 3:07
  • 2
    \$\begingroup\$ -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. \$\endgroup\$ Apr 27, 2014 at 17:02
  • 1
    \$\begingroup\$ @TheGuywithTheHat: I would prefer if my huge function names would fit in the code box without horizontal scrolling. Even if it's code-trolling, I hate scrolling. \$\endgroup\$ Apr 27, 2014 at 17:03
28
votes
\$\begingroup\$

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;

\$\endgroup\$
2
  • 16
    \$\begingroup\$ I like how your code breaks JS compressors. \$\endgroup\$ Apr 22, 2014 at 6:15
  • 2
    \$\begingroup\$ @xfix Yeah, if anything tries to change the name of that self-executing function, the code will break :) \$\endgroup\$
    – nderscore
    Apr 22, 2014 at 14:34
25
votes
\$\begingroup\$

Julia

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)
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   
\$\endgroup\$
6
  • 2
    \$\begingroup\$ The radius of convergent of this power series is 1, so this will only work for t in (0,2) (or for complex t in the open disk centered at 1 of radius 1). For other values, you could use factorizations... \$\endgroup\$ Apr 21, 2014 at 8:02
  • \$\begingroup\$ You are right, i do not specified the convergence interval only for simplicity :) \$\endgroup\$
    – CCP
    Apr 21, 2014 at 22:13
  • 2
    \$\begingroup\$ Too useful for my liking. You can easily divide by 4 until it is in bounds, then multiply the result with the corresponding power of 2. \$\endgroup\$
    – user19713
    Apr 22, 2014 at 6:47
  • 1
    \$\begingroup\$ ^ I think it's safe to say that your average lazy question-asker would just take it as-is. \$\endgroup\$
    – Joe Z.
    Apr 22, 2014 at 13:56
  • \$\begingroup\$ 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). \$\endgroup\$
    – CCP
    Apr 22, 2014 at 16:09
20
votes
\$\begingroup\$

LaTeX

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

\sqrt{9}

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

\sqrt{1234321}

Last but not least lets say your number is 0.

\sqrt{0}

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

Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook? Ook. Ook? Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook! Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook? Ook! Ook! Ook? Ook! 

Same for Piet:

Does the same as the simple program written in Ook!

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.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ I would like this Piet code, but it's just a Brainfuck compiler (that I could find on the Internet) executing the Ook code. \$\endgroup\$ Apr 21, 2014 at 17:27
  • 11
    \$\begingroup\$ Wait a second? It's a esolang program that runs another language's compiler to parse a third language? Oh boy! \$\endgroup\$
    – Kroltan
    Apr 22, 2014 at 9:22
  • \$\begingroup\$ Ook is just a symbol-for-word gloss on Brainfuck. \$\endgroup\$ Apr 28, 2014 at 19:52
20
votes
\$\begingroup\$

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.

\$\endgroup\$
4
  • 11
    \$\begingroup\$ DuckDuckGo beats Google! \$\endgroup\$
    – M. Mimpen
    Apr 22, 2014 at 11:33
  • 2
    \$\begingroup\$ +1.0 for the "crap aleph-1 reals" \$\endgroup\$
    – wchargin
    Apr 26, 2014 at 0:47
  • 2
    \$\begingroup\$ @M.Mimpen Ackhhhchh: duckduckgo.com/… \$\endgroup\$
    – A.M.K
    Apr 27, 2014 at 3:14
  • 1
    \$\begingroup\$ @A.M.K Huh. Maybe Google is using doubles and DDG is using triples. \$\endgroup\$
    – wchargin
    Apr 27, 2014 at 22:56
16
votes
\$\begingroup\$

Java

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

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

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

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

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

\$\endgroup\$
5
  • 1
    \$\begingroup\$ The problem with using 0.000000001 is that it's prone to rounding errors. I've created a more precise solution in C++. \$\endgroup\$
    – Joe Z.
    Apr 21, 2014 at 2:40
  • 2
    \$\begingroup\$ @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 ;) \$\endgroup\$
    – Geobits
    Apr 21, 2014 at 2:43
  • \$\begingroup\$ True. Should I put epsilon detection in there? \$\endgroup\$
    – Joe Z.
    Apr 21, 2014 at 2:49
  • 3
    \$\begingroup\$ Why not do Math.nextUp(root) instead of +0.000000001? That would take much longer... and it is guaranteed to succeed. \$\endgroup\$
    – Justin
    Apr 21, 2014 at 6:44
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Geobits
    Apr 21, 2014 at 11:38
11
votes
\$\begingroup\$

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

\$\endgroup\$
10
votes
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\begingroup\$ How does this troll? Is it the fact that it gives a negative answer? \$\endgroup\$
    – Joe Z.
    Apr 21, 2014 at 13:28
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Michael M.
    Apr 21, 2014 at 14:01
  • 28
    \$\begingroup\$ -1 not enough jQuery. \$\endgroup\$ Apr 22, 2014 at 9:54
  • 5
    \$\begingroup\$ @ArlaudPierre Hope you didn't actually give a -1... \$\endgroup\$
    – tomsmeding
    Apr 22, 2014 at 12:03
  • \$\begingroup\$ @tomsmeding He didn't. \$\endgroup\$
    – Justin
    Apr 26, 2014 at 18:12
10
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ The best answer out there. i liked the 'power' operator \$\endgroup\$ Apr 24, 2014 at 7:23
  • \$\begingroup\$ Such answer would be meaner in C or Python2, where additionally 1/2 == 0. \$\endgroup\$
    – aland
    Apr 28, 2014 at 11:07
9
votes
\$\begingroup\$

Python 2.7

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

Explanation

Quoting

Wikipedia - Square root

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

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

Note

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

\$\endgroup\$
9
votes
\$\begingroup\$

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!

\$\endgroup\$
0
8
votes
\$\begingroup\$

C

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

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define usage "message"
#define the number

char *squareroot(int number);

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

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

Code-trolling:

  • Very odd naming
  • forloop abuse
  • Putting semicolons at the beginning of the line, where they were meant to be
  • #define use to increase decrease readability
  • useless usage message
  • minus or plus instead of plus or minus
  • returns a string
  • returns a local variable
  • 4 compiler warnings (2 unused expression result, returning local variable address, not a string literal in printf)
  • only works for nonnegative perfect squares < 100 (aka 0, 4, 9, 16, 25, 36, 49, 64, and 81) since the answer can only be 1 digit (hits a backspace after the answer is printed for absolutely no reason, so for example √1024 returns 3√1024 = ∓32, which is just plain wrong)
\$\endgroup\$
2
  • \$\begingroup\$ #define the number ... nice! I liked your reasoning about the condition for showing the usage message, in particular. \$\endgroup\$
    – CompuChip
    Apr 22, 2014 at 12:28
  • \$\begingroup\$ -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. \$\endgroup\$
    – ClickRick
    Apr 23, 2014 at 0:16
8
votes
\$\begingroup\$

C++

based on http://en.wikipedia.org/wiki/Fast_inverse_square_root and @snack's answer.

Except instead of bolting on a way to convert the x^(-0.5) into x^(0.5) I modified the algorithm to do it directly.

ALGORITHM

Cast a floating point number (in this case a double) to an integer (in this case long long.)

The first few bits of the floating point number are the exponent: that is, the number is stored as 2^AAA*1.BBBBBBB. So do a rightshift and this exponent is halved.

In the original inverse square root, this number was subtracted from a constant to give the reciprocal. I just add it to the constant, because I want the square root directly. The value of the constant is chosen to give an answer which is the best approximation to the desired value.

Cast the number back to floating point.

Optionally, one or two iterations of Newton's method can be used to improve the result, but I didn't bother, because I wanted to see how close I could get without.

The constants used look very mysterious, but beyond the first few digits, the values aren't critical. I found the constant by trial and error. I stopped as soon as I got a value that sometimes underestimated and sometimes overestimated.

#include "stdafx.h"

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

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

Results

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

enter image description here

\$\endgroup\$
3
  • \$\begingroup\$ Super accurate floating point \$\endgroup\$
    – Cole Tobin
    Apr 22, 2014 at 2:52
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ Apr 22, 2014 at 9:56
  • \$\begingroup\$ Well the double is clearly overkill, and part of the troll. I expected to get about +/-30% from this method. Trolling apart, I am amazed how accurate it is. Part of the reason is this: 4=2^10*1.000, sqrt(4)=2^01*1.000=2, sqrt(2)=2^00*1.100=1.5. So the 1bit shifted out of the exponent gives a mantissa of 1.5, which is not far off the true value of sqrt(2) which is about 1.4. But have no idea how it consistently gives answers with an accuracy better than 3%. \$\endgroup\$ Apr 24, 2014 at 20:29
7
votes
\$\begingroup\$

E

Note: this only works on my computer, as the underlying hardware does not store numbers in binary but in base e, such that what appears as 10 represents e, 100 represents ee, and so on. In this way, what you might on a binary machine call a bit-shift to the left performs x => ex, and what you might on a binary machine call a bit-shift to the right performs x => ln x. Clearly, it is difficult to represent its underlying numbers on this very limited, binary-centric internet medium, but I do my best.

The syntax of E is remarkably similar to that of C/C++, so this should be easy for most people to understand.

double sqrt(double n)
{
    return ((n >> 1) / 2) << 1;
}
\$\endgroup\$
7
  • 7
    \$\begingroup\$ Is this a real language? \$\endgroup\$
    – Joe Z.
    Apr 21, 2014 at 13:14
  • \$\begingroup\$ What kind of computer are you using? \$\endgroup\$
    – Cole Tobin
    Apr 22, 2014 at 2:50
  • \$\begingroup\$ @ClickRick Any chance you can provide a link for the E programming syntax and command scheme? \$\endgroup\$ Apr 23, 2014 at 0:01
  • 6
    \$\begingroup\$ Sorry, but even in base e, n >> 1 is not the same as log(n). \$\endgroup\$
    – jwg
    Apr 23, 2014 at 22:51
  • 2
    \$\begingroup\$ The language is easy enough to infer. The existence of supporting hardware is the part you should be questioning. \$\endgroup\$
    – ClickRick
    Apr 27, 2014 at 20:32
6
votes
\$\begingroup\$

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;
}
\$\endgroup\$
6
votes
\$\begingroup\$

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:

enter image description here enter image description here

\$\endgroup\$
6
votes
\$\begingroup\$

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

\$\endgroup\$
4
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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) \$\endgroup\$
    – Exelian
    Apr 29, 2014 at 11:11
  • \$\begingroup\$ @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. \$\endgroup\$ Apr 30, 2014 at 17:13
3
votes
\$\begingroup\$

JQuery

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

Please enter the number : 
<script>
$("#b").submit(function() 
{
 
var a = $("#a").val();
a = "&radic;" +a ;
document.write(a);  
});
</script>

Here is a fiddle

\$\endgroup\$
6
  • 3
    \$\begingroup\$ Taking the challenge too literally is not too funny. Although I don't think document.write counters it enough. \$\endgroup\$ Apr 21, 2014 at 8:41
  • 2
    \$\begingroup\$ @JanDvorak this is a code-trolling, such soloutions are valid here. \$\endgroup\$
    – Mohammad
    Apr 21, 2014 at 8:52
  • 3
    \$\begingroup\$ @Mhmd: Still, we expect you to be creative here. Everybody already did that, do something else. You won't get much upvotes this way. \$\endgroup\$ Apr 21, 2014 at 9:07
  • 1
    \$\begingroup\$ @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.) \$\endgroup\$ Apr 21, 2014 at 18:19
  • 1
    \$\begingroup\$ @JanDvorak: Good point. Considering that, thanks for the explanation! \$\endgroup\$ Apr 21, 2014 at 19:10
3
votes
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Since you're limited by machine epsilon already, why not use x+=1e-16? \$\endgroup\$
    – Kyle Kanos
    Apr 21, 2014 at 13:32
  • 1
    \$\begingroup\$ @KyleKanos Or more correctly, DBL_EPSILON. \$\endgroup\$
    – Cole Tobin
    Apr 22, 2014 at 2:50
3
votes
\$\begingroup\$

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)))
\$\endgroup\$
3
votes
\$\begingroup\$

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;}
\$\endgroup\$

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