C++ 程式實現模冪演算法
這是一個 C++ 程式,用於實現模冪演算法。
演算法
Begin function modular(): // Arguments: base, exp, mod. // Body of the function: initialize res = 1 while (exp > 0) if (exp mod 2 == 1) res= (res * base) % mod exp = exp left shift 1 base = (base * base) % mod return res. End
示例
#include <iostream>
using namespace std;
long long modular(long long base, long long exp, int mod) {
long long res = 1;
while (exp > 0) {
if (exp % 2 == 1)
res= (res * base) % mod;
exp = exp >> 1;
base = (base * base) % mod;
}
return res;
}
int main() {
long long b, e;
int mod;
cout<<"Enter Base : ";
cin>>b;
cout<<"Enter Exponent: ";
cin>>e;
cout<<"Enter Modular Value: ";
cin>>mod;
cout<<modular(b, e , mod);
return 0;
}輸出
Enter Base : 7 Enter Exponent: 6 Enter Modular Value: 26 25
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP