码迷,mamicode.com
首页 > 其他好文 > 详细

hdu1395 2^x mod n = 1(欧拉函数)

时间:2018-12-07 21:24:18      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:答案   iostream   out   pre   code   bsp   ble   The   inpu   

2^x mod n = 1

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


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
 
题意:求满足2^x mod n = 1的最小x的值
 
直接暴力:
#include<iostream>
#include<math.h>
#define ll long long
using namespace std;
int main()
{
  ll n;
  while(~scanf("%lld",&n))
  {
    if(n==1||n%2==0)
      printf("2^? mod %d = 1\n",n );
    else
    {
      ll s=2;
      for(int i=2;;i++)
      {
        s=s*2%n;
        if(s==1)
        {
          printf("2^%d mod %d = 1\n",i,n );
          break;
        }
      }
      
    }
  }
  return 0;

}

 

欧拉函数:

 

先求欧拉函数的值phi(n),在对phi(n)进行因数分解,把phi(n)的因数存在数组e[i]里面

 

然后依次枚举e[i]的每一个数,同时判断这个数e[i]是否满足2e[i]%m==1,不断更新一个最小值,最后得到答案

 

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL __int64
LL t,e[1000];
LL mod;
LL euler_phi(LL n)//欧拉函数
{
    LL m=sqrt(n+0.5);
    LL ans=n,i;
    for(i=2;i<=m;i++)
    {
        if(n%i==0)
        {
            ans=ans/i*(i-1);
            while(n%i==0)n=n/i;
        }
    }
    if(n>1)ans=ans/n*(n-1);
    return ans;
}
void find(LL n)//找出m的所有因子
{
    LL i;
    e[t++]=n;
    for(i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            if(i*i==n)
                e[t++]=i;
            else
            {
                e[t++]=i;
                e[t++]=n/i;
            }
        }
    }
}
LL pows(LL a,LL b)
{
    LL s=1;
    while(b)
    {
        if(b&1)
            s=(s*a)%mod;
        a=(a*a)%mod;
        b=b>>1;
    }
    return s;
}
int main()
{
    LL n;
    while(cin>>n)
    {
        if(n%2==0||n==1)
            cout<<"2^? mod "<<n<<" = 1"<<endl;
        else
        {
            LL m,ans,i;
            m=euler_phi(n);
            t=0;
            find(m);
            sort(e,e+t);
            mod=n;
            for(i=0;i<t;i++)
            {
                if(pows(2,e[i])==1)
                {
                    ans=e[i];
                    break;
                }
            }
            cout<<"2^"<<ans<<" mod "<<n<<" = 1"<<endl;
        }
    }
    return 0;
}

 

hdu1395 2^x mod n = 1(欧拉函数)

标签:答案   iostream   out   pre   code   bsp   ble   The   inpu   

原文地址:https://www.cnblogs.com/-citywall123/p/10084259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!