Reading is a way to acquire knowledge and wisdom, as well as an important means to broaden thinking and cultivate personal qualities.
01 | 👑 题目描述
设计一个高效的算法计算 X^Y mod N
02 | 🔋 解题思路
计算 X^Y mod N 的问题可以使用快速幂算法来解决,其思路是将指数 Y 进行二进制拆分,以降低计算量。
算法流程如下:
- 初始化结果 res 为 1。
- 将底数 X 对 N 取模,得到 base。
- 对指数 Y 进行二进制拆分,从最低位开始判断:
- 若当前位为 1,将 res 乘以 base 并对 N 取模,并更新 res。
- 将 base 自乘并对 N 取模,更新 base。
- 将 Y 右移一位(相当于除以 2),继续进行第 3 步的判断,直到 Y 变为 0。
- 返回最终结果 res。
时间 && 空间复杂度
- 时间复杂度:** O(log Y),其中 Y 是指数**
该算法通过二进制拆分将指数 Y 降低为 log Y 级别的复杂度,因此能够高效地计算 X^Y mod N 的结果 - 空间复杂度:O(1)
这个算法的空间复杂度为 O(1),因为除了存储输入参数和结果之外,没有使用额外的数据结构或空间。无论输入的 X、Y、N 的大小如何变化,算法所占用的额外空间始终保持不变。因此,空间复杂度为常数级别 O(1)。
03 | 🧢 代码片段
#include <iostream>
typedef long long ll;
ll modularExponentiation(ll x, ll y, ll n) {
ll res = 1;
x %= n;
while (y > 0) {
if (y & 1) {
res = (res * x) % n;
}
x = (x * x) % n;
y >>= 1;
}
return res;
}
int main() {
ll x = 2;
ll y = 10;
ll n = 1000000007;
ll result = modularExponentiation(x, y, n);
std::cout << x << "^" << y << " mod " << n << " = " << result << std::endl;
return 0;
}