Problem about GCD
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 262 Accepted Submission(s): 31
Problem Description
Given integer m. Find multiplication of all 1<=a<=m such gcd(a, m)=1 (coprime with m) modulo m.
Input
Input contains multiple tests, one test per line.
Last line contains -1, it should be skipped.
[Technical Specification]
m <= 10^18
Output
For each test please output result. One case per line. Less than 160 test cases.
Sample Input
1243 5 -1
Sample Output
0132 4
Source
思路:
首先有一个定理一个数m,对于所有小于m的数并与之互质的正整数的乘积x,x%m的结果不是1就是m-1,当m%2==0时,判断m/2;
当结果为m-1时,需要满足:
1、m只有1个质因子,即m只能表达成m=p^k; 其中p为素数,p为次方
2、m%4!=0 (不包括4)
由于m可以达到10^18次方,可以先用10^6以内的素数去试那个等式,如果没有找到,那么我们用Miller_Rabin算法测试m是不是素数。如果不是我们看m是不是完全平方 数,如果是并且m的平方根sqr是一个素数,那么结果为m-1。否则结果就是1。这里为什么用10^6内的素数去枚举呢?因为大于10^6的素数sqr,它的k不会超过2,所以可 以用平方判断。
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
using namespace std;
const int MAXN=1000002;
int cnt;
bool p[MAXN];
int prim[78498];
typedef __int64 LL;
//****************************************************************
// Miller_Rabin 算法进行素数测试
//速度快,而且可以判断 <2^63的数
//****************************************************************
const int S=20;//随机算法判定次数,S越大,判错概率越小
LL mult_mod(LL a,LL b,LL mod) //(a*b)%c a,b,c<2^63
{
a%=mod;
b%=mod;
LL ans=0;
while(b)
{
if(b&1)
{
ans=ans+a;
if(ans>=mod)
ans=ans-mod;
}
a=a<<1;
if(a>=mod) a=a-mod;
b=b>>1;
}
return ans;
}
LL pow_mod(LL a,LL b,LL mod) // a^b%mod
{
LL ans=1;
a=a%mod;
while(b)
{
if(b&1)
{
ans=mult_mod(ans,a,mod);
}
a=mult_mod(a,a,mod);
b=b>>1;
}
return ans;
}
//以a为基,n-1=x*2^t a^(n-1)=1(mod n) 验证n是不是合数
//一定是合数返回true,不一定返回false
bool check(LL a,LL n,LL x,LL t)
{
LL ret=pow_mod(a,x,n);
LL last=ret;
for(int i=1;i<=t;i++)
{
ret=mult_mod(ret,ret,n);
if(ret==1 && last!=1 && last!=n-1) return true;//合数
last=ret;
}
if(ret!=1) return true;
else return false;
}
// Miller_Rabin()算法素数判定
//是素数返回true.(可能是伪素数,但概率极小)
//合数返回false;
bool Miller_Rabin(LL n)
{
if(n<2)return false;
if(n==2) return true;
if( (n&1)==0) return false;//偶数
LL x=n-1;
LL t=0;
while( (x&1)==0 ) { x>>=1;t++;}
for(int i=0;i<S;i++)
{
LL a=rand()%(n-1)+1;//rand()需要stdlib.h头文件
if(check(a,n,x,t))
return false;//合数
}
return true;
}
void get_Prime()
{
cnt=0;
memset(p,1,sizeof(p));
int i,j;
p[0]=p[1]=0;
for(i=4;i<MAXN;i+=2)p[i]=0;
for(i=3;i<MAXN;i+=2)
{
if(p[i])
{
prim[cnt++]=i;
for(j=i+i;j<MAXN;j+=i)
p[j]=0;
}
}
//printf("%d\n",cnt);
}
bool solve(LL n)
{
if(n%4==0) return false;
if(n%2==0)n/=2;
int i;
for(i=0;i<cnt;i++)
{
LL x=n;
while(x%prim[i]==0)
x/=prim[i];
if(x==1) return true;
}
if(Miller_Rabin(n)) return true;
LL sqr=sqrt(n+0.0);
if(sqr*sqr==n && Miller_Rabin(sqr)) return true;
else return false;
}
int main()
{
LL m;
get_Prime();
while(scanf("%I64d",&m)!=EOF&&m!=-1)
{
if(solve(m) || m<6)printf("%I64d\n",m-1);
else printf("1\n");
}
return 0;
}