Hdu 1395 2^x mod n = 1 取模運算
阿新 • • 發佈:2018-11-01
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
當n=1||n為偶數時,一定不存在解...
當n為奇數時,一定存在解....
然後用最普通的累成取模就可以過.....
程式碼如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; int n; int gcd (int a,int b) { return b==0? a:gcd(b,a%b); } int main() { while (scanf("%d",&n)!=EOF) { if(n==1||n%2==0) printf("2^? mod %d = 1\n",n); else { int ans=1,m=2; while (m%n!=1) { m=(m*2)%n; ans++; } printf("2^%d mod %d = 1\n",ans,n); } } return 0; }