#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
unsigned long gcd(unsigned long n,unsigned long r)
{
if(!r) return n;
return gcd(r,n%r);
}
int cf(unsigned long n)
{
double i;
for(i=2;i<=ceil(log(n)/log(2));i++)
{
if(pow(n,1/i)-floor(pow(n,1/i))==0)
{
return 1;
break;
}
}
return 0;
}
int test(unsigned long r)
{
unsigned long i=2;
while(i<=sqrt(r))
{
if(i%r!=0)
i++;
else
return 0;
}
return 1;
}
unsigned long syz(unsigned long r)
{
unsigned long i=2;
while(i<=sqrt(r))
{
if(i%r!=0)
i++;
else
r=r/i;
}
return r;
}
unsigned long pf(unsigned long a,unsigned long b,unsigned long r)
{
unsigned long z=1;
while(b!=0)
{
if(b%2==0)
{
b=b/2;
a=(a*a)%r;
}
else
{
b=b-1;
z=(z*a)%r;
}
}
return z;
}
unsigned long mods(unsigned long n,unsigned long r,unsigned long a)
{
int x=5;
unsigned long f=1,g=x*a,y=n,h;
while(y!=0)
{
if(y%2==0)
{
y=y/2;
h=g*g;
g=h%(unsigned long)(pow(x,r)-1);
}
else
{
y=y-1;
h=f*g;
f=h%(unsigned long)(pow(x,r)-1);
}
}
return f;
}
int main()
{
unsigned long a=1;
int x=5;
unsigned long n;
printf("输入一个整数 n=");
scanf("%lu",&n);
if(n<2)
{
printf("请输入一个大于1的整数!\n");
exit(0);
}
else if(cf(n)==0)
{
unsigned long r=2;
while(r<n)
{
if(gcd(n,r)!=1)
{
printf("%lu是一个合数\n",n);
exit(0);
}
if(test(r)==1)
{
unsigned long q;
q=syz(r-1);
if(q>=4*sqrt(r)*(unsigned long)(log(n)/log(2))&&pf(n,(r-1)/q,r)!=1)
break;
}
r=r+1;
}
for(a=1;a<=2*sqrt(r)*((unsigned long)(log(n)/log(2)));a++)
{
if(mods(n,r,a)!=(((unsigned long)pow(x,n)-a)%((unsigned long)pow(x,r)-1)))
{
printf("%lu是一个素数\n",n);
break;
exit(0);
}
{
printf("%lu是一个合数\n",n);
break;
}
}
}
return 0;
}
判断素数算法
最新推荐文章于 2021-08-08 11:34:38 发布