简单数论问题

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[n]), ans = n;
        for(int i = 1; i <= sn; i++)
        {
            if (phi[n] % i == 0)
            {
                if (Mod(a, i, n) == 1 && ans > i)
                    ans = i;
                if (Mod(a, phi[n] / i, n) == 1 && ans > phi[n] / i)
                    ans = phi[n] / i;
             }
        }
        cout << ans << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值