GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — javascript-algorithms/src/algorithms/math/fast-powering at master · willsilence/javascript-algorithms

Expand file tree

/

fast-powering

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
 
 
/

fast-powering

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
__test__
__test__
 
 
README.fr-FR.md
README.fr-FR.md
 
 
README.md
README.md
 
 
fastPowering.js
fastPowering.js
 
 

README.md

Outline

Fast Powering Algorithm

Read this in other languages: français.

The power of a number says how many times to use the number in a multiplication.

It is written as a small number to the right and above the base number.

Power

Naive Algorithm Complexity

How to find a raised to the power b?

We multiply a to itself, b times. That is, a^b = a * a * a * ... * a (b occurrences of a).

This operation will take O(n) time since we need to do multiplication operation exactly n times.

Fast Power Algorithm

Can we do better than naive algorithm does? Yes we may solve the task of powering in O(log(n)) time.

The algorithm uses divide and conquer approach to compute power. Currently the algorithm work for two positive integers X and Y.

The idea behind the algorithm is based on the fact that:

For even Y:

X^Y = X^(Y/2) * X^(Y/2)

For odd Y:

X^Y = X^(Y//2) * X^(Y//2) * X
where Y//2 is result of division of Y by 2 without reminder.

For example

2^4 = (2 * 2) * (2 * 2) = (2^2) * (2^2)
2^5 = (2 * 2) * (2 * 2) * 2 = (2^2) * (2^2) * (2)

Now, since on each step we need to compute the same X^(Y/2) power twice we may optimise it by saving it to some intermediate variable to avoid its duplicate calculation.

Time Complexity

Since each iteration we split the power by half then we will call function recursively log(n) times. This the time complexity of the algorithm is reduced to:

O(log(n))

References

  • YouTube
  • Wikipedia
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.