0
\$\begingroup\$

This is my soloution for Project Euler: Problem 5 - Smallest multiple. Tell me if there is any way this could be improved:

main:
    for (var i = 1; true; i++) {
        for (var j = 1; j < 20; j++) {
            if (i % (j + 1) != 0) {
                continue main;
            }
        }
        document.write("Answer: " + i);
        break;
    }
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Project Euler problems are exercises in mathematics, not exercises in writing loops. If you continue writing brute-force solutions without understanding the mathematical principles behind the problem, you’re going to have a miserable time. \$\endgroup\$ Commented Sep 23, 2017 at 16:04
  • 1
    \$\begingroup\$ Please include a summary of the programming challenge task. \$\endgroup\$ Commented Sep 23, 2017 at 16:08
  • \$\begingroup\$ If you get the solution for the value 3 which is 6 the solution for the value 4 must be divisible by the solution for 3. For 4 it is 12, and again for 5 the solution must be divisible by the solution for 4, so the outer loop starts at answer for the previous answer and the value i steps up at the same rate. And the inner loop need only start at the half the integer value or nearest prime, and rather than count up count down. You can fly by pulling up on your boot straps, find the solution for 3 to find 4, 4 to find 5, 5 to find 6, and so on You can get to 20 in about 80+ total iterations \$\endgroup\$
    – Blindman67
    Commented Sep 23, 2017 at 16:30

1 Answer 1

3
\$\begingroup\$

Remarks

Your code solves this problem using very naive brute-force approach, which has polynomial complexity, i.e. \$O(n^c)\$. It's also pretty legacy and unusual, at least. Specifically, I'm talking i.a. about your use of label and document.write(). Moreover, it's a good habit to use identity operator wherever applicable.

Rewrite

Project Euler is a set of math-oriented programming challenges, and as such, authors of your problem sought for a solution that would use the least common multiple. Such solution has only linear complexity, i.e. \$O(n)\$, and it may be implemented in ES2015 (formerly ES6) as follows:

const lcm = n => {
  const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
  let result = 1;

  for (let i = 2; i <= n; i++) {
    result *= i / gcd(i, result);
  }
  return result;
};

console.log(lcm(20));
.as-console-wrapper { top: 0; }

Benchmark

Comparison of actual run times for various values of \$n\$ with regression curves and their \$R^2\$ (y-axis is in milliseconds per 30,000 runs).

Linear solution: Linear complexity solution

Your solution: Original solution

In this case, I run benchmark only for \$n<=8\$, because further ones took too long for my machine and patience.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.