我有这个递归函数来计算模数:
uint64_t fast_power(uint64_t k, uint64_t n, uint32_t m) {
uint64_t sum;
if (n == 0) {
return 1;
}
if ((n % 2) == 0) {
sum = fast_power(k, (n / 2), m) * fast_power(k, (n / 2), m);
return MOD(sum, m);
} else {
sum = k * (fast_power(k, (n - 1), m));
return MOD(sum, m);
}
}
如何使相同的函数使用迭代?这是我到目前为止所拥有的:
uint64_t iter_power(uint64_t k, uint64_t n, uint32_t m) {
uint64_t arr[n - 1];
uint64_t num;
for (int i = 1; i < n; i++) {
num = power(k, i);
arr[num] = MOD(arr[num], m);
}
return arr[num];
}