蒙哥马利模乘的优点在于减少了取模的次数(在大数的条件下)以及简化了
除法的复杂度(在2的k次幂的进制下除法仅需要进行左移操作)。模
幂运算是RSA
的核心算法,最直接地决定了RSA 算法的性能。
针对快速模幂运算这一课题,西方现代数学家提出了大量的解决方案,通常都是先将幂
模运算转化为乘模运算。
例如求D=C^15%N
由于:a*b % n = (a % n)*(b % n) % n
所以令:
C1 =C*C % N =C^2 % N
C2 =C1*C % N =C^3 % N
C3 =C2*C2 % N =C^6 % N
C4 =C3*C % N =C^7 % N
C5 =C4*C4 % N =C^14 % N
C6 =C5*C % N =C^15 % N
int Monto(int a,int b,int c)
{
int ans = 1;
while(b)
{
if(b&1)
ans = (ans*a)%c;
b>>=1;
a =(a*a)%c;
}
return ans;
}
例如HDU 1395
2^x mod n = 1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15203 Accepted Submission(s): 4699
Problem Description
Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.
Input
One positive integer on each line, the value of n.
Output
If the minimum x exists, print a line with 2^x mod n = 1.
Print 2^? mod n = 1 otherwise.
You should replace x and n with specific numbers.
Sample Input
2
5
Sample Output
2^? mod 2 = 1
2^4 mod 5 = 1
Author
MA, Xiao
#include
#include
#include
#include
using namespace std;
int Monto(int a,int b,int c)
{
int ans = 1;
while(b)
{
if(b&1)
ans = (ans*a)%c;
b>>=1;
a =(a*a)%c;
}
return ans;
}
int main()
{
int i,j,m,n,g,t,d,k;
int cnt,a,b,c;
while(cin>>n)
{
if(n%2==0 || n==1)
{
cout<<"2^? mod "<
虽然这样可以AC,但是,挺耗时的,还不如暴力的循环