題目連接:http://acm.timus.ru/problem.aspx?space=1&num=1204ios
題目描述:spa
x*x ≡ x (mod n) ,求解全部知足該式的x值,其中n爲兩個不一樣的素數的積,而且有x<n;code
那麼假設n=p*q,且 x mod n = x, 而後易獲得 x*x = a*n + x,則 x(x-1) = a*n, 則必有兩個解0和1blog
故剩餘狀況等價於求 a1*p + a2*q = 1的解,其中a1*a2=-a(a !=0 )ci
爲擴展的歐幾里得了,其中爲正的一項爲解,還有一個解即增一次便可,兩次則會超過n,故有且僅有4個解。get
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 using namespace std ; 5 6 const int MAXM = 100000 ; 7 int k, n ; 8 int prims[MAXM], totals ; 9 bool is_prim[MAXM] ; 10 11 void init(){ 12 memset(is_prim, true, sizeof(is_prim)) ; 13 totals = 0 ; 14 for( int i = 2; i < MAXM; i++ ){ 15 if( is_prim[i] ){ 16 for( int j = 2; j*i < MAXM; j++ ) is_prim[i*j] = false ; 17 prims[totals++] = i ; 18 } 19 } 20 } 21 22 void extGcd(int& x, int& y, int p, int q){ 23 if( q == 0 ){ 24 x = 1, y = 0 ; 25 return ; 26 } 27 extGcd(x, y, q, p%q) ; 28 int t = y ; 29 y = x - (p/q)*y ; 30 x = t ; 31 } 32 33 void solve(){ 34 cout << "0 1 " ; 35 int p, q ; 36 for( int i = 0; i < totals && prims[i]*prims[i] < n; i++ ){ 37 if( n % prims[i] == 0 ) p = prims[i], q = n / prims[i] ; 38 } 39 int x, y ; 40 extGcd(x, y, p, q) ; 41 if( x > 0 ){ 42 cout << x*p << " " << (y+p)*q << endl ; 43 }else{ 44 cout << y*q << " " << (x+q)*p << endl ; 45 } 46 } 47 48 int main(){ 49 //freopen("1234.txt", "r", stdin) ; 50 cin >> k ; 51 init() ; 52 while( k-- ){ 53 scanf("%d", &n) ; 54 solve() ; 55 } 56 return 0 ; 57 }