forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindLcm.js
More file actions
Latest commit
53 lines (41 loc) · 1.35 KB
/
Copy pathFindLcm.js
File metadata and controls
53 lines (41 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
author: PatOnTheBack
license: GPL-3.0 or later
Modified from:
https://github.com/TheAlgorithms/Python/blob/master/maths/findLcm.py
More about LCM:
https://en.wikipedia.org/wiki/Least_common_multiple
*/
'use strict'
import{findHCF}from'./FindHcf'
// Find the LCM of two numbers.
constfindLcm=(num1,num2)=>{
// If the input numbers are less than 1 return an error message.
if(num1<1||num2<1){
throwError('Numbers must be positive.')
}
// If the input numbers are not integers return an error message.
if(num1!==Math.round(num1)||num2!==Math.round(num2)){
throwError('Numbers must be whole.')
}
// Get the larger number between the two
constmaxNum=Math.max(num1,num2)
letlcm=maxNum
while(true){
if(lcm%num1===0&&lcm%num2===0)returnlcm
lcm+=maxNum
}
}
// Typically, but not always, more efficient
constfindLcmWithHcf=(num1,num2)=>{
// If the input numbers are less than 1 return an error message.
if(num1<1||num2<1){
throwError('Numbers must be positive.')
}
// If the input numbers are not integers return an error message.
if(num1!==Math.round(num1)||num2!==Math.round(num2)){
throwError('Numbers must be whole.')
}
return(num1*num2)/findHCF(num1,num2)
}
export{findLcm,findLcmWithHcf}