-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmoduli-number.js
50 lines (36 loc) · 1.64 KB
/
moduli-number.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
/*
A number system with moduli is defined by a vector of k moduli, [m1,m2, ···,mk].
The moduli must be pairwise co-prime, which means that, for any pair of moduli, the only common factor is 1.
In such a system each number n is represented by a string "-x1--x2-- ... --xk-" of its residues, one for each modulus. The product m1 ... mk must be greater than the given number n which is to be converted in the moduli number system.
For example, if we use the system [2, 3, 5] the number n = 11 is represented by "-1--2--1-",
the number n = 23 by "-1--2--3-". If we use the system [8, 7, 5, 3] the number n = 187 becomes "-3--5--2--1-".
You will be given a number n (n >= 0) and a system S = [m1,m2, ···,mk] and you will return a string "-x1--x2-- ...--xk-" representing the number n in the system S.
If the moduli are not pairwise co-prime or if the product m1 ... mk is not greater than n, return "Not applicable".
Examples:
fromNb2Str(11 [2,3,5]) -> "-1--2--1-"
fromNb2Str(6, [2, 3, 4]) -> "Not applicable", since 2 and 4 are not coprime
fromNb2Str(7, [2, 3]) -> "Not applicable" since 2 * 3 < 7
*/
function fromNb2Str(n,sys) {
if (sys.reduce(function(p,c) { return p * c; }) < n) return 'Not applicable';
var min = Math.min.apply(null, sys);
for(var i = 2, k; i <= min; i++) {
k = 0;
for(var j = 0; j < sys.length; j++) {
if (sys[j] % i === 0) {
k++;
}
}
if (k > 1) return 'Not applicable';
}
return '-' + sys.map(function(i) { return n % i; }).join('--') + '-';
}
fromNb2Str(187, [8, 7, 5, 3]);
// -3--5--2--1-
/*
Can be optimized by using
function gcd(a, b) {
if(!b) return a;
return gcd(b, a % b);
}
*/