隨機算法 之模冪函數

在隨機素數測試算法中要用到模冪運算,在O(lgn)的時間內產生模冪結果是非常有用的。
在諸如RSA等算法中都要用到求a^n mod p的運算,例如費馬小定理(a^(n-1) mod n = 1,p是a的非素數因子)
及rsa算法用到的費馬定理的推廣(a^(y(n))mod n = 1,y(n)爲n的歐拉函數)等等都需要用到模冪運算,那麼
怎麼能快速的到模冪運算結果其實原理很簡單,這是我用english寫的,希望沒寫錯,呵呵
Basing on the two simple theories:
 1,(x*y)%z=((x%z)*(y%z))%z
 2,(x^y)%z=((x%z)^y)%z
To solve the y=(g^x)%p problem left shifting x until x become 0,compute g^x by computing
k=(g^(x/2)%p) and g^x=k*k or g^x=k*k*g 。so this algorithm is O(lgn) which is also linear。
This is a simple and recursive algorithm.
這是我寫的參考程序 (僅供參考)
class MMath{
 
 public:
  
 static int power(int g,int p,int n){

  int s,u;

  if(n==0)return 1;
  else {
   s = power(g,p,n>>1);
   u = s*s;
   if(n%2==0)
    return u%p;
   else
    return u*g%p;
  }
 }

 static bool prime_judge(int n){
  if(power(2,n,n-1)!=1)return false;
  else return true;
 }
}
另外附一個根據費馬定理寫的素數測試程序(會產生錯誤,僞素數如1387等)
MillerRabin測試還沒有想好怎麼寫程序呢。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章