1 Star 0 Fork 79

zhizou/javascript-algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

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

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/zhizous/javascript-algorithms.git
git@gitee.com:zhizous/javascript-algorithms.git
zhizous
javascript-algorithms
javascript-algorithms
master

搜索帮助