lcm.js (1414B)
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 gcd = require( './../../../../base/special/gcd' ); 25 26 27 // MAIN // 28 29 /** 30 * Computes the least common multiple (lcm). 31 * 32 * @param {integer} a - integer 33 * @param {integer} b - integer 34 * @returns {integer} least common multiple 35 * 36 * @example 37 * var v = lcm( 21, 6 ); 38 * // returns 42 39 * 40 * @example 41 * var v = lcm( 3.14, 6 ); 42 * // returns NaN 43 * 44 * @example 45 * var v = lcm( NaN, 6 ); 46 * // returns NaN 47 */ 48 function lcm( a, b ) { 49 var d; 50 if ( a === 0 || b === 0 ) { 51 return 0; 52 } 53 if ( a < 0 ) { 54 a = -a; 55 } 56 if ( b < 0 ) { 57 b = -b; 58 } 59 // Note: we rely on `gcd` to perform further argument validation... 60 d = gcd( a, b ); 61 if ( isnan( d ) ) { 62 return d; 63 } 64 return (a/d) * b; 65 } 66 67 68 // EXPORTS // 69 70 module.exports = lcm;