Fundamentals 4 min read

How to Compute √2 Efficiently: Binary Search, Newton’s Method, and C Tricks

Learn multiple techniques to calculate the square root of 2—including binary search, Newton’s iteration, and a clever C library implementation—through clear explanations, step‑by‑step illustrations, and full JavaScript and C code examples that reveal the underlying mathematics and performance considerations.

Programmer DD
Programmer DD
Programmer DD
How to Compute √2 Efficiently: Binary Search, Newton’s Method, and C Tricks

Source: Algorithm interview question

Problem

During an interview, the candidate was asked how to compute the value of √2.

Approach

Two main methods are presented: binary search and Newton’s iteration. The article also mentions using the Taylor series and discusses how the standard library sqrt function is implemented, typically using a clever variant of Newton’s method for high efficiency.

Illustrations of the iterative process:

Code Implementation

Newton’s method (JavaScript)

function sqrt(n) {
    let res = n >= 1 ? n : 1;
    while (res * res - n > 1e-8) {
        res = 0.5 * (res + n / res);
    }
    return res;
}

C library function (source)

float invSqrt(float x) {
    float xhalf = 0.5f * x;
    int i = *(int*)&x;
    i = 0x5f375a86 - (i >> 1);
    x = *(float*)&i;
    x = x * (1.5f - xhalf * x * x);
    x = x * (1.5f - xhalf * x * x);
    x = x * (1.5f - xhalf * x * x);
    return x;
}

Note: The C function returns the reciprocal of √x; the actual √x can be obtained by taking the inverse of the result.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmCBinary SearchsqrtNumerical MethodsNewton's method
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.