Skip to content

Commit e1f69d6

Browse files
reduced pythagorean-triplet's time complexity from cubic to quadratic (#1324)
* reduced time complexity from cubic to quadratic * skipping large number test * [CI] Format code Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
1 parent 3f9b302 commit e1f69d6

File tree

1 file changed

+8
-3
lines changed
  • exercises/practice/pythagorean-triplet/.meta

1 file changed

+8
-3
lines changed

exercises/practice/pythagorean-triplet/.meta/proof.ci.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,17 @@ export function triplets({ minFactor, maxFactor, sum }) {
2727
};
2828

2929
const result = [];
30+
const squared_map = {};
31+
32+
for (let a = min; a < max; a += 1) {
33+
squared_map[a * a] = a;
34+
}
3035

3136
for (let a = min; a < max - 1; a += 1) {
3237
for (let b = a + 1; b < max; b += 1) {
33-
for (let c = b + 1; c <= max; c += 1) {
34-
const triplet = new Triplet(a, b, c);
35-
38+
const c = a * a + b * b;
39+
if (squared_map[c]) {
40+
const triplet = new Triplet(a, b, squared_map[c]);
3641
if (isDesired(triplet)) {
3742
result.push(triplet);
3843
}

0 commit comments

Comments
 (0)