JavaScript - Improving algorithm for finding square roots of perfect squares without Math.sqrt

I'm trying to learn algorithms and coding stuff by scratch. I wrote a function that will find square roots of square numbers only, but I need to know how to improve its performance and possibly return square roots of non square numbers

function squareroot(number) {
    var number;
    for (var i = number; i >= 1; i--) {
        if (i * i === number) {
            number = i;
            break;
       }
   }
   return number;
}

 alert(squareroot(64))

Will return 8

Most importantly I need to know how to improve this performance. I don't really care about its limited functionality yet

Here is a small improvement I can suggest. First - start iterating from 0. Second - exit loop when the square of root candidate exceeds the number.

function squareroot(number) {
    for (var i = 0; i * i <= number; i++) {
        if (i * i === number)
            return i;
   }
   return number; // don't know if you should have this line in case nothing found
}

This algo will work in O(√number) time comparing to initial O(n) which is indeed performance improvement that you asked.

Edit #1

Just even more efficient solution would be to binary search the answer as @Spektre suggested. It is known that x2 is increasing function.

function squareroot(number) {
    var lo = 0, hi = number;
    while(lo <= hi) {
         var mid = Math.floor((lo + hi) / 2);
         if(mid * mid > number) hi = mid - 1;
         else lo = mid + 1;
    }
    return hi;
}

This algo has O(log(number)) running time complexity.

Square root of a number without using sqrt() function, Given a number N, the task is to find the square root of N without using sqrt() function. If i * i = n, then print i as n is a perfect square whose square root is i. i – 1 and i and we can use Binary Search algorithm to find the square root. If mid itself is the square root,. // return mid. if ((mul == n) ||. (Math.Abs(mul - n) < 0.00001)). Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

The stuff that you try to do is called numerical methods. The most rudimentary/easy numerical method for equation solving (yes, you solve an equation x^2 = a here) is a Newtons method.

All you do is iterate this equation:

In your case f(x) = x^2 - a and therefore f'(x) = 2x.

This will allow you to find a square root of any number with any precision. It is not hard to add a step which approximate the solution to an integer and verifies whether sol^2 == a

Babylonian method for square root, Babylonian method for square root. Algorithm: This method can be derived from 1 Start with an arbitrary positive start value x (the closer to the root, the better). which are not perfect. squares*/. unsigned int squareRoot( int n). {. int x = n; Please write comments if you find any bug in the above program/algorithm, or if  Better algorithms for finding the root of x² - n = 0 are : Halving intervals to search for the root. This is called the bisection method. Even faster would be Newton's method: follow the tangent line on your current approximated root, to find a closer approximation. Note the pseudo code on the linked wiki pages.

Separates Newton's method from the function to approximate. Can be used to find other roots.

function newton(f, fPrime, tolerance) {
  var x, first;

  return function iterate(n) {
    if (!first) { x = n; first = 1; }

    var fn = f(x);

    var deltaX = fn(n) / fPrime(n);
    if (deltaX > tolerance) {
      return iterate(n - deltaX)
    }

    first = 0;
    return n;
  }
}


function f(n) { 
  return  function(x) { 
    if(n < 0) throw n + ' is outside the domain of sqrt()';
    return x*x - n;
  };
}

function fPrime(x) {
  return 2*x;
}


var sqrt = newton(f, fPrime, .00000001)
console.log(sqrt(2))
console.log(sqrt(9))
console.log(sqrt(64))

Perfect square in javascript - JavaScript, else if (age % Math.sqrt(age) === 0) { console.log("Perfect sqaure!"); } else { console.log("Wow you are " + age + " years old!"); } have been  If we want to calculate square root, we can use Math.sqrt() method. It is simple. Now do you know how to write such a method by yourself? Here is the equation you need. The first sqrt number should be the input number / 2. Using the equation, we can come up with a Java Square Root method by ourselves.

Binary search will work best.

let number = 29;
let res = 0;

console.log((square_root_binary(number)));
function square_root_binary(number){

    if (number == 0 || number == 1)  
       return number;

    let start = 0;
    let end = number;


    while(start <= end){

        let mid = ( start + end ) / 2;

        mid = Math.floor(mid);

        if(mid * mid == number){
            return mid;
        }

        if(mid * mid < number){
            start = mid + 1;
            res = mid;
        }
        else{
            end = mid - 1;
        }
    }

    return res;
}

How to write a program for finding the square root of a number , How do I write a program for finding the square root of a number without using the sqrt the square root of that number based on knowing the perfect squares? Here's the pseudo-code for the algorithm, starting with guess as 1,which you can get the square root of any number with help of Math.sqrt function javascript. How to Check Valid Perfect Square without Sqrt Function? Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt.

function squareRoot(n){
    var avg=(a,b)=>(a+b)/2,c=5,b;
    for(let i=0;i<20;i++){
        b=n/c;
        c=avg(b,c);
    }
    return c;
}

This will return the square root by repeatedly finding the average.

var result1 = squareRoot(25) //5
var result2 = squareRoot(100) //10
var result3 = squareRoot(15) //3.872983346207417

JSFiddle: https://jsfiddle.net/L5bytmoz/12/

JavaScript sqrt() Method, Math.sqrt(9);. Try it Yourself ». More "Try it Yourself" examples below. Definition and Usage. The sqrt() method returns the square root of a number. Because all perfect squares are sums of consecutive odd numbers: 1 = 1; 4 = 1 + 3; 9 = 1 + 3 + 5; 16 = 1 + 3 + 5 + 7; and so on. Your program attempts to subtract consecutive odd numbers from n, and see if it drops to zero or goes negative.

How to get the square root of a number in JavaScript?, To get the square root, use the Math.sqrt() method. This method returns the square root of a number. If the value of a number is negative, sqrt  Algorithm starts with 1 as first approximation for square root value. Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt (x), it will be the same. If y > sqrt (x), then x/y < sqrt (x) by about the same amount. In other words, it will converge very fast.

Calculate square root without a calculator, Explanation of three ways to find square roots without calculator, including the then square the guess, and depending how close you got, improve your guess. I vaguely recall learning the square root algorithm in K-12, but frankly, I see no value For square roots of perfect squares, no estimation would even be needed. how to calculate a square root :there are a multitude of operations that have an inverse or opposite operation. √n : is the number that gives n when multiplied by itself

How to decide if a given number will have integer square-root or not?, If an integer has square-root, then the last digit is either 0 (even number of zeros) I do not know a reference for a theoretical analysis of this algorithm. problem and we could not find an accurate mathematical description of "how to verify if thread given by Joseph Issac, the solutions of the problem are perfect squares. Given a number N, the task is to find the square root of N without using sqrt () function. Output: 1.73205. Output: 1.58114. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Start iterating from i = 1. If i * i = n, then print i as n is a perfect square whose square root is i.

Comments
  • What happens for squareroot(65)? Hint: nothing good.
  • ` I need to know how to improve its performance` what makes you think it doesn't have "good" performance? What are your benchmarks? People talk in general terms of performance but that's all it is general terms. What are you trying to improve?
  • var squareroot = Math.sqrt; there I did it for you
  • It seems I'm iterating over every possible number and that might be unnecessary
  • There are pretty many quite sophisticated algorithms to do this. You won't benefit from most of these as a learner, though.
  • @user5680735 this runs in O(n) if you change the for a little to scan the bits from MSB to LSB you will get binary search which runs in O(log(n)) instead. the code will change just slightly see my linked QA's I commented your Question with
  • @Spektre, where did you found a sqrt function usage? I've changed O(sqrt(number)) notation not to confuse you.
  • Sorry my bad... You gave it right. I still did not have my tea in the morning ... I saw it in O(sqrt(number)) miss the O :)
  • @LeoDutra you are right, 2 is not a square root of 5. But OP was interested in finding square roots of square numbers. 5 is not a square number.
  • Thanks for your answer. But what is a? I found in preudocode on Wikipedia Newton's method page that f = @(x) x^2 - 2 %The function whose root we are trying to find and can't understand why ... - 2 here
  • @Mikhail a is the number which square root you are trying to find. So if you want to find a sqrt(15), then a=15
  • can you explain your function?