Skip to content

Commit 3ef2d96

Browse files
committed
Added medium/linear_congruence
1 parent 14bff41 commit 3ef2d96

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

medium/linear_congruence.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Using the JavaScript language, have the function linearCongruence(str) read
3+
* the str parameter being passed which will be a linear congruence equation in
4+
* the form: "ax = b (mod m)" Your goal is to solve for x and return the number
5+
* of solutions to x. For example: if str is "32x = 8 (mod 4)" then your program
6+
* should return 4 because the answers to this equation can be either 0, 1, 2,
7+
* or 3.
8+
*
9+
* https://www.coderbyte.com/results/bhanson:Linear%20Congruence:JavaScript
10+
*
11+
* @param {string} str
12+
* @return {number}
13+
*/
14+
function linearCongruence(str) {
15+
// http://mathworld.wolfram.com/LinearCongruenceEquation.html
16+
17+
// parse 'ax = b (mod m)'
18+
const [, a, b, m] = str
19+
.match(/([\d]+)x[ ]+=[ ]+([\d]+)[ ]+\(mod ([\d]+)\)/)
20+
.map(Number);
21+
22+
const answers = [];
23+
24+
for (let i = 0; i < m; i++) {
25+
if ((a * i) % m === b % m) {
26+
answers.push(i);
27+
}
28+
}
29+
30+
return answers.length;
31+
}
32+
33+
module.exports = linearCongruence;

medium/linear_congruence.test.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const linearCongruence = require('./linear_congruence');
2+
3+
describe('linearCongruence()', () => {
4+
test('returns number of solutions to given linear congruence problem', () => {
5+
expect(linearCongruence('32x = 8 (mod 4)')).toBe(4);
6+
7+
expect(linearCongruence('12x = 5 (mod 2)')).toBe(0);
8+
9+
expect(linearCongruence('12x = 4 (mod 2)')).toBe(2);
10+
});
11+
12+
test('passes Coderbyte.com tests', () => {
13+
expect(linearCongruence('32x = 8 (mod 4)')).toBe(4);
14+
15+
expect(linearCongruence('12x = 5 (mod 2)')).toBe(0);
16+
17+
expect(linearCongruence('12x = 4 (mod 2)')).toBe(2);
18+
19+
expect(linearCongruence('1x = 1 (mod 2)')).toBe(1);
20+
21+
expect(linearCongruence('22x = 2 (mod 3)')).toBe(1);
22+
23+
expect(linearCongruence('222x = 5 (mod 2)')).toBe(0);
24+
25+
expect(linearCongruence('64x = 4 (mod 18)')).toBe(2);
26+
27+
expect(linearCongruence('64x = 4 (mod 16)')).toBe(0);
28+
29+
expect(linearCongruence('64x = 4 (mod 12)')).toBe(4);
30+
31+
expect(linearCongruence('124x = 12 (mod 12)')).toBe(4);
32+
});
33+
});

0 commit comments

Comments
 (0)