在 C++ 中求 (a^b)%m,其中 ‘a’ 非常大
在本教程中,我们将解决方程 (ab)%m,其中 a 是一个非常大的数字。
方程 (ab)%m=(a%m)*(a%m)...b_times。我们可以通过找到 a%m 的值,然后将其乘以 b 次来解决问题。
让我们看看解决问题的步骤。
初始化数字 a、b 和 m。
编写一个函数来查找 a%m。
将数字初始化为 0。
迭代字符串格式的数字。
将最后一位数字添加到数字中。
使用数字模 m 更新数字。
获取 a%m 的值。
编写一个循环,迭代 b 次。
将 a%m 相乘,并将结果模 m。
打印结果。
示例
让我们看看代码。
#include<bits/stdc++.h>
using namespace std;
unsigned int aModm(string str, unsigned int mod) {
unsigned int number = 0;
for (unsigned int i = 0; i < str.length(); i++) {
number = number * 10 + (str[i] - '0');
number %= mod;
}
return number;
}
unsigned int aPowerBmodM(string &a, unsigned int b, unsigned int m) {
unsigned int a_mod_m_result = aModm(a, m);
unsigned int final_result = 1;
for (unsigned int i = 0; i < b; i++) {
final_result = (final_result * a_mod_m_result) % m;
}
return final_result;
}
int main() {
string a = "123456789012345678901234567890123";
unsigned int b = 3, m = 7;
cout << aPowerBmodM(a, b, m) << endl;
return 0;
}输出
如果您执行上述程序,则将得到以下结果。
1
结论
如果您在本教程中有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP