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.
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
分析:
欧拉定理 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); 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 ",V[i],n); break; } } } } return 0; }