trekhleb / trekhleb/javascript-algorithms
Should approach fastPowering this way?
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- JavaScript
- Sterne
- 197k
- Forks
- 31k
- PR-Merge-Kennzahlen
- Keine gemergten PRs in 30 T.
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
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.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript
- Bereich
- tooling
- Issue-Typ
- Refactoring
- Schwierigkeit
- 2/5
- Geschätzter Aufwand
- 1-3 Stunden
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 42/100