@stdlib/math-base-special-gcd
Version:
Compute the greatest common divisor (gcd).
84 lines (74 loc) • 1.82 kB
JavaScript
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
;
// MODULES //
var isnan = require( '@stdlib/math-base-assert-is-nan' );
var isInteger = require( '@stdlib/math-base-assert-is-integer' );
var PINF = require( '@stdlib/constants-float64-pinf' );
var NINF = require( '@stdlib/constants-float64-ninf' );
var INT32_MAX = require( '@stdlib/constants-int32-max' );
var bitwise = require( './bitwise_binary_gcd.js' );
var largeIntegers = require( './binary_gcd.js' );
// MAIN //
/**
* Computes the greatest common divisor (gcd).
*
* @param {integer} a - integer
* @param {integer} b - integer
* @returns {integer} greatest common divisor
*
* @example
* var v = gcd( 48, 18 );
* // returns 6
*
* @example
* var v = gcd( 3.14, 18 );
* // returns NaN
*
* @example
* var v = gcd( NaN, 18 );
* // returns NaN
*/
function gcd( a, b ) {
if ( isnan( a ) || isnan( b ) ) {
return NaN;
}
if (
a === PINF ||
b === PINF ||
a === NINF ||
b === NINF
) {
return NaN;
}
if ( !( isInteger( a ) && isInteger( b ) ) ) {
return NaN;
}
if ( a < 0 ) {
a = -a;
}
if ( b < 0 ) {
b = -b;
}
if ( a <= INT32_MAX && b <= INT32_MAX ) {
return bitwise( a, b );
}
return largeIntegers( a, b );
}
// EXPORTS //
module.exports = gcd;