您的位置:首页 > 其它

简单数论问题

2014-07-20 19:56 204 查看
Problem Description
Given two positive integers a and N, satisfaing gcd(a,N)=1, please find the smallest positive integer x with a^x≡1(mod N).
Input
First is an integer T, indicating the number of test cases. T<3001.
Each of following T lines contains two positive integer a and N, separated by a space. a<N<=1000000.
Output
For each test case print one line containing the value of x.
Sample Input
2
2 3
3 5
Sample Output
2
4
//题意:求最小的x使 a^x % n = 1.(注意:用欧拉定理求的x不一定是最小的,有的还需要求要去除因子.)
//标程:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
const int Max = 1000010;
int prime[Max], phi[Max];
void euler()   //求欧拉函数值;
{
prime[0] = prime[1] = 0;
for(int i = 2;i <= Max; i ++)  prime[i]=1;
for(int i = 2; i*i <= Max; i ++)
if(prime[i])
for(int j=i*i;j<=Max;j+=i)
prime[j]=0;
for(int i=1;i<=Max;i++)
phi[i]=i;
for(int i=2;i<=Max;i++)
if(prime[i])
for(int j = i; j <= Max; j += i)
phi[j] = phi[j]/i * (i-1);
}
int Mod(int a, int b, int c)
{
int ans = 1;
long long aa = a;
while(b)
{
if (b % 2)  ans = ans * aa % c;
aa = aa * aa % c;
b /= 2;
}
return ans;
}
int main()
{
//   freopen("a.txt","r",stdin);
//   freopen("b.txt","w",stdout);
euler();
int t, a, n;
cin >> t;
while(t --)
{
cin >> a >> n;
int sn = (int)sqrt(phi
), ans = n;
for(int i = 1; i <= sn; i++)
{
if (phi
% i == 0)
{
if (Mod(a, i, n) == 1 && ans > i)
ans = i;
if (Mod(a, phi
/ i, n) == 1 && ans > phi
/ i)
ans = phi
/ i;
}
}
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: