-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgcd_hcf.js
More file actions
44 lines (44 loc) · 1.17 KB
/
gcd_hcf.js
File metadata and controls
44 lines (44 loc) · 1.17 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
// Time complexity = O(min(x, y))
function findGCD(x, y) {
// --------------------------------------------
// Approach 1 (Start)
// let gcd:number = 1;
// for (let i:number = 1; i <= Math.min(x, y); i++) {
// if(x%i == 0 && y%i == 0) {
// gcd = Math.max(gcd, i);
// }
// }
// return gcd;
// Approach 1 (End)
// --------------------------------------------
// --------------------------------------------
// Approach 2 (Start)
for (var i = Math.min(x, y); i >= 1; i--) {
if (x % i == 0 && y % i == 0) {
return i;
}
}
return 1;
// Approach 2 (End)
// --------------------------------------------
}
// Time complexity - O(logφ(min(x, y)))
// why φ because we are dividing by x or y. x and y are not constant they are fluctuating again and again
function findGCDUsingEuclidean(x, y) {
while (x > 0 && y > 0) {
if (x > y) {
x = x % y;
}
else {
y = y % x;
}
}
if (x === 0)
return y;
else
return x;
}
var x = 52;
var y = 10;
console.log(findGCD(x, y));
console.log(findGCDUsingEuclidean(x, y));