Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ideas for improvement #1

Open
ghost opened this issue Mar 14, 2019 · 0 comments
Open

ideas for improvement #1

ghost opened this issue Mar 14, 2019 · 0 comments

Comments

@ghost
Copy link

ghost commented Mar 14, 2019

I took a look at the source code and found some places to improve it and therefore increase efficiency and reduce runtime. BTW: Why is the content of the complete main.js file shifted to the right?

gcd:

  • to parse the arguments into integers and to check if both numbers are NaN or negative is only necessary once, at the beginning
  • instead of checking for negative number or zero simply use Math.abs
    --> outsourcing the actual implementation of the Euclidean algorithm
    --> BETTER: use imperative implementation instead of recursive
  • Code:
function gcd (m, n) {
  m = Math.abs(parseInt(m, 10));
  n = Math.abs(parseInt(n, 10));

  // NaN
  if (isNaN(m) || isNaN(n)) {
    throw new Error("Invalid arguments.");  
  }

  // Euclidean algorithm
  while (n != 0) {
    let t = n;
    n = m % n;
    m = t;
  }

  return m;
}
  • improved readability
  • should reduce runtime

gcdExtended:

  • see gcd

factorize:

  • avoid loop without break-condition to avoid mistakes and infinite loops
    --> use m * m <= n as loop-break-condition
    --> add factors.push(n); return factors; at end

Hope i could help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants