-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathTree of Coprimes.js
56 lines (48 loc) · 1.08 KB
/
Tree of Coprimes.js
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
54
55
56
var getCoprimes = function(nums, edges) {
const node = {}
const ans = Array(nums.length).fill(null)
function addNode(f, t){
if(!node[f]){
node[f]=[]
}
node[f].push(t)
}
edges.forEach(([f, t])=>{
addNode(f, t)
addNode(t, f)
})
function gcd(a, b){
while(b) [a, b] = [b, a % b];
return a;
}
const map = []
for(let i=0; i<51; i++){
map[i]=[]
for(let j=0; j<51; j++){
map[i][j]= gcd(i,j)
}
}
let pi=-1
let path=Array(nums.length)
function check(v){
if(ans[v]!==null) return
ans[v] = -1
let a = nums[v]
for(let k=pi; k>=0; k--){
let b = nums[path[k]]
if(map[a][b]===1){
ans[v]=path[k]
break
}
}
if(node[v]) {
path[++pi]=v
node[v].forEach(child=>check(child))
pi--
}
}
for(let i=0; i<nums.length; i++){
check(i)
}
return ans
};