同步操作将从 Gitee 极速下载/javascript-algorithms 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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.
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.
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))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。