time-to-botec

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

gcd.js (1819B)


      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 // MODULES //
     22 
     23 var isnan = require( './../../../../base/assert/is-nan' );
     24 var isInteger = require( './../../../../base/assert/is-integer' );
     25 var PINF = require( '@stdlib/constants/float64/pinf' );
     26 var NINF = require( '@stdlib/constants/float64/ninf' );
     27 var INT32_MAX = require( '@stdlib/constants/int32/max' );
     28 var bitwise = require( './bitwise_binary_gcd.js' );
     29 var largeIntegers = require( './binary_gcd.js' );
     30 
     31 
     32 // MAIN //
     33 
     34 /**
     35 * Computes the greatest common divisor (gcd).
     36 *
     37 * @param {integer} a - integer
     38 * @param {integer} b - integer
     39 * @returns {integer} greatest common divisor
     40 *
     41 * @example
     42 * var v = gcd( 48, 18 );
     43 * // returns 6
     44 *
     45 * @example
     46 * var v = gcd( 3.14, 18 );
     47 * // returns NaN
     48 *
     49 * @example
     50 * var v = gcd( NaN, 18 );
     51 * // returns NaN
     52 */
     53 function gcd( a, b ) {
     54 	if ( isnan( a ) || isnan( b ) ) {
     55 		return NaN;
     56 	}
     57 	if (
     58 		a === PINF ||
     59 		b === PINF ||
     60 		a === NINF ||
     61 		b === NINF
     62 	) {
     63 		return NaN;
     64 	}
     65 	if ( !( isInteger( a ) && isInteger( b ) ) ) {
     66 		return NaN;
     67 	}
     68 	if ( a < 0 ) {
     69 		a = -a;
     70 	}
     71 	if ( b < 0 ) {
     72 		b = -b;
     73 	}
     74 	if ( a <= INT32_MAX && b <= INT32_MAX ) {
     75 		return bitwise( a, b );
     76 	}
     77 	return largeIntegers( a, b );
     78 }
     79 
     80 
     81 // EXPORTS //
     82 
     83 module.exports = gcd;