File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @function lcm
3+ * @description Compute the least common multiple (LCM) of two integers.
4+ * @param {number } a - first integer
5+ * @param {number } b - second integer
6+ * @return {number } LCM of a and b
7+ * @example lcm(4,6) -> 12
8+ * @example lcm(7,3) -> 21
9+ */
10+ const gcd = ( x , y ) => {
11+ let a = Math . abs ( x )
12+ let b = Math . abs ( y )
13+ if ( Number . isNaN ( a ) || Number . isNaN ( b ) ) throw new TypeError ( 'Argument is NaN - Not a Number' )
14+ while ( b !== 0 ) {
15+ const t = a % b
16+ a = b
17+ b = t
18+ }
19+ return a
20+ }
21+
22+ const lcm = ( a , b ) => {
23+ const na = Number ( a )
24+ const nb = Number ( b )
25+
26+ if ( Number . isNaN ( na ) || Number . isNaN ( nb ) || typeof a === 'object' || typeof b === 'object' ) {
27+ throw new TypeError ( 'Argument is NaN - Not a Number' )
28+ }
29+
30+ if ( na === 0 || nb === 0 ) return 0
31+
32+ // lcm(a,b) = |a * b| / gcd(a,b)
33+ return Math . abs ( ( na / gcd ( na , nb ) ) * nb )
34+ }
35+
36+ export { lcm }
Original file line number Diff line number Diff line change 1+ import { describe , it , expect } from 'vitest'
2+ import { lcm } from '../LCM'
3+
4+ describe ( 'lcm()' , ( ) => {
5+ it ( 'returns 0 when either argument is 0' , ( ) => {
6+ expect ( lcm ( 0 , 5 ) ) . toBe ( 0 )
7+ expect ( lcm ( 7 , 0 ) ) . toBe ( 0 )
8+ } )
9+
10+ it ( 'computes LCM for positive integers' , ( ) => {
11+ expect ( lcm ( 4 , 6 ) ) . toBe ( 12 )
12+ expect ( lcm ( 7 , 3 ) ) . toBe ( 21 )
13+ expect ( lcm ( 21 , 6 ) ) . toBe ( 42 )
14+ } )
15+
16+ it ( 'computes LCM when inputs are negative' , ( ) => {
17+ expect ( lcm ( - 4 , 6 ) ) . toBe ( 12 )
18+ expect ( lcm ( 4 , - 6 ) ) . toBe ( 12 )
19+ expect ( lcm ( - 4 , - 6 ) ) . toBe ( 12 )
20+ } )
21+
22+ it ( 'throws for non-numeric inputs' , ( ) => {
23+ // @ts -ignore
24+ expect ( ( ) => lcm ( 'a' , 5 ) ) . toThrow ( )
25+ // @ts -ignore
26+ expect ( ( ) => lcm ( 4 , { } ) ) . toThrow ( )
27+ } )
28+ } )
You can’t perform that action at this time.
0 commit comments