模p平方根算法實現

#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
int  power(int x,int y,int m)//cal x^y%m
{
	if(y==0)return 1%m;
	int  ret=x%m;
	for(int i=0;i<y-1;i++)
		ret=(ret*x)%m;
	return ret;
}
int normal_power(int a,int b)
{
	int ret=1;
	for(int i=0;i<b;i++)
		ret*=a;
	return ret;
}
int inverse(int a,int m)
{
	for(int i=1;i<m;i++)
		if((a*i)%m==1)return i;
	return true;
}
int getn(int p)
{
	for(int i=2;i<p;i++)
	{
		if(power(i,(p-1)/2,p)==p-1)
			return i;
	}
	return -1;
}
bool is_prime(int n)
{
	if(n==2)return false;
	double x=sqrt(n);
	for(int i=2;i<=x;i++)
		if(n%i==0)
			{
				cout<<i<<endl;
				return false;
			}
	return true;
}
int main()
{
	cout<<"This program can calculate the square root mode P of A if"<<endl;
	cout<<"there is a solution.The A and P should be input.and The P"<<endl;
	cout<<"must be an odd prime."<<endl<<endl;
	while(true)
	{
	//initialize to get a p s t n b 
	int a,p;
    cout<<"input the p please"<<endl;
    cin>>p;
    if(!is_prime(p))
	{
		cout<<"The p should be an odd prime try again please!"<<endl;
		continue;
	}
	cout<<"input the a please"<<endl;
	cin>>a;
	if(power(a,(p-1)/2,p)==p-1)
	{
		printf("a:%d p:%d\n",a,p);
		cout<<"No solution for this pair of number"<<endl;
		continue;
	}
	while(a<0)a+=p;
	while(a>p)a-=p;
	int n=getn(p);
	cout<<"The random n is "<<n<<endl;
	bool finish=false;
	int t=1;
	int s=p-1;
	while(!finish)
	{
		s=s/2;
		if(s%2) finish=true;
		else t+=1;
	}
	int b=power(n,s,p);
	int _a=inverse(a,p);
	printf("a:%d p:%d\nt:%d s:%d\nn:%d b:%d\n_a:%d\n",a,p,t,s,n,b,_a);
	int x[66];
	for(int i=0;i<66;i++)x[i]=0;
	x[t-1]=power(a,(s+1)/2,p);
	printf("x[%d]:%d\n",t-1,x[t-1]);	
	for(int i=1;i<=t-1;i++)
	{
		int judge=power((_a*x[t-i]*x[t-i])%p,normal_power(2,t-i-1),p);
		cout<<"the i is "<<i<<endl;
		cout<<"the under int is "<<(_a*x[t-i]*x[t-i])%p<<endl;
		cout<<"The times is "<<normal_power(2,t-i-1)<<endl;
		if(judge==1)
		{
			cout<<"The judge is "<<judge<<endl;
			x[t-i-1]=x[t-i];
		}
		else if(judge==p-1)
		{
			cout<<"The judge is -1"<<endl;
			x[t-i-1]=(power(b,normal_power(2,i-1),p)*x[t-i])%p;
		}
		printf("x[%d]:%d\n",t-i-1,x[t-i-1]);
		cout<<"------------------------------------"<<endl;
	}
	cout<<endl;
	cout<<"final solution:"<<x[0]<<endl<<endl;
}
}

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