/
amicable.js
63 lines (54 loc) · 1.37 KB
/
amicable.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
57
58
59
60
61
62
63
function processData(input) {
//Enter your code here
const [count, ...args] = input.split('\r\n')
const numbers = args.filter(String)
// First, put numbers into object to ease the logic handling
const obj = Object.assign(
{},
...numbers.map((key) => ({
[key]: {
divisors: [], // just for info, can be deleted
sumOfDivisors: 0,
isAmicable: false,
},
}))
)
// Second, find a proper division on each input
for (let i = 0; i <= count; i++) {
const num = +numbers[i]
let j = 1
while (j <= num / 2) {
if (num % j === 0) {
obj[num].divisors.push(j)
obj[num].sumOfDivisors += j
}
j++
}
}
// Third, check it self against the sumOfDivisors
for (const key of Object.keys(obj)) {
const currentSumOfDivisors = obj[key].sumOfDivisors
let newSumOfDivisors = 0
let j = 1
while (j <= currentSumOfDivisors / 2) {
if (currentSumOfDivisors % j === 0) {
newSumOfDivisors += j
}
j++
}
if (+key === +newSumOfDivisors) {
obj[key].isAmicable = true
}
}
// Fourth, map the result
const result = []
for (const num of numbers) {
if (obj[num].isAmicable) {
result.push(`Yes, amicable with ${obj[num].sumOfDivisors}`)
} else {
result.push('No')
}
}
// Last, log the output
console.log(result.join('\r\n'))
}