Miller_rabin素数检验[HDU5391]

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<functional>
#include<string>
#include<algorithm>
#include<time.h>
#include<bitset>
void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);}
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
typedef int Int;
template <class T> inline void gmax(T &a,T b){if(b>a)a=b;}
template <class T> inline void gmin(T &a,T b){if(b<a)a=b;}
using namespace std;
int casenum,casei;
int n,Z;
//功能:通过概率学,快速判定一个LL级别的数是否为素数
LL mul(LL x,LL y,LL Z)//大数相乘取模
{
    LL tmp=x/(long double)Z*y+1e-3;
    return (x*y+Z-tmp*Z)%Z;
}
LL MUL(LL x,LL p,LL Z)
{
    LL y=1;
    while(p)
    {
        if(p&1)y=mul(y,x,Z);
        x=mul(x,x,Z);
        p>>=1;
    }
    return y;
}
bool miller_rabin(LL n)
{
    if(n<=1)return 0;
    if(n==2)return 1;
    if(n%2==0)return 0;
    LL p=n-1;
    srand(time(NULL));
    int TIMES=8;
    for(int i=1;i<=TIMES;i++)
    {
        LL x=rand()%(n-1)+1;
        if(MUL(x,p,n)!=1)return 0;
    }
    return 1;
}
void solve()
{
    scanf("%d",&n);
    if(n==4)printf("2\n");
    else
    {
        if(miller_rabin(n))printf("%d\n",n-1);
        else printf("%d\n",0);
    }
}
int main()
{
    scanf("%d",&casenum);
    for(casei=1;casei<=casenum;casei++)
    {
        solve();
    }
    return 0;
}
/* 【题意】 求(n-1)! mod n,n可达1e9。 【类型】 威尔逊定理 素数判定 【分析】 素数判定,这里提供一种方法——费马米勒素数检验法。 对于一个素数,必定满足—— x^(p-1)%p=1 对于任意的x(x<p)都成立 【时间复杂度&&优化】 【trick】 【数据】 Sample Input 2 3 10 Sample Output 2 0 */

你可能感兴趣的:(Miller_rabin素数检验[HDU5391])