-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum-by-factors.js
53 lines (41 loc) · 1.46 KB
/
sum-by-factors.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
// Given an array of positive or negative integers
// I= [i1,..,in]
// you have to produce a sorted array P of the form
// [ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...]
// P will be sorted by increasing order of the prime numbers. The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages.
// Example:
// I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]]
// [2, 3, 5] is the list of all prime factors of the elements of I, hence the result.
// Notes:
// It can happen that a sum is 0 if some numbers are negative!
// Example: I = [15, 30, -45] 5 divides 15, 30 and (-45) so 5 appears in the result, the sum of the numbers for which 5 is a factor is 0 so we have [5, 0] in the result amongst others.
function sumOfDivided(lst) {
let pL;
let primesObject = {};
lst.forEach(n => {
pL = formPrimes(n);
pL.forEach(p => {
if (!primesObject[p]) primesObject[p] = [];
primesObject[p].push(n);
})
});
const result = [];
for (let l in primesObject) {
result.push([parseInt(l), primesObject[l].reduce((a, b) => a + b, 0)])
}
return result;
}
// forming the list of distinct prime divisors of a number
function formPrimes(n) {
n = Math.abs(n);
let i = 2;
let primesList = new Set();
for (i; i <= n/i; i++){
while (n % i === 0) {
n=n/i;
primesList.add(i);
}
}
if (n > 1) primesList.add(n);
return Array.from(primesList);
}