hdu 5391 素数测试

题意是求(n-1)!(mod n)的值


根据威尔逊定理:

(n1)!=1(modn)[n==prime]

所以如果是素数的话,直接等于-1,如果不是素数的话,显然答案应该为0,因为如果n是合数,显然1到n-1中一定会出现n的所有因数,注意要特判4,答案是2


#include 
#include 
#include 
using namespace std;
long long a[10]={0,2,3,5,7};
long long fast_pow( long long BASE, long long pr, long long mod ) {
    long long x = 1, y = BASE;
    while( pr ) {
        if( pr & 1 ) x = x * y % mod;
        pr >>= 1;
        y = y * y % mod;
    }
    return x % mod;
}
bool miller_rabin( int n ) {
    if( n == 2 || n == 3 || n == 5 || n == 7 ) return true;
    if( n % 2 == 0 ) return false;
    for( register int i = 1; i <= 4; i++ ){
        long long y = a[i];
        long long x = fast_pow( y, n-1, n );
        if( x != 1 ) return false;
    }
    return true;
}
int main() { int T;
    scanf( "%d", &T );
    while( T-- ) { int n;
        scanf( "%lld", &n );
        if( n == 4 ) { printf( "2\n" ); continue; }
        if( miller_rabin( n ) ) {
            printf( "%lld\n" , n - 1 );
        } else {
            printf( "0\n" );
        }
    }
    return 0;
}

你可能感兴趣的:(素数测试)