Should approach fastPowering this way?

Aperta
#299 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
42/100
Tipo di issue
Refactoring
Chiarezza
Abbastanza chiara
Stato di attività
Ferma
Stack tecnologico
javascript
Ambito
tooling

Direzione di ricerca

Read fastPowering.js and compare its odd and even branches with the proposed shared multiplier calculation. Verify that the refactor preserves results for zero, even, and odd powers; done means the approach is accepted and the issue is closed.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
JavaScript
Stelle
197k
Fork
31k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di trekhleb/javascript-algorithms

Tutte le issue di trekhleb/javascript-algorithms

Issue simili

Altre issue su JavaScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.