模幂运算

//一开始写错了是因为模幂运算溢出
#include <iostream>
#include<cmath>
#define mistakeP 0.0001
using namespace std;
bool Btest(int a,int n)
{int s=0;
 int t=n-1;
 do{
 s++;
 t=t/2;
 }while(t % 2!=1);
 //int x=((int)pow(a,t))%n;
 int x=1;
 for(int i=0;i<t;i++)
    x=x*a%n;

 if(x==1 || x==n-1)
    {return true;
    }
 for(int i=1;i<=s-1;i++)
    {x=x*x%n;
     if(x==n-1)
        return true;
    }
    return false;


}
bool MillRab(int n)
    {int a=rand()%(n-3)+2;//n need large than 3
    return Btest(a,n);

    }
bool repeatMillRab(int n,int k)
    {for(int i=0;i<k;i++)
        {if(MillRab(n)==false)
            return false;
        }
     return true;
    }
int printPrimes()
{   cout<<"2 3 ";
    int n=5;
    int count=0;
    while(n<10000)
        {if(repeatMillRab(n,(int)(log2(1.0/mistakeP)/2)))
            {cout<<n<<" ";
            if(n>100)
                count++;
            }
         n=n+2;
        }
    cout<<endl;
    return count;
}
bool judgePrime(int n)
    {for(int i=2;i<=(int)pow(n,0.5);i++)
        {if(n%i==0)
            return false;
        }
     return true;
    }
int accuratePrimes()
    {int count=0;
    for(int i=2;i<=10000;i++)
        {if(judgePrime(i))
            {cout<<i<<" ";
            if(i>100)
            count++;
            }
        }
     cout<<endl;
     return count;
    }
int main()
{cout<<"repeatMillRab:"<<endl;
int c1=printPrimes();
cout<<"accurate:"<<endl;
int c2=accuratePrimes();

cout<<endl;
cout<<"100~10000"<<"repeatMillRab: "<<c1<<"  accurate: "<<c2<<endl;

cout<<"deviation: "<<((float)(c2-c1))/c2<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值