1. 程式人生 > >HDU 1395 2^x mod n = 1 (歐拉函數)

HDU 1395 2^x mod n = 1 (歐拉函數)

ear val clu pro ava http align 歐拉 similar

2^x mod n = 1

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


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 ZOJ Monthly, February 2003

Recommend Ignatius.L | We have carefully selected several similar problems for you: 2462 2421 2521 1695 2466 分析: 歐拉定理 1、初等數論中的歐拉定理:  對於互質的整數a和n,有a^φ(n) ≡ 1 (mod n) φ(n)為n的歐拉函數 如果我們設m為φ(n),那麽m可能不是最小的解,但是最小的解必然是m的因數 所以我們只需要判定m的因數即可 代碼如下:
#include <cstdio>
#include 
<iostream> #include <cstring> #include <vector> #include <algorithm> using namespace std; typedef long long ll; ll euler(ll n){ //返回euler(n) ll res=n,a=n; for(ll i=2;i*i<=a;i++){ if(a%i==0){ res=res/i*(i-1);//先進行除法是為了防止中間數據的溢出 while(a%i==0
) a/=i; } } if(a>1) res=res/a*(a-1); return res; } ll mi(ll b,ll n) { ll ans=1; ll a=2; while(b>0) { if(b&1)ans=ans*a%n; b=b/2; a=(a*a)%n; } return ans; } int main() { ll n,h; while(scanf("%lld",&n)!=EOF){ vector<ll>V; if(n%2==0||n==1) printf("2^? mod %lld = 1\n",n); else { ll m=euler(n); for(ll i=1;i*i<=m;i++) { if(m%i==0){ V.push_back(i); if(i!=m/i) V.push_back(m/i); } } sort(V.begin(),V.end()); for(ll i=0;i<V.size();i++) { if(mi(V[i],n)==1){ printf("2^%lld mod %lld = 1\n",V[i],n); break; } } } } return 0; }

HDU 1395 2^x mod n = 1 (歐拉函數)