HDU 5478 Can you find it(快速幂)
Problem Description
Given a prime number C(1≤C≤2×105), and three integers k1, b1, k2 (1≤k1,k2,b1≤109). Please find all pairs (a, b) which satisfied the equation ak1⋅n+b1+ bk2⋅n−k2+1 = 0 (mod C)(n = 1, 2, 3, ...).
Input
There are multiple test cases (no more than 30). For each test, a single line contains four integers C, k1, b1, k2.
Output
First, please output "Case #k: ", k is the number of test case. See sample output for more detail.
Please output all pairs (a, b) in lexicographical order. (1≤a,b<C). If there is not a pair (a, b), please output -1.
Please output all pairs (a, b) in lexicographical order. (1≤a,b<C). If there is not a pair (a, b), please output -1.
Sample Input
23 1 1 2
Sample Output
Case #1:
1 22
Source
没做出的主要原因在于没有想到化简式子的方法,快速幂还是很容易就想到的,但是以前并没有用过这种方法,主要是题意没有理解好,把n看的太重要,其实题意就是告诉你n=1,2...的时候肯定成立,并不是选其中一个n成立!!!!那么就可以只取1,2来进行计算。
n=1时,ak1+b1+ b = 0 (mod C)------------------①
n=2时,a2*k1+b1+ bk2+1 = 0 (mod C)----------②
①*ak1 ,等式仍成立,a2*k1+b1+ak1 *b = 0 (mod C)-------------③
由方程②=③,可推出 :ak1 (mod C) = bk2 (mod C)---------------*
遍历a:1~c-1,利用快速幂从①计算出b,再利用快速幂计算*式等号两边,比较是否相等。
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 #include<queue> 5 #include<stack> 6 #include<math.h> 7 #include<vector> 8 #include<map> 9 #include<set> 10 #include<stdlib.h> 11 #include<cmath> 12 #include<string> 13 #include<algorithm> 14 #include<iostream> 15 #define exp 1e-10 16 17 using namespace std; 18 19 __int64 Quick_Mod(int a, int b, int m) 20 { 21 __int64 res = 1,term = a % m; 22 while(b) 23 { 24 if(b & 1) res = (res * term) % m; 25 term = (term * term) % m; 26 b >>= 1; 27 } 28 return res%m; 29 } 30 31 int main() 32 { 33 int c,k1,b1,k2,t; 34 int f; 35 t=1; 36 while(cin>>c>>k1>>b1>>k2) 37 { 38 cout<<"Case #"<<t++<<":"<<endl; 39 f=0; 40 int a,b,x,y; 41 for(a=1;a<c;++a) 42 { 43 x=Quick_Mod(a,k1,c); 44 b=c-Quick_Mod(a,k1+b1,c); 45 y=Quick_Mod(b,k2,c); 46 if(x==y) 47 { 48 f=1; 49 cout<<a<<" "<<b<<endl; 50 } 51 } 52 if(f==0) 53 { 54 cout<<-1<<endl; 55 } 56 57 } 58 59 return 0; 60 }