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

Should approach fastPowering this way? #299

Open
iAziz786 opened this issue Feb 6, 2019 · 1 comment
Open

Should approach fastPowering this way? #299

iAziz786 opened this issue Feb 6, 2019 · 1 comment

Comments

@iAziz786
Copy link

iAziz786 commented Feb 6, 2019

While learning about Fast Powering Algorithm, I notice that a minor tweak can be made to the fastPowering.js file.

In both of the cases whether the power is odd or event, calculated multiplier will be the same. So, we can calculate multiplier before the if clause and return the multiplication based on the nature of power.

export default function fastPowering(base, power) {
  if (power === 0) {
    // Anything that is raised to the power of zero is 1.
    return 1;
  }

  // multiplier will be same whether power is even or odd
  const multiplier = fastPowering(base, Math.floor(power / 2)); 
  if (power % 2 === 0) {
    // If the power is even...
    // we may recursively redefine the result via twice smaller powers:
    // x^8 = x^4 * x^4.
    return multiplier * multiplier;
  }

  // If the power is odd...
  // we may recursively redefine the result via twice smaller powers:
  // x^9 = x^4 * x^4 * x.
  return multiplier * multiplier * base;
}

@trekhleb Let me know your thoughts. And if you're okay with this implementation I can raise a PR.

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

2 participants
@iAziz786 and others