随机算法 之模幂函数

在随机素数测试算法中要用到模幂运算,在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测试还没有想好怎么写程序呢。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值