# Approximate My Squares

Inspired by this video by tecmath.

An approximation of the square root of any number x can be found by taking the integer square root s (i.e. the largest integer such that s * s ≤ x) and then calculating s + (x - s^2) / (2 * s). Let us call this approximation S(x). (Note: this is equivalent to applying one step of the Newton-Raphson method).

Though this does have quirk, where S(n^2 - 1) will always be √(n^2), but generally it will be very accurate. In some larger cases, this can have a >99.99% accuracy.

## Input and Output

You will take one number in any convienent format.

## Examples

Format: Input -> Output

2 -> 1.50
5 -> 2.25
15 -> 4.00
19 -> 4.37               // actually 4.37       + 1/200
27 -> 5.20
39 -> 6.25
47 -> 6.91               // actually 6.91       + 1/300
57 -> 7.57               // actually 7.57       + 1/700
2612 -> 51.10            // actually 51.10      + 2/255
643545345 -> 25368.19    // actually 25,368.19  + 250,000,000/45,113,102,859
35235234236 -> 187710.50 // actually 187,710.50 + 500,000,000/77,374,278,481


## Specifications

• Your output must be rounded to at least the nearest hundredth (ie. if the answer is 47.2851, you may output 47.29)

• Your output does not have to have following zeros and a decimal point if the answer is a whole number (ie. 125.00 can be outputted as 125 and 125.0, too)

• You do not have to support any numbers below 1.

• You do not have to support non-integer inputs. (ie. 1.52 etc...)

## Rules

Standard Loopholes are forbidden.

This is a , so shortest answer in bytes wins.

• Sandbox – Stan Strum Oct 26 '17 at 19:06
• Note: s + (x - s^2) / (2 * s) == (x + s^2) / (2 * s) – JungHwan Min Oct 26 '17 at 19:31
• My solutions: Pyth, 25 bytes; 14 bytes – Stan Strum Oct 26 '17 at 20:31
• Does it need to be accurate to at least 2 digits? – totallyhuman Oct 27 '17 at 1:01
• @totallyhuman Yes. 47.2851 can be represented as 47.28, but no more inaccurate. – Stan Strum Oct 27 '17 at 1:05

# Jelly,  8  7 bytes

-1 byte thanks to Olivier Grégoire's simplified mathematical formula - see their Java answer.

÷Æ½+Æ½H


Try it online!

### How?

÷Æ½+Æ½H - Link: number, n
Æ½     - integer square root of n  -> s
÷       - divide                    -> n / s
Æ½  - integer square root of n  -> s
+    - add                       -> n / s + s
H - halve                     -> (n / s + s) / 2

• 7 bytes: ÷Æ½+Æ½H First time trying to use Jelly so I might be wrong. I wish I knew how to store Æ½, though, to not repeat it. That might save another byte. – Olivier Grégoire Oct 27 '17 at 13:10
• Thanks @OlivierGrégoire! Æ½ɓ÷⁹+H would not recalculate the integer root, but it's also 7. ɓ starts a new dyadic chain with swapped arguments and then ⁹ refers to that chain's right argument (i.e. the result of Æ½). Æ½ɓ÷+⁹H would work here too. – Jonathan Allan Oct 27 '17 at 18:30

f x=last[s+x/s|s<-[1..x],s*s<=x]/2


Try it online!

Explanation in imperative pseudocode:

results=[]
foreach s in [1..x]:
if s*s<=x:
results.append(s+x/s)
return results[end]/2


# Java (OpenJDK 8), 32 bytes

n->(n/(n=(int)Math.sqrt(n))+n)/2


Try it online!

## Explanations

The code is equivalent to this:

double approx_sqrt(double x) {
double s = (int)Math.sqrt(x);  // assign the root integer to s
return (x / s + s) / 2
}


The maths behind:

s + (x - s²) / (2 * s)  =  (2 * s² + x - s²) / (2 * s)
=  (x + s²) / (2 * s)
=  (x + s²) / s / 2
=  ((x + s²) / s) / 2
=  (x / s + s² / s) / 2
=  (x / s + s) / 2

• This doesn't appear to handle the specification: Your output must be rounded to at least the nearest hundredth – Ayb4btu Oct 27 '17 at 21:04
• Well, it is rounded to lower than the nearest hundredth, so it's totally valid. – Olivier Grégoire Oct 27 '17 at 21:48
• Ah, I see, my misunderstanding. – Ayb4btu Oct 27 '17 at 21:51

# Python 2, 47 ... 36 bytes

-3 bytes thanks to @JungHwanMin
-1 byte thanks to @HyperNeutrino
-2 bytes thanks to @JonathanFrech
-3 bytes thanks to @OlivierGrégoire

def f(x):s=int(x**.5);print(x/s+s)/2


Try it online!

• -2 bytes: s+(x-s*s)/s/2 to (x+s*s)/s/2 – JungHwan Min Oct 26 '17 at 19:31
• -2 bytes using a function – HyperNeutrino Oct 26 '17 at 19:41
• @HyperNeutrino I only get -1 byte – ovs Oct 26 '17 at 19:46
• Oh sorry I accidentally deleted a character after testing and then counted the bytes after :P yeah just -1 – HyperNeutrino Oct 26 '17 at 19:53
• Can you not omit +.0 and replace /s/2 with /2./s, saving two bytes? – Jonathan Frech Oct 26 '17 at 21:47

# MATL, 12 9 bytes

X^kGy/+2/


Try it online!

# R, 43 bytes 29 bytes

x=scan()
(x/(s=x^.5%/%1)+s)/2


Thanks to @Giuseppe for the new equation and help in golfing of 12 bytes with the integer division solution. By swapping out the function call for scan, I golfed another couple bytes.

Try it online!

# APL (Dyalog), 20 16 bytes

{.5×s+⍵÷s←⌊⍵*.5}


Try it online!

# JavaScript (ES7), 22 bytes

x=>(s=x**.5|0)/2+x/s/2


We don't really need an intermediate variable, so this can actually be rewritten as:

x=>x/(x=x**.5|0)/2+x/2


### Test cases

let f =

x=>x/(x=x**.5|0)/2+x/2

console.log(f(2))           // 1.50
console.log(f(5))           // 2.25
console.log(f(15))          // 4.00
console.log(f(19))          // 4.37
console.log(f(27))          // 5.20
console.log(f(39))          // 6.25
console.log(f(47))          // 6.91
console.log(f(57))          // 7.57
console.log(f(2612))        // 51.10
console.log(f(643545345))   // 25368.19
console.log(f(35235234236)) // 187710.50

# C, 34 bytes

Thanks to @Olivier Grégoire!

s;
#define f(x)(x/(s=sqrt(x))+s)/2


Works only with float inputs.

Try it online!

# C,  41  39  37 bytes

s;
#define f(x).5/(s=sqrt(x))*(x+s*s)


Try it online!

# C,  49  47  45  43 bytes

s;float f(x){return.5/(s=sqrt(x))*(x+s*s);}


Try it online!

Thanks to @JungHwan Min for saving two bytes!

• 47 bytes; edit: Thank you, but credit @JungHwanMin for finding that. – Stan Strum Oct 26 '17 at 19:50
• 34 bytes – Olivier Grégoire Oct 27 '17 at 8:43

Another one bytes the dust thanks to H.PWiz.

f n|s<-realToFrac$floor$sqrt n=s/2+n/s/2


Try it online!

# AWK, 47 44 38 bytes

{s=int($1^.5);printf"%.2f",$1/2/s+s/2}


Try it online!

NOTE: The TIO like has 2 extra bytes for \n to make the output prettier. :)

It feels like cheating a bit to use sqrt to find the square root, so here is a version with a few more bytes that doesn't.

{for(;++s*s<=$1;);s--;printf("%.3f\n",s+($1-s*s)/(2*s))}


Try it online!

• well you could say this is AWKward. I’ll show myself out. edit: originally I planned for the question to shun using sqrt, but there’s too many answers and I’ll get tort if I change it so my original idea works. – Stan Strum Oct 27 '17 at 19:17
• 'AWK' puns are fun :) – Robert Benson Oct 28 '17 at 13:19
• instead of sqrt($1) you can use $1^.5 – Cabbie407 Oct 29 '17 at 22:42
• Thanks @Cabbie407 don't know why I didn't think of that. – Robert Benson Oct 30 '17 at 13:52
• You're welcome. Some other things: you don't need the \n to get the output, the printf in awk doesn't need parentheses and the formula can be shortened to s/2+$1/s/2, which results in {s=int($1^.5);printf"%.2f",s/2+$1/s/2}. Sorry if this comment seems rude. – Cabbie407 Oct 31 '17 at 0:18 # Racket, 92 bytes Thanks to @JungHwan Min for the tip in the comment section (λ(x)(let([s(integer-sqrt x)])(~r(exact->inexact(/(+ x(* s s))(* 2 s)))#:precision'(= 2))))  Try it online! Ungolfed (define(fun x) (let ([square (integer-sqrt x)]) (~r (exact->inexact (/ (+ x (* square square)) (* 2 square))) #:precision'(= 2))))  # PowerShell, 54 bytes param($x)($x+($s=(1..$x|?{$_*$_-le$x})[-1])*$s)/(2*$s)


Takes input $x and then does exactly what is requested. The |? part finds the maximal integer that, when squared, is -less-than-or-equal to the input $x, then we perform the required calculations. Output is implicit.

• Wow. I've never been able to comprehend how people golf in Windows Powershell – Stan Strum Oct 26 '17 at 20:13
• @StanStrum You're not alone, lol. :D – AdmBorkBork Oct 26 '17 at 20:24

# Husk, 9 bytes

½Ṡ§+K/(⌊√


Try it online!

There is still something ugly in this answer, but I can't seem to find a shorter solution.

### Explanation

I'm implementing one step of Newton's algorithm (which is indeed equivalent to the one proposed in this question)

½Ṡ§+K/(⌊√
§+K/       A function which takes two numbers s and x, and returns s+x/s
Ṡ           Call this function with the input as second argument and
(⌊√    the floor of the square-root of the input as first argument
½            Halve the final result

• I think you want actual division, rather than ÷ – H.PWiz Oct 26 '17 at 23:24
• @H.PWiz whoops, I do, thank you. That was a remain from an experiment to find other solutions – Leo Oct 26 '17 at 23:29

# Pyt, 11 10 bytes

←Đ√⌊Đ↔⇹/+₂


# Explanation

code                explanation                        stack
←                   get input                          [input]
Đ                  duplicate ToS                      [input,input]
√⌊                calculate s                        [input,s]
Đ               duplicate ToS                      [input,s,s]
↔              reverse stack                      [s,s,input]
⇹             swap ToS and SoS                   [s,input,s]
/            divide                             [s,input/s]
₂          halve                              [(s+input/s)/2]
implicit print

• Just saw this and it was a good minute until I realised it’s not Pyth. Great answer. – Stan Strum Dec 25 '17 at 17:47
• Yeah, it's a little language I've been thinking about for a while and just decided to actually make. – mudkip201 Dec 25 '17 at 17:51
• Is ToS top-of-stack... and if so, what’s SoS? – Stan Strum Dec 25 '17 at 17:53
• ToS is top of stack, and SoS is second on stack – mudkip201 Dec 25 '17 at 17:54
• Nice, I’ll see if I can delve into this language; I like it! – Stan Strum Dec 25 '17 at 17:55

# Milky Way, 17 14 bytes

-3 bytes by using Olivier Grégoire's formula

^^':2;g:>/+2/!


Try it online!

## Explanation

code              explanation                   stack layout

^^                clear preinitialized stack    []
':              push input and duplicate it   [input, input]
2;            push 2 and swap ToS and SoS   [input, 2, input]
g           nth root                      [input, s=floor(sqrt(input))]
:          duplicate ToS                 [input, s, s]
>         rotate stack right            [s, input, s]
/        divide                        [s, input/s]
2/     divide by 2                   [(s+input/s)/2]
!    output                        => (s+input/s)/2

• shouldn't that be floor instead of ceil? – mudkip201 Dec 25 '17 at 15:56
• @mudkip201 Updated, thanks – ovs Dec 25 '17 at 22:28

# C# (.NET Core), 39 bytes

v=>(v/(v=(int)System.Math.Sqrt(v))+v)/2


Try it online!

A C# version of Olivier Grégoire's Java answer.