time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

sqrt.js (1752B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // VARIABLES //
     22 
     23 // Set the second most significant bit: 00100000000000000000000000000000 => 1<<30 = 1073741824
     24 var BIT = 1073741824 >>> 0; // asm type annotation
     25 
     26 
     27 // MAIN //
     28 
     29 /**
     30 * Returns an integer square root.
     31 *
     32 * @param {uinteger32} x - input value
     33 * @returns {uinteger32} integer square root
     34 *
     35 * @example
     36 * var v = sqrt( 9 >>> 0 );
     37 * // returns 3
     38 *
     39 * @example
     40 * var v = sqrt( 2 >>> 0 );
     41 * // returns 1
     42 *
     43 * @example
     44 * var v = sqrt( 3 >>> 0 );
     45 * // returns 1
     46 *
     47 * @example
     48 * var v = sqrt( 0 >>> 0 );
     49 * // returns 0
     50 */
     51 function sqrt( x ) {
     52 	var root;
     53 	var bit;
     54 	var sum;
     55 	var y;
     56 
     57 	y = x >>> 0; // asm type annotation
     58 
     59 	root = 0 >>> 0; // asm type annotation
     60 	bit = BIT;
     61 
     62 	// `bit` should start as the highest power of `4` less than or equal to `x`:
     63 	while ( bit > y ) {
     64 		bit >>>= 2;
     65 	}
     66 	// Perform a digit-by-digit/abacus computation...
     67 	while ( bit !== 0 ) {
     68 		sum = ( root + bit ) >>> 0; // asm type annotation
     69 		root >>>= 1;
     70 		if ( x >= sum ) {
     71 			x -= sum;
     72 			root += bit;
     73 		}
     74 		bit >>>= 2;
     75 	}
     76 	// Note: `x` is the remainder
     77 
     78 	return root >>> 0; // asm type annotation
     79 }
     80 
     81 
     82 // EXPORTS //
     83 
     84 module.exports = sqrt;