hdu-1395 2^x mod n = 1

2^x mod n = 1

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11542 Accepted Submission(s): 3577


Problem Description
Give a number n, find the minimum x(x>0) that satisfies 2^x mod n = 1.

Input
One positive integer on each line, the value of n.

Output
If the minimum x exists, print a line with 2^x mod n = 1.

Print 2^? mod n = 1 otherwise.

You should replace x and n with specific numbers.

Sample Input
  
  
2 5

Sample Output
  
  
2^? mod 2 = 1 2^4 mod 5 = 1

Author
MA, Xiao

Source

Recommend
Ignatius.L | We have carefully selected several similar problems for you: 2462 2421 1695 2466 2447
 
//跟上一题差不多。这题直接告诉底数为2  求最小的满足2^xmod n==1的最小x,解法是一样 的。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
const int Max = 1000010;
int prime[Max], phi[Max]; //保存所有值的欧拉函数
void fun() //求1到max所有值的欧拉函数
{
 int i,j;
    prime[0] = prime[1] = 0;
    for(i = 2;i <= Max; i ++)  prime[i]=1;
    for(i = 2; i*i <= Max; i ++)
        if(prime[i])
           for(int j=i*i;j<=Max;j+=i)
               prime[j]=0;
    for(i=1;i<=Max;i++)
         phi[i]=i;
    for(i=2;i<=Max;i++)
        if(prime[i])
          for(j = i; j <= Max; j += i)
              phi[j] = phi[j]/i * (i-1);
}
int Mod(int a, int b, int c) //快速幂取模  
{
    int ans = 1;
    __int64 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);
    fun();
    int a, n,i;
    while(scanf("%d",&n)!=EOF)
    {
        int sn = (int)sqrt(phi[n]), ans = n;  //在1-sn之间枚举n的欧拉函数的因子
        for(i = 1; i <= sn; i++) //在欧拉函数的所有因子中查找满足条件并且是最小的。
        {
            if (phi[n] % i == 0) //如果i是phi的因子  更新最小值
            {
                if (Mod(2, i, n) == 1 && ans > i)
                    ans = i;   
                if (Mod(2, phi[n] / i, n) == 1 && ans > phi[n] / i)
                    ans = phi[n] / i;
             }
        }
  if(ans==n) printf("2^? mod %d = 1\n",n);
  else printf("2^%d mod %d = 1\n",ans,n);
        //cout << ans << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值