用C++写给定三个正整数abp的值求a b p的值的代码
以下是用C++编写的求a b% p的值的代码:
#include <iostream>
int mod(int a, int b, int p) {
int result = 1;
while (b > 0) {
if (b % 2 == 1) {
result = (result * a) % p;
}
a = (a * a) % p;
b /= 2;
}
return result;
}
int main() {
int a, b, p;
std::cout << "Enter the values of a, b, and p: ";
std::cin >> a >> b >> p;
int result = mod(a, b, p);
std::cout << "a^b % p = " << result << std::endl;
return 0;
}
这段代码中,mod函数使用快速幂算法计算a^b % p的值。main函数用于获取输入的a、b和p的值,并调用mod函数计算结果。最后,将结果输出到控制台
原文地址: https://www.cveoy.top/t/topic/hXDC 著作权归作者所有。请勿转载和采集!